clang 20.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
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#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"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/STLForwardCompat.h"
53#include "llvm/ADT/ScopeExit.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include <map>
59#include <optional>
60#include <set>
61
62using namespace clang;
63
64//===----------------------------------------------------------------------===//
65// CheckDefaultArgumentVisitor
66//===----------------------------------------------------------------------===//
67
68namespace {
69/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
70/// the default argument of a parameter to determine whether it
71/// contains any ill-formed subexpressions. For example, this will
72/// diagnose the use of local variables or parameters within the
73/// default argument expression.
74class CheckDefaultArgumentVisitor
75 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
76 Sema &S;
77 const Expr *DefaultArg;
78
79public:
80 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
81 : S(S), DefaultArg(DefaultArg) {}
82
83 bool VisitExpr(const Expr *Node);
84 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
85 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
86 bool VisitLambdaExpr(const LambdaExpr *Lambda);
87 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
104
105 if (!isa<VarDecl, BindingDecl>(Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(DRE->getBeginLoc(),
119 diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(DRE->getBeginLoc(),
136 diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(ThisE->getBeginLoc(),
148 diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(&LC))
176 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(LC.getCapturedVar());
179 Invalid |= Visit(D->getInit());
180 }
181 return Invalid;
182}
183} // namespace
184
185void
187 const CXXMethodDecl *Method) {
188 // If we have an MSAny spec already, don't bother.
189 if (!Method || ComputedEST == EST_MSAny)
190 return;
191
192 const FunctionProtoType *Proto
193 = Method->getType()->getAs<FunctionProtoType>();
194 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
195 if (!Proto)
196 return;
197
199
200 // If we have a throw-all spec at this point, ignore the function.
201 if (ComputedEST == EST_None)
202 return;
203
204 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
205 EST = EST_BasicNoexcept;
206
207 switch (EST) {
208 case EST_Unparsed:
210 case EST_Unevaluated:
211 llvm_unreachable("should not see unresolved exception specs here");
212
213 // If this function can throw any exceptions, make a note of that.
214 case EST_MSAny:
215 case EST_None:
216 // FIXME: Whichever we see last of MSAny and None determines our result.
217 // We should make a consistent, order-independent choice here.
218 ClearExceptions();
219 ComputedEST = EST;
220 return;
222 ClearExceptions();
223 ComputedEST = EST_None;
224 return;
225 // FIXME: If the call to this decl is using any of its default arguments, we
226 // need to search them for potentially-throwing calls.
227 // If this function has a basic noexcept, it doesn't affect the outcome.
229 case EST_NoexceptTrue:
230 case EST_NoThrow:
231 return;
232 // If we're still at noexcept(true) and there's a throw() callee,
233 // change to that specification.
234 case EST_DynamicNone:
235 if (ComputedEST == EST_BasicNoexcept)
236 ComputedEST = EST_DynamicNone;
237 return;
239 llvm_unreachable(
240 "should not generate implicit declarations for dependent cases");
241 case EST_Dynamic:
242 break;
243 }
244 assert(EST == EST_Dynamic && "EST case not considered earlier.");
245 assert(ComputedEST != EST_None &&
246 "Shouldn't collect exceptions when throw-all is guaranteed.");
247 ComputedEST = EST_Dynamic;
248 // Record the exceptions in this function's exception specification.
249 for (const auto &E : Proto->exceptions())
250 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
251 Exceptions.push_back(E);
252}
253
255 if (!S || ComputedEST == EST_MSAny)
256 return;
257
258 // FIXME:
259 //
260 // C++0x [except.spec]p14:
261 // [An] implicit exception-specification specifies the type-id T if and
262 // only if T is allowed by the exception-specification of a function directly
263 // invoked by f's implicit definition; f shall allow all exceptions if any
264 // function it directly invokes allows all exceptions, and f shall allow no
265 // exceptions if every function it directly invokes allows no exceptions.
266 //
267 // Note in particular that if an implicit exception-specification is generated
268 // for a function containing a throw-expression, that specification can still
269 // be noexcept(true).
270 //
271 // Note also that 'directly invoked' is not defined in the standard, and there
272 // is no indication that we should only consider potentially-evaluated calls.
273 //
274 // Ultimately we should implement the intent of the standard: the exception
275 // specification should be the set of exceptions which can be thrown by the
276 // implicit definition. For now, we assume that any non-nothrow expression can
277 // throw any exception.
278
279 if (Self->canThrow(S))
280 ComputedEST = EST_None;
281}
282
284 SourceLocation EqualLoc) {
285 if (RequireCompleteType(Param->getLocation(), Param->getType(),
286 diag::err_typecheck_decl_incomplete_type))
287 return true;
288
289 // C++ [dcl.fct.default]p5
290 // A default argument expression is implicitly converted (clause
291 // 4) to the parameter type. The default argument expression has
292 // the same semantic constraints as the initializer expression in
293 // a declaration of a variable of the parameter type, using the
294 // copy-initialization semantics (8.5).
296 Param);
298 EqualLoc);
299 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
300 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
301 if (Result.isInvalid())
302 return true;
303 Arg = Result.getAs<Expr>();
304
305 CheckCompletedExpr(Arg, EqualLoc);
307
308 return Arg;
309}
310
312 SourceLocation EqualLoc) {
313 // Add the default argument to the parameter
314 Param->setDefaultArg(Arg);
315
316 // We have already instantiated this parameter; provide each of the
317 // instantiations with the uninstantiated default argument.
318 UnparsedDefaultArgInstantiationsMap::iterator InstPos
320 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
321 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
322 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
323
324 // We're done tracking this parameter's instantiations.
326 }
327}
328
329void
331 Expr *DefaultArg) {
332 if (!param || !DefaultArg)
333 return;
334
335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
336 UnparsedDefaultArgLocs.erase(Param);
337
338 // Default arguments are only permitted in C++
339 if (!getLangOpts().CPlusPlus) {
340 Diag(EqualLoc, diag::err_param_default_argument)
341 << DefaultArg->getSourceRange();
342 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
343 }
344
345 // Check for unexpanded parameter packs.
347 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
348
349 // C++11 [dcl.fct.default]p3
350 // A default argument expression [...] shall not be specified for a
351 // parameter pack.
352 if (Param->isParameterPack()) {
353 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
354 << DefaultArg->getSourceRange();
355 // Recover by discarding the default argument.
356 Param->setDefaultArg(nullptr);
357 return;
358 }
359
360 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
361 if (Result.isInvalid())
362 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
363
364 DefaultArg = Result.getAs<Expr>();
365
366 // Check that the default argument is well-formed
367 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
368 if (DefaultArgChecker.Visit(DefaultArg))
369 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
370
371 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
372}
373
375 SourceLocation EqualLoc,
376 SourceLocation ArgLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setUnparsedDefaultArg();
382 UnparsedDefaultArgLocs[Param] = ArgLoc;
383}
384
386 Expr *DefaultArg) {
387 if (!param)
388 return;
389
390 ParmVarDecl *Param = cast<ParmVarDecl>(param);
391 Param->setInvalidDecl();
392 UnparsedDefaultArgLocs.erase(Param);
393 ExprResult RE;
394 if (DefaultArg) {
395 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
396 Param->getType().getNonReferenceType());
397 } else {
398 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
399 Param->getType().getNonReferenceType());
400 }
401 Param->setDefaultArg(RE.get());
402}
403
405 // C++ [dcl.fct.default]p3
406 // A default argument expression shall be specified only in the
407 // parameter-declaration-clause of a function declaration or in a
408 // template-parameter (14.1). It shall not be specified for a
409 // parameter pack. If it is specified in a
410 // parameter-declaration-clause, it shall not occur within a
411 // declarator or abstract-declarator of a parameter-declaration.
412 bool MightBeFunction = D.isFunctionDeclarationContext();
413 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
414 DeclaratorChunk &chunk = D.getTypeObject(i);
415 if (chunk.Kind == DeclaratorChunk::Function) {
416 if (MightBeFunction) {
417 // This is a function declaration. It can have default arguments, but
418 // keep looking in case its return type is a function type with default
419 // arguments.
420 MightBeFunction = false;
421 continue;
422 }
423 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
424 ++argIdx) {
425 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
426 if (Param->hasUnparsedDefaultArg()) {
427 std::unique_ptr<CachedTokens> Toks =
428 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
429 SourceRange SR;
430 if (Toks->size() > 1)
431 SR = SourceRange((*Toks)[1].getLocation(),
432 Toks->back().getLocation());
433 else
434 SR = UnparsedDefaultArgLocs[Param];
435 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436 << SR;
437 } else if (Param->getDefaultArg()) {
438 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
439 << Param->getDefaultArg()->getSourceRange();
440 Param->setDefaultArg(nullptr);
441 }
442 }
443 } else if (chunk.Kind != DeclaratorChunk::Paren) {
444 MightBeFunction = false;
445 }
446 }
447}
448
450 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
451 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
452 });
453}
454
456 Scope *S) {
457 bool Invalid = false;
458
459 // The declaration context corresponding to the scope is the semantic
460 // parent, unless this is a local function declaration, in which case
461 // it is that surrounding function.
462 DeclContext *ScopeDC = New->isLocalExternDecl()
463 ? New->getLexicalDeclContext()
464 : New->getDeclContext();
465
466 // Find the previous declaration for the purpose of default arguments.
467 FunctionDecl *PrevForDefaultArgs = Old;
468 for (/**/; PrevForDefaultArgs;
469 // Don't bother looking back past the latest decl if this is a local
470 // extern declaration; nothing else could work.
471 PrevForDefaultArgs = New->isLocalExternDecl()
472 ? nullptr
473 : PrevForDefaultArgs->getPreviousDecl()) {
474 // Ignore hidden declarations.
475 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
476 continue;
477
478 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
479 !New->isCXXClassMember()) {
480 // Ignore default arguments of old decl if they are not in
481 // the same scope and this is not an out-of-line definition of
482 // a member function.
483 continue;
484 }
485
486 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
487 // If only one of these is a local function declaration, then they are
488 // declared in different scopes, even though isDeclInScope may think
489 // they're in the same scope. (If both are local, the scope check is
490 // sufficient, and if neither is local, then they are in the same scope.)
491 continue;
492 }
493
494 // We found the right previous declaration.
495 break;
496 }
497
498 // C++ [dcl.fct.default]p4:
499 // For non-template functions, default arguments can be added in
500 // later declarations of a function in the same
501 // scope. Declarations in different scopes have completely
502 // distinct sets of default arguments. That is, declarations in
503 // inner scopes do not acquire default arguments from
504 // declarations in outer scopes, and vice versa. In a given
505 // function declaration, all parameters subsequent to a
506 // parameter with a default argument shall have default
507 // arguments supplied in this or previous declarations. A
508 // default argument shall not be redefined by a later
509 // declaration (not even to the same value).
510 //
511 // C++ [dcl.fct.default]p6:
512 // Except for member functions of class templates, the default arguments
513 // in a member function definition that appears outside of the class
514 // definition are added to the set of default arguments provided by the
515 // member function declaration in the class definition.
516 for (unsigned p = 0, NumParams = PrevForDefaultArgs
517 ? PrevForDefaultArgs->getNumParams()
518 : 0;
519 p < NumParams; ++p) {
520 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
521 ParmVarDecl *NewParam = New->getParamDecl(p);
522
523 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
524 bool NewParamHasDfl = NewParam->hasDefaultArg();
525
526 if (OldParamHasDfl && NewParamHasDfl) {
527 unsigned DiagDefaultParamID =
528 diag::err_param_default_argument_redefinition;
529
530 // MSVC accepts that default parameters be redefined for member functions
531 // of template class. The new default parameter's value is ignored.
532 Invalid = true;
533 if (getLangOpts().MicrosoftExt) {
534 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
535 if (MD && MD->getParent()->getDescribedClassTemplate()) {
536 // Merge the old default argument into the new parameter.
537 NewParam->setHasInheritedDefaultArg();
538 if (OldParam->hasUninstantiatedDefaultArg())
540 OldParam->getUninstantiatedDefaultArg());
541 else
542 NewParam->setDefaultArg(OldParam->getInit());
543 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
544 Invalid = false;
545 }
546 }
547
548 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
549 // hint here. Alternatively, we could walk the type-source information
550 // for NewParam to find the last source location in the type... but it
551 // isn't worth the effort right now. This is the kind of test case that
552 // is hard to get right:
553 // int f(int);
554 // void g(int (*fp)(int) = f);
555 // void g(int (*fp)(int) = &f);
556 Diag(NewParam->getLocation(), DiagDefaultParamID)
557 << NewParam->getDefaultArgRange();
558
559 // Look for the function declaration where the default argument was
560 // actually written, which may be a declaration prior to Old.
561 for (auto Older = PrevForDefaultArgs;
562 OldParam->hasInheritedDefaultArg(); /**/) {
563 Older = Older->getPreviousDecl();
564 OldParam = Older->getParamDecl(p);
565 }
566
567 Diag(OldParam->getLocation(), diag::note_previous_definition)
568 << OldParam->getDefaultArgRange();
569 } else if (OldParamHasDfl) {
570 // Merge the old default argument into the new parameter unless the new
571 // function is a friend declaration in a template class. In the latter
572 // case the default arguments will be inherited when the friend
573 // declaration will be instantiated.
574 if (New->getFriendObjectKind() == Decl::FOK_None ||
576 // It's important to use getInit() here; getDefaultArg()
577 // strips off any top-level ExprWithCleanups.
578 NewParam->setHasInheritedDefaultArg();
579 if (OldParam->hasUnparsedDefaultArg())
580 NewParam->setUnparsedDefaultArg();
581 else if (OldParam->hasUninstantiatedDefaultArg())
583 OldParam->getUninstantiatedDefaultArg());
584 else
585 NewParam->setDefaultArg(OldParam->getInit());
586 }
587 } else if (NewParamHasDfl) {
588 if (New->getDescribedFunctionTemplate()) {
589 // Paragraph 4, quoted above, only applies to non-template functions.
590 Diag(NewParam->getLocation(),
591 diag::err_param_default_argument_template_redecl)
592 << NewParam->getDefaultArgRange();
593 Diag(PrevForDefaultArgs->getLocation(),
594 diag::note_template_prev_declaration)
595 << false;
596 } else if (New->getTemplateSpecializationKind()
599 // C++ [temp.expr.spec]p21:
600 // Default function arguments shall not be specified in a declaration
601 // or a definition for one of the following explicit specializations:
602 // - the explicit specialization of a function template;
603 // - the explicit specialization of a member function template;
604 // - the explicit specialization of a member function of a class
605 // template where the class template specialization to which the
606 // member function specialization belongs is implicitly
607 // instantiated.
608 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
610 << New->getDeclName()
611 << NewParam->getDefaultArgRange();
612 } else if (New->getDeclContext()->isDependentContext()) {
613 // C++ [dcl.fct.default]p6 (DR217):
614 // Default arguments for a member function of a class template shall
615 // be specified on the initial declaration of the member function
616 // within the class template.
617 //
618 // Reading the tea leaves a bit in DR217 and its reference to DR205
619 // leads me to the conclusion that one cannot add default function
620 // arguments for an out-of-line definition of a member function of a
621 // dependent type.
622 int WhichKind = 2;
624 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
625 if (Record->getDescribedClassTemplate())
626 WhichKind = 0;
627 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
628 WhichKind = 1;
629 else
630 WhichKind = 2;
631 }
632
633 Diag(NewParam->getLocation(),
634 diag::err_param_default_argument_member_template_redecl)
635 << WhichKind
636 << NewParam->getDefaultArgRange();
637 }
638 }
639 }
640
641 // DR1344: If a default argument is added outside a class definition and that
642 // default argument makes the function a special member function, the program
643 // is ill-formed. This can only happen for constructors.
644 if (isa<CXXConstructorDecl>(New) &&
646 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
647 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
648 if (NewSM != OldSM) {
649 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
650 assert(NewParam->hasDefaultArg());
651 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
652 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
653 Diag(Old->getLocation(), diag::note_previous_declaration);
654 }
655 }
656
657 const FunctionDecl *Def;
658 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
659 // template has a constexpr specifier then all its declarations shall
660 // contain the constexpr specifier.
661 if (New->getConstexprKind() != Old->getConstexprKind()) {
662 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
663 << New << static_cast<int>(New->getConstexprKind())
664 << static_cast<int>(Old->getConstexprKind());
665 Diag(Old->getLocation(), diag::note_previous_declaration);
666 Invalid = true;
667 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
668 Old->isDefined(Def) &&
669 // If a friend function is inlined but does not have 'inline'
670 // specifier, it is a definition. Do not report attribute conflict
671 // in this case, redefinition will be diagnosed later.
672 (New->isInlineSpecified() ||
674 // C++11 [dcl.fcn.spec]p4:
675 // If the definition of a function appears in a translation unit before its
676 // first declaration as inline, the program is ill-formed.
677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
678 Diag(Def->getLocation(), diag::note_previous_definition);
679 Invalid = true;
680 }
681
682 // C++17 [temp.deduct.guide]p3:
683 // Two deduction guide declarations in the same translation unit
684 // for the same class template shall not have equivalent
685 // parameter-declaration-clauses.
686 if (isa<CXXDeductionGuideDecl>(New) &&
688 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
689 Diag(Old->getLocation(), diag::note_previous_declaration);
690 }
691
692 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
693 // argument expression, that declaration shall be a definition and shall be
694 // the only declaration of the function or function template in the
695 // translation unit.
698 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
699 Diag(Old->getLocation(), diag::note_previous_declaration);
700 Invalid = true;
701 }
702
703 // C++11 [temp.friend]p4 (DR329):
704 // When a function is defined in a friend function declaration in a class
705 // template, the function is instantiated when the function is odr-used.
706 // The same restrictions on multiple declarations and definitions that
707 // apply to non-template function declarations and definitions also apply
708 // to these implicit definitions.
709 const FunctionDecl *OldDefinition = nullptr;
711 Old->isDefined(OldDefinition, true))
712 CheckForFunctionRedefinition(New, OldDefinition);
713
714 return Invalid;
715}
716
719 ? diag::warn_cxx23_placeholder_var_definition
720 : diag::ext_placeholder_var_definition);
721}
722
723NamedDecl *
725 MultiTemplateParamsArg TemplateParamLists) {
726 assert(D.isDecompositionDeclarator());
727 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
728
729 // The syntax only allows a decomposition declarator as a simple-declaration,
730 // a for-range-declaration, or a condition in Clang, but we parse it in more
731 // cases than that.
732 if (!D.mayHaveDecompositionDeclarator()) {
733 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
734 << Decomp.getSourceRange();
735 return nullptr;
736 }
737
738 if (!TemplateParamLists.empty()) {
739 // FIXME: There's no rule against this, but there are also no rules that
740 // would actually make it usable, so we reject it for now.
741 Diag(TemplateParamLists.front()->getTemplateLoc(),
742 diag::err_decomp_decl_template);
743 return nullptr;
744 }
745
746 Diag(Decomp.getLSquareLoc(),
748 ? diag::ext_decomp_decl
749 : D.getContext() == DeclaratorContext::Condition
750 ? diag::ext_decomp_decl_cond
751 : diag::warn_cxx14_compat_decomp_decl)
752 << Decomp.getSourceRange();
753
754 // The semantic context is always just the current context.
755 DeclContext *const DC = CurContext;
756
757 // C++17 [dcl.dcl]/8:
758 // The decl-specifier-seq shall contain only the type-specifier auto
759 // and cv-qualifiers.
760 // C++20 [dcl.dcl]/8:
761 // If decl-specifier-seq contains any decl-specifier other than static,
762 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
763 // C++23 [dcl.pre]/6:
764 // Each decl-specifier in the decl-specifier-seq shall be static,
765 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
766 auto &DS = D.getDeclSpec();
767 {
768 // Note: While constrained-auto needs to be checked, we do so separately so
769 // we can emit a better diagnostic.
770 SmallVector<StringRef, 8> BadSpecifiers;
771 SmallVector<SourceLocation, 8> BadSpecifierLocs;
772 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
773 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
774 if (auto SCS = DS.getStorageClassSpec()) {
775 if (SCS == DeclSpec::SCS_static) {
776 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 } else {
779 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
780 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781 }
782 }
783 if (auto TSCS = DS.getThreadStorageClassSpec()) {
784 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
785 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
786 }
787 if (DS.hasConstexprSpecifier()) {
788 BadSpecifiers.push_back(
789 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
790 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
791 }
792 if (DS.isInlineSpecified()) {
793 BadSpecifiers.push_back("inline");
794 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
795 }
796
797 if (!BadSpecifiers.empty()) {
798 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
799 Err << (int)BadSpecifiers.size()
800 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
801 // Don't add FixItHints to remove the specifiers; we do still respect
802 // them when building the underlying variable.
803 for (auto Loc : BadSpecifierLocs)
804 Err << SourceRange(Loc, Loc);
805 } else if (!CPlusPlus20Specifiers.empty()) {
806 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
808 ? diag::warn_cxx17_compat_decomp_decl_spec
809 : diag::ext_decomp_decl_spec);
810 Warn << (int)CPlusPlus20Specifiers.size()
811 << llvm::join(CPlusPlus20Specifiers.begin(),
812 CPlusPlus20Specifiers.end(), " ");
813 for (auto Loc : CPlusPlus20SpecifierLocs)
814 Warn << SourceRange(Loc, Loc);
815 }
816 // We can't recover from it being declared as a typedef.
817 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
818 return nullptr;
819 }
820
821 // C++2a [dcl.struct.bind]p1:
822 // A cv that includes volatile is deprecated
823 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
825 Diag(DS.getVolatileSpecLoc(),
826 diag::warn_deprecated_volatile_structured_binding);
827
829 QualType R = TInfo->getType();
830
831 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
833 D.setInvalidType();
834
835 // The syntax only allows a single ref-qualifier prior to the decomposition
836 // declarator. No other declarator chunks are permitted. Also check the type
837 // specifier here.
838 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
839 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
840 (D.getNumTypeObjects() == 1 &&
841 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
842 Diag(Decomp.getLSquareLoc(),
843 (D.hasGroupingParens() ||
844 (D.getNumTypeObjects() &&
845 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
846 ? diag::err_decomp_decl_parens
847 : diag::err_decomp_decl_type)
848 << R;
849
850 // In most cases, there's no actual problem with an explicitly-specified
851 // type, but a function type won't work here, and ActOnVariableDeclarator
852 // shouldn't be called for such a type.
853 if (R->isFunctionType())
854 D.setInvalidType();
855 }
856
857 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
858 if (DS.isConstrainedAuto()) {
859 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
860 assert(TemplRep->Kind == TNK_Concept_template &&
861 "No other template kind should be possible for a constrained auto");
862
863 SourceRange TemplRange{TemplRep->TemplateNameLoc,
864 TemplRep->RAngleLoc.isValid()
865 ? TemplRep->RAngleLoc
866 : TemplRep->TemplateNameLoc};
867 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
868 << TemplRange << FixItHint::CreateRemoval(TemplRange);
869 }
870
871 // Build the BindingDecls.
873
874 // Build the BindingDecls.
875 for (auto &B : D.getDecompositionDeclarator().bindings()) {
876 // Check for name conflicts.
877 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
878 IdentifierInfo *VarName = B.Name;
879 assert(VarName && "Cannot have an unnamed binding declaration");
880
882 RedeclarationKind::ForVisibleRedeclaration);
884 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
885
886 // It's not permitted to shadow a template parameter name.
887 if (Previous.isSingleResult() &&
888 Previous.getFoundDecl()->isTemplateParameter()) {
889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
890 Previous.getFoundDecl());
891 Previous.clear();
892 }
893
894 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
895
896 ProcessDeclAttributeList(S, BD, *B.Attrs);
897
898 // Find the shadowed declaration before filtering for scope.
899 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
901 : nullptr;
902
903 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
904 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
905 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
906 /*AllowInlineNamespace*/false);
907
908 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
909 DC->isFunctionOrMethod() && VarName->isPlaceholder();
910 if (!Previous.empty()) {
911 if (IsPlaceholder) {
912 bool sameDC = (Previous.end() - 1)
913 ->getDeclContext()
914 ->getRedeclContext()
915 ->Equals(DC->getRedeclContext());
916 if (sameDC &&
917 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
918 Previous.clear();
920 }
921 } else {
922 auto *Old = Previous.getRepresentativeDecl();
923 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
924 Diag(Old->getLocation(), diag::note_previous_definition);
925 }
926 } else if (ShadowedDecl && !D.isRedeclaration()) {
927 CheckShadow(BD, ShadowedDecl, Previous);
928 }
929 PushOnScopeChains(BD, S, true);
930 Bindings.push_back(BD);
931 ParsingInitForAutoVars.insert(BD);
932 }
933
934 // There are no prior lookup results for the variable itself, because it
935 // is unnamed.
936 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
937 Decomp.getLSquareLoc());
939 RedeclarationKind::ForVisibleRedeclaration);
940
941 // Build the variable that holds the non-decomposed object.
942 bool AddToScope = true;
943 NamedDecl *New =
944 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
945 MultiTemplateParamsArg(), AddToScope, Bindings);
946 if (AddToScope) {
947 S->AddDecl(New);
949 }
950
951 if (OpenMP().isInOpenMPDeclareTargetContext())
953
954 return New;
955}
956
959 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
960 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
961 if ((int64_t)Bindings.size() != NumElems) {
962 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
963 << DecompType << (unsigned)Bindings.size()
964 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
965 << toString(NumElems, 10) << (NumElems < Bindings.size());
966 return true;
967 }
968
969 unsigned I = 0;
970 for (auto *B : Bindings) {
971 SourceLocation Loc = B->getLocation();
972 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
973 if (E.isInvalid())
974 return true;
975 E = GetInit(Loc, E.get(), I++);
976 if (E.isInvalid())
977 return true;
978 B->setBinding(ElemType, E.get());
979 }
980
981 return false;
982}
983
986 ValueDecl *Src, QualType DecompType,
987 const llvm::APSInt &NumElems,
988 QualType ElemType) {
990 S, Bindings, Src, DecompType, NumElems, ElemType,
991 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
993 if (E.isInvalid())
994 return ExprError();
995 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
996 });
997}
998
1000 ValueDecl *Src, QualType DecompType,
1001 const ConstantArrayType *CAT) {
1002 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1003 llvm::APSInt(CAT->getSize()),
1004 CAT->getElementType());
1005}
1006
1008 ValueDecl *Src, QualType DecompType,
1009 const VectorType *VT) {
1011 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1013 DecompType.getQualifiers()));
1014}
1015
1018 ValueDecl *Src, QualType DecompType,
1019 const ComplexType *CT) {
1021 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1023 DecompType.getQualifiers()),
1024 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1025 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1026 });
1027}
1028
1031 const TemplateParameterList *Params) {
1033 llvm::raw_svector_ostream OS(SS);
1034 bool First = true;
1035 unsigned I = 0;
1036 for (auto &Arg : Args.arguments()) {
1037 if (!First)
1038 OS << ", ";
1039 Arg.getArgument().print(PrintingPolicy, OS,
1041 PrintingPolicy, Params, I));
1042 First = false;
1043 I++;
1044 }
1045 return std::string(OS.str());
1046}
1047
1048static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1049 SourceLocation Loc, StringRef Trait,
1051 unsigned DiagID) {
1052 auto DiagnoseMissing = [&] {
1053 if (DiagID)
1055 Args, /*Params*/ nullptr);
1056 return true;
1057 };
1058
1059 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1061 if (!Std)
1062 return DiagnoseMissing();
1063
1064 // Look up the trait itself, within namespace std. We can diagnose various
1065 // problems with this lookup even if we've been asked to not diagnose a
1066 // missing specialization, because this can only fail if the user has been
1067 // declaring their own names in namespace std or we don't support the
1068 // standard library implementation in use.
1072 return DiagnoseMissing();
1073 if (Result.isAmbiguous())
1074 return true;
1075
1076 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1077 if (!TraitTD) {
1078 Result.suppressDiagnostics();
1079 NamedDecl *Found = *Result.begin();
1080 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1081 S.Diag(Found->getLocation(), diag::note_declared_at);
1082 return true;
1083 }
1084
1085 // Build the template-id.
1086 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1087 if (TraitTy.isNull())
1088 return true;
1089 if (!S.isCompleteType(Loc, TraitTy)) {
1090 if (DiagID)
1092 Loc, TraitTy, DiagID,
1094 TraitTD->getTemplateParameters()));
1095 return true;
1096 }
1097
1098 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1099 assert(RD && "specialization of class template is not a class?");
1100
1101 // Look up the member of the trait type.
1102 S.LookupQualifiedName(TraitMemberLookup, RD);
1103 return TraitMemberLookup.isAmbiguous();
1104}
1105
1108 uint64_t I) {
1110 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1111}
1112
1116}
1117
1118namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1119
1121 llvm::APSInt &Size) {
1124
1127
1128 // Form template argument list for tuple_size<T>.
1131
1132 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1133 // it's not tuple-like.
1134 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1135 R.empty())
1136 return IsTupleLike::NotTupleLike;
1137
1138 // If we get this far, we've committed to the tuple interpretation, but
1139 // we can still fail if there actually isn't a usable ::value.
1140
1141 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1142 LookupResult &R;
1144 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1145 : R(R), Args(Args) {}
1146 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1147 SourceLocation Loc) override {
1148 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1150 /*Params*/ nullptr);
1151 }
1152 } Diagnoser(R, Args);
1153
1154 ExprResult E =
1155 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1156 if (E.isInvalid())
1157 return IsTupleLike::Error;
1158
1159 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1160 if (E.isInvalid())
1161 return IsTupleLike::Error;
1162
1163 return IsTupleLike::TupleLike;
1164}
1165
1166/// \return std::tuple_element<I, T>::type.
1168 unsigned I, QualType T) {
1169 // Form template argument list for tuple_element<I, T>.
1171 Args.addArgument(
1174
1175 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1178 S, R, Loc, "tuple_element", Args,
1179 diag::err_decomp_decl_std_tuple_element_not_specialized))
1180 return QualType();
1181
1182 auto *TD = R.getAsSingle<TypeDecl>();
1183 if (!TD) {
1185 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1187 /*Params*/ nullptr);
1188 if (!R.empty())
1189 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1190 return QualType();
1191 }
1192
1193 return S.Context.getTypeDeclType(TD);
1194}
1195
1196namespace {
1197struct InitializingBinding {
1198 Sema &S;
1199 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1203 Ctx.Entity = BD;
1205 }
1206 ~InitializingBinding() {
1208 }
1209};
1210}
1211
1214 VarDecl *Src, QualType DecompType,
1215 const llvm::APSInt &TupleSize) {
1216 if ((int64_t)Bindings.size() != TupleSize) {
1217 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1218 << DecompType << (unsigned)Bindings.size()
1219 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1220 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1221 return true;
1222 }
1223
1224 if (Bindings.empty())
1225 return false;
1226
1227 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1228
1229 // [dcl.decomp]p3:
1230 // The unqualified-id get is looked up in the scope of E by class member
1231 // access lookup ...
1232 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1233 bool UseMemberGet = false;
1234 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1235 if (auto *RD = DecompType->getAsCXXRecordDecl())
1236 S.LookupQualifiedName(MemberGet, RD);
1237 if (MemberGet.isAmbiguous())
1238 return true;
1239 // ... and if that finds at least one declaration that is a function
1240 // template whose first template parameter is a non-type parameter ...
1241 for (NamedDecl *D : MemberGet) {
1242 if (FunctionTemplateDecl *FTD =
1243 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1244 TemplateParameterList *TPL = FTD->getTemplateParameters();
1245 if (TPL->size() != 0 &&
1246 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1247 // ... the initializer is e.get<i>().
1248 UseMemberGet = true;
1249 break;
1250 }
1251 }
1252 }
1253 }
1254
1255 unsigned I = 0;
1256 for (auto *B : Bindings) {
1257 InitializingBinding InitContext(S, B);
1258 SourceLocation Loc = B->getLocation();
1259
1260 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1261 if (E.isInvalid())
1262 return true;
1263
1264 // e is an lvalue if the type of the entity is an lvalue reference and
1265 // an xvalue otherwise
1266 if (!Src->getType()->isLValueReferenceType())
1267 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1268 E.get(), nullptr, VK_XValue,
1270
1272 Args.addArgument(
1274
1275 if (UseMemberGet) {
1276 // if [lookup of member get] finds at least one declaration, the
1277 // initializer is e.get<i-1>().
1278 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1279 CXXScopeSpec(), SourceLocation(), nullptr,
1280 MemberGet, &Args, nullptr);
1281 if (E.isInvalid())
1282 return true;
1283
1284 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1285 } else {
1286 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1287 // in the associated namespaces.
1290 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1292 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1293
1294 Expr *Arg = E.get();
1295 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1296 }
1297 if (E.isInvalid())
1298 return true;
1299 Expr *Init = E.get();
1300
1301 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1302 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1303 if (T.isNull())
1304 return true;
1305
1306 // each vi is a variable of type "reference to T" initialized with the
1307 // initializer, where the reference is an lvalue reference if the
1308 // initializer is an lvalue and an rvalue reference otherwise
1309 QualType RefType =
1310 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1311 if (RefType.isNull())
1312 return true;
1313 auto *RefVD = VarDecl::Create(
1314 S.Context, Src->getDeclContext(), Loc, Loc,
1315 B->getDeclName().getAsIdentifierInfo(), RefType,
1317 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1318 RefVD->setTSCSpec(Src->getTSCSpec());
1319 RefVD->setImplicit();
1320 if (Src->isInlineSpecified())
1321 RefVD->setInlineSpecified();
1322 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1323
1326 InitializationSequence Seq(S, Entity, Kind, Init);
1327 E = Seq.Perform(S, Entity, Kind, Init);
1328 if (E.isInvalid())
1329 return true;
1330 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1331 if (E.isInvalid())
1332 return true;
1333 RefVD->setInit(E.get());
1335
1337 DeclarationNameInfo(B->getDeclName(), Loc),
1338 RefVD);
1339 if (E.isInvalid())
1340 return true;
1341
1342 B->setBinding(T, E.get());
1343 I++;
1344 }
1345
1346 return false;
1347}
1348
1349/// Find the base class to decompose in a built-in decomposition of a class type.
1350/// This base class search is, unfortunately, not quite like any other that we
1351/// perform anywhere else in C++.
1353 const CXXRecordDecl *RD,
1354 CXXCastPath &BasePath) {
1355 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1356 CXXBasePath &Path) {
1357 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1358 };
1359
1360 const CXXRecordDecl *ClassWithFields = nullptr;
1362 if (RD->hasDirectFields())
1363 // [dcl.decomp]p4:
1364 // Otherwise, all of E's non-static data members shall be public direct
1365 // members of E ...
1366 ClassWithFields = RD;
1367 else {
1368 // ... or of ...
1369 CXXBasePaths Paths;
1370 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1371 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1372 // If no classes have fields, just decompose RD itself. (This will work
1373 // if and only if zero bindings were provided.)
1374 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1375 }
1376
1377 CXXBasePath *BestPath = nullptr;
1378 for (auto &P : Paths) {
1379 if (!BestPath)
1380 BestPath = &P;
1381 else if (!S.Context.hasSameType(P.back().Base->getType(),
1382 BestPath->back().Base->getType())) {
1383 // ... the same ...
1384 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1385 << false << RD << BestPath->back().Base->getType()
1386 << P.back().Base->getType();
1387 return DeclAccessPair();
1388 } else if (P.Access < BestPath->Access) {
1389 BestPath = &P;
1390 }
1391 }
1392
1393 // ... unambiguous ...
1394 QualType BaseType = BestPath->back().Base->getType();
1395 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1396 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1397 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1398 return DeclAccessPair();
1399 }
1400
1401 // ... [accessible, implied by other rules] base class of E.
1402 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1403 *BestPath, diag::err_decomp_decl_inaccessible_base);
1404 AS = BestPath->Access;
1405
1406 ClassWithFields = BaseType->getAsCXXRecordDecl();
1407 S.BuildBasePathArray(Paths, BasePath);
1408 }
1409
1410 // The above search did not check whether the selected class itself has base
1411 // classes with fields, so check that now.
1412 CXXBasePaths Paths;
1413 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1414 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1415 << (ClassWithFields == RD) << RD << ClassWithFields
1416 << Paths.front().back().Base->getType();
1417 return DeclAccessPair();
1418 }
1419
1420 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1421}
1422
1424 ValueDecl *Src, QualType DecompType,
1425 const CXXRecordDecl *OrigRD) {
1426 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1427 diag::err_incomplete_type))
1428 return true;
1429
1430 CXXCastPath BasePath;
1431 DeclAccessPair BasePair =
1432 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1433 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1434 if (!RD)
1435 return true;
1437 DecompType.getQualifiers());
1438
1439 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1440 unsigned NumFields = llvm::count_if(
1441 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1442 assert(Bindings.size() != NumFields);
1443 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1444 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1445 << (NumFields < Bindings.size());
1446 return true;
1447 };
1448
1449 // all of E's non-static data members shall be [...] well-formed
1450 // when named as e.name in the context of the structured binding,
1451 // E shall not have an anonymous union member, ...
1452 unsigned I = 0;
1453 for (auto *FD : RD->fields()) {
1454 if (FD->isUnnamedBitField())
1455 continue;
1456
1457 // All the non-static data members are required to be nameable, so they
1458 // must all have names.
1459 if (!FD->getDeclName()) {
1460 if (RD->isLambda()) {
1461 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1462 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1463 return true;
1464 }
1465
1466 if (FD->isAnonymousStructOrUnion()) {
1467 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1468 << DecompType << FD->getType()->isUnionType();
1469 S.Diag(FD->getLocation(), diag::note_declared_at);
1470 return true;
1471 }
1472
1473 // FIXME: Are there any other ways we could have an anonymous member?
1474 }
1475
1476 // We have a real field to bind.
1477 if (I >= Bindings.size())
1478 return DiagnoseBadNumberOfBindings();
1479 auto *B = Bindings[I++];
1480 SourceLocation Loc = B->getLocation();
1481
1482 // The field must be accessible in the context of the structured binding.
1483 // We already checked that the base class is accessible.
1484 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1485 // const_cast here.
1487 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1489 BasePair.getAccess(), FD->getAccess())));
1490
1491 // Initialize the binding to Src.FD.
1492 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1493 if (E.isInvalid())
1494 return true;
1495 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1496 VK_LValue, &BasePath);
1497 if (E.isInvalid())
1498 return true;
1499 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1500 CXXScopeSpec(), FD,
1501 DeclAccessPair::make(FD, FD->getAccess()),
1502 DeclarationNameInfo(FD->getDeclName(), Loc));
1503 if (E.isInvalid())
1504 return true;
1505
1506 // If the type of the member is T, the referenced type is cv T, where cv is
1507 // the cv-qualification of the decomposition expression.
1508 //
1509 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1510 // 'const' to the type of the field.
1511 Qualifiers Q = DecompType.getQualifiers();
1512 if (FD->isMutable())
1513 Q.removeConst();
1514 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1515 }
1516
1517 if (I != Bindings.size())
1518 return DiagnoseBadNumberOfBindings();
1519
1520 return false;
1521}
1522
1524 QualType DecompType = DD->getType();
1525
1526 // If the type of the decomposition is dependent, then so is the type of
1527 // each binding.
1528 if (DecompType->isDependentType()) {
1529 for (auto *B : DD->bindings())
1530 B->setType(Context.DependentTy);
1531 return;
1532 }
1533
1534 DecompType = DecompType.getNonReferenceType();
1536
1537 // C++1z [dcl.decomp]/2:
1538 // If E is an array type [...]
1539 // As an extension, we also support decomposition of built-in complex and
1540 // vector types.
1541 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1542 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1543 DD->setInvalidDecl();
1544 return;
1545 }
1546 if (auto *VT = DecompType->getAs<VectorType>()) {
1547 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1548 DD->setInvalidDecl();
1549 return;
1550 }
1551 if (auto *CT = DecompType->getAs<ComplexType>()) {
1552 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1553 DD->setInvalidDecl();
1554 return;
1555 }
1556
1557 // C++1z [dcl.decomp]/3:
1558 // if the expression std::tuple_size<E>::value is a well-formed integral
1559 // constant expression, [...]
1560 llvm::APSInt TupleSize(32);
1561 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1562 case IsTupleLike::Error:
1563 DD->setInvalidDecl();
1564 return;
1565
1566 case IsTupleLike::TupleLike:
1567 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1568 DD->setInvalidDecl();
1569 return;
1570
1571 case IsTupleLike::NotTupleLike:
1572 break;
1573 }
1574
1575 // C++1z [dcl.dcl]/8:
1576 // [E shall be of array or non-union class type]
1577 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1578 if (!RD || RD->isUnion()) {
1579 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1580 << DD << !RD << DecompType;
1581 DD->setInvalidDecl();
1582 return;
1583 }
1584
1585 // C++1z [dcl.decomp]/4:
1586 // all of E's non-static data members shall be [...] direct members of
1587 // E or of the same unambiguous public base class of E, ...
1588 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1589 DD->setInvalidDecl();
1590}
1591
1593 // Shortcut if exceptions are disabled.
1594 if (!getLangOpts().CXXExceptions)
1595 return;
1596
1597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1598 "Should only be called if types are otherwise the same.");
1599
1600 QualType NewType = New->getType();
1601 QualType OldType = Old->getType();
1602
1603 // We're only interested in pointers and references to functions, as well
1604 // as pointers to member functions.
1605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1606 NewType = R->getPointeeType();
1607 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1609 NewType = P->getPointeeType();
1610 OldType = OldType->castAs<PointerType>()->getPointeeType();
1611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1612 NewType = M->getPointeeType();
1613 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1614 }
1615
1616 if (!NewType->isFunctionProtoType())
1617 return;
1618
1619 // There's lots of special cases for functions. For function pointers, system
1620 // libraries are hopefully not as broken so that we don't need these
1621 // workarounds.
1623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1625 New->setInvalidDecl();
1626 }
1627}
1628
1629/// CheckCXXDefaultArguments - Verify that the default arguments for a
1630/// function declaration are well-formed according to C++
1631/// [dcl.fct.default].
1633 // This checking doesn't make sense for explicit specializations; their
1634 // default arguments are determined by the declaration we're specializing,
1635 // not by FD.
1637 return;
1638 if (auto *FTD = FD->getDescribedFunctionTemplate())
1639 if (FTD->isMemberSpecialization())
1640 return;
1641
1642 unsigned NumParams = FD->getNumParams();
1643 unsigned ParamIdx = 0;
1644
1645 // Find first parameter with a default argument
1646 for (; ParamIdx < NumParams; ++ParamIdx) {
1647 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1648 if (Param->hasDefaultArg())
1649 break;
1650 }
1651
1652 // C++20 [dcl.fct.default]p4:
1653 // In a given function declaration, each parameter subsequent to a parameter
1654 // with a default argument shall have a default argument supplied in this or
1655 // a previous declaration, unless the parameter was expanded from a
1656 // parameter pack, or shall be a function parameter pack.
1657 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1658 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1659 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1662 continue;
1663 if (Param->isInvalidDecl())
1664 /* We already complained about this parameter. */;
1665 else if (Param->getIdentifier())
1666 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1667 << Param->getIdentifier();
1668 else
1669 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1670 }
1671}
1672
1673/// Check that the given type is a literal type. Issue a diagnostic if not,
1674/// if Kind is Diagnose.
1675/// \return \c true if a problem has been found (and optionally diagnosed).
1676template <typename... Ts>
1678 SourceLocation Loc, QualType T, unsigned DiagID,
1679 Ts &&...DiagArgs) {
1680 if (T->isDependentType())
1681 return false;
1682
1683 switch (Kind) {
1685 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1686 std::forward<Ts>(DiagArgs)...);
1687
1689 return !T->isLiteralType(SemaRef.Context);
1690 }
1691
1692 llvm_unreachable("unknown CheckConstexprKind");
1693}
1694
1695/// Determine whether a destructor cannot be constexpr due to
1697 const CXXDestructorDecl *DD,
1699 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1700 "this check is obsolete for C++23");
1701 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1702 const CXXRecordDecl *RD =
1704 if (!RD || RD->hasConstexprDestructor())
1705 return true;
1706
1708 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1709 << static_cast<int>(DD->getConstexprKind()) << !FD
1710 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1711 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1712 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1713 }
1714 return false;
1715 };
1716
1717 const CXXRecordDecl *RD = DD->getParent();
1718 for (const CXXBaseSpecifier &B : RD->bases())
1719 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1720 return false;
1721 for (const FieldDecl *FD : RD->fields())
1722 if (!Check(FD->getLocation(), FD->getType(), FD))
1723 return false;
1724 return true;
1725}
1726
1727/// Check whether a function's parameter types are all literal types. If so,
1728/// return true. If not, produce a suitable diagnostic and return false.
1730 const FunctionDecl *FD,
1732 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1733 "this check is obsolete for C++23");
1734 unsigned ArgIndex = 0;
1735 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1737 e = FT->param_type_end();
1738 i != e; ++i, ++ArgIndex) {
1739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1740 assert(PD && "null in a parameter list");
1741 SourceLocation ParamLoc = PD->getLocation();
1742 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1743 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1744 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1745 FD->isConsteval()))
1746 return false;
1747 }
1748 return true;
1749}
1750
1751/// Check whether a function's return type is a literal type. If so, return
1752/// true. If not, produce a suitable diagnostic and return false.
1755 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1756 "this check is obsolete for C++23");
1757 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1758 diag::err_constexpr_non_literal_return,
1759 FD->isConsteval()))
1760 return false;
1761 return true;
1762}
1763
1764/// Get diagnostic %select index for tag kind for
1765/// record diagnostic message.
1766/// WARNING: Indexes apply to particular diagnostics only!
1767///
1768/// \returns diagnostic %select index.
1770 switch (Tag) {
1772 return 0;
1774 return 1;
1775 case TagTypeKind::Class:
1776 return 2;
1777 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1778 }
1779}
1780
1781static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1782 Stmt *Body,
1784static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1785
1787 CheckConstexprKind Kind) {
1788 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1789 if (MD && MD->isInstance()) {
1790 // C++11 [dcl.constexpr]p4:
1791 // The definition of a constexpr constructor shall satisfy the following
1792 // constraints:
1793 // - the class shall not have any virtual base classes;
1794 //
1795 // FIXME: This only applies to constructors and destructors, not arbitrary
1796 // member functions.
1797 const CXXRecordDecl *RD = MD->getParent();
1798 if (RD->getNumVBases()) {
1800 return false;
1801
1802 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1803 << isa<CXXConstructorDecl>(NewFD)
1805 for (const auto &I : RD->vbases())
1806 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1807 << I.getSourceRange();
1808 return false;
1809 }
1810 }
1811
1812 if (!isa<CXXConstructorDecl>(NewFD)) {
1813 // C++11 [dcl.constexpr]p3:
1814 // The definition of a constexpr function shall satisfy the following
1815 // constraints:
1816 // - it shall not be virtual; (removed in C++20)
1817 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1818 if (Method && Method->isVirtual()) {
1819 if (getLangOpts().CPlusPlus20) {
1820 if (Kind == CheckConstexprKind::Diagnose)
1821 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1822 } else {
1824 return false;
1825
1826 Method = Method->getCanonicalDecl();
1827 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1828
1829 // If it's not obvious why this function is virtual, find an overridden
1830 // function which uses the 'virtual' keyword.
1831 const CXXMethodDecl *WrittenVirtual = Method;
1832 while (!WrittenVirtual->isVirtualAsWritten())
1833 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1834 if (WrittenVirtual != Method)
1835 Diag(WrittenVirtual->getLocation(),
1836 diag::note_overridden_virtual_function);
1837 return false;
1838 }
1839 }
1840
1841 // - its return type shall be a literal type; (removed in C++23)
1842 if (!getLangOpts().CPlusPlus23 &&
1843 !CheckConstexprReturnType(*this, NewFD, Kind))
1844 return false;
1845 }
1846
1847 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1848 // A destructor can be constexpr only if the defaulted destructor could be;
1849 // we don't need to check the members and bases if we already know they all
1850 // have constexpr destructors. (removed in C++23)
1851 if (!getLangOpts().CPlusPlus23 &&
1852 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1854 return false;
1855 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1856 return false;
1857 }
1858 }
1859
1860 // - each of its parameter types shall be a literal type; (removed in C++23)
1861 if (!getLangOpts().CPlusPlus23 &&
1862 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1863 return false;
1864
1865 Stmt *Body = NewFD->getBody();
1866 assert(Body &&
1867 "CheckConstexprFunctionDefinition called on function with no body");
1868 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1869}
1870
1871/// Check the given declaration statement is legal within a constexpr function
1872/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1873///
1874/// \return true if the body is OK (maybe only as an extension), false if we
1875/// have diagnosed a problem.
1877 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1879 // C++11 [dcl.constexpr]p3 and p4:
1880 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1881 // contain only
1882 for (const auto *DclIt : DS->decls()) {
1883 switch (DclIt->getKind()) {
1884 case Decl::StaticAssert:
1885 case Decl::Using:
1886 case Decl::UsingShadow:
1887 case Decl::UsingDirective:
1888 case Decl::UnresolvedUsingTypename:
1889 case Decl::UnresolvedUsingValue:
1890 case Decl::UsingEnum:
1891 // - static_assert-declarations
1892 // - using-declarations,
1893 // - using-directives,
1894 // - using-enum-declaration
1895 continue;
1896
1897 case Decl::Typedef:
1898 case Decl::TypeAlias: {
1899 // - typedef declarations and alias-declarations that do not define
1900 // classes or enumerations,
1901 const auto *TN = cast<TypedefNameDecl>(DclIt);
1902 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1903 // Don't allow variably-modified types in constexpr functions.
1905 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1906 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1907 << TL.getSourceRange() << TL.getType()
1908 << isa<CXXConstructorDecl>(Dcl);
1909 }
1910 return false;
1911 }
1912 continue;
1913 }
1914
1915 case Decl::Enum:
1916 case Decl::CXXRecord:
1917 // C++1y allows types to be defined, not just declared.
1918 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1920 SemaRef.Diag(DS->getBeginLoc(),
1921 SemaRef.getLangOpts().CPlusPlus14
1922 ? diag::warn_cxx11_compat_constexpr_type_definition
1923 : diag::ext_constexpr_type_definition)
1924 << isa<CXXConstructorDecl>(Dcl);
1925 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1926 return false;
1927 }
1928 }
1929 continue;
1930
1931 case Decl::EnumConstant:
1932 case Decl::IndirectField:
1933 case Decl::ParmVar:
1934 // These can only appear with other declarations which are banned in
1935 // C++11 and permitted in C++1y, so ignore them.
1936 continue;
1937
1938 case Decl::Var:
1939 case Decl::Decomposition: {
1940 // C++1y [dcl.constexpr]p3 allows anything except:
1941 // a definition of a variable of non-literal type or of static or
1942 // thread storage duration or [before C++2a] for which no
1943 // initialization is performed.
1944 const auto *VD = cast<VarDecl>(DclIt);
1945 if (VD->isThisDeclarationADefinition()) {
1946 if (VD->isStaticLocal()) {
1948 SemaRef.Diag(VD->getLocation(),
1949 SemaRef.getLangOpts().CPlusPlus23
1950 ? diag::warn_cxx20_compat_constexpr_var
1951 : diag::ext_constexpr_static_var)
1952 << isa<CXXConstructorDecl>(Dcl)
1953 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1954 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1955 return false;
1956 }
1957 }
1958 if (SemaRef.LangOpts.CPlusPlus23) {
1959 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1960 diag::warn_cxx20_compat_constexpr_var,
1961 isa<CXXConstructorDecl>(Dcl),
1962 /*variable of non-literal type*/ 2);
1963 } else if (CheckLiteralType(
1964 SemaRef, Kind, VD->getLocation(), VD->getType(),
1965 diag::err_constexpr_local_var_non_literal_type,
1966 isa<CXXConstructorDecl>(Dcl))) {
1967 return false;
1968 }
1969 if (!VD->getType()->isDependentType() &&
1970 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1972 SemaRef.Diag(
1973 VD->getLocation(),
1974 SemaRef.getLangOpts().CPlusPlus20
1975 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1976 : diag::ext_constexpr_local_var_no_init)
1977 << isa<CXXConstructorDecl>(Dcl);
1978 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1979 return false;
1980 }
1981 continue;
1982 }
1983 }
1985 SemaRef.Diag(VD->getLocation(),
1986 SemaRef.getLangOpts().CPlusPlus14
1987 ? diag::warn_cxx11_compat_constexpr_local_var
1988 : diag::ext_constexpr_local_var)
1989 << isa<CXXConstructorDecl>(Dcl);
1990 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1991 return false;
1992 }
1993 continue;
1994 }
1995
1996 case Decl::NamespaceAlias:
1997 case Decl::Function:
1998 // These are disallowed in C++11 and permitted in C++1y. Allow them
1999 // everywhere as an extension.
2000 if (!Cxx1yLoc.isValid())
2001 Cxx1yLoc = DS->getBeginLoc();
2002 continue;
2003
2004 default:
2006 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2007 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2008 }
2009 return false;
2010 }
2011 }
2012
2013 return true;
2014}
2015
2016/// Check that the given field is initialized within a constexpr constructor.
2017///
2018/// \param Dcl The constexpr constructor being checked.
2019/// \param Field The field being checked. This may be a member of an anonymous
2020/// struct or union nested within the class being checked.
2021/// \param Inits All declarations, including anonymous struct/union members and
2022/// indirect members, for which any initialization was provided.
2023/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2024/// multiple notes for different members to the same error.
2025/// \param Kind Whether we're diagnosing a constructor as written or determining
2026/// whether the formal requirements are satisfied.
2027/// \return \c false if we're checking for validity and the constructor does
2028/// not satisfy the requirements on a constexpr constructor.
2030 const FunctionDecl *Dcl,
2031 FieldDecl *Field,
2032 llvm::SmallSet<Decl*, 16> &Inits,
2033 bool &Diagnosed,
2035 // In C++20 onwards, there's nothing to check for validity.
2037 SemaRef.getLangOpts().CPlusPlus20)
2038 return true;
2039
2040 if (Field->isInvalidDecl())
2041 return true;
2042
2043 if (Field->isUnnamedBitField())
2044 return true;
2045
2046 // Anonymous unions with no variant members and empty anonymous structs do not
2047 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2048 // indirect fields don't need initializing.
2049 if (Field->isAnonymousStructOrUnion() &&
2050 (Field->getType()->isUnionType()
2051 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2052 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2053 return true;
2054
2055 if (!Inits.count(Field)) {
2057 if (!Diagnosed) {
2058 SemaRef.Diag(Dcl->getLocation(),
2059 SemaRef.getLangOpts().CPlusPlus20
2060 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2061 : diag::ext_constexpr_ctor_missing_init);
2062 Diagnosed = true;
2063 }
2064 SemaRef.Diag(Field->getLocation(),
2065 diag::note_constexpr_ctor_missing_init);
2066 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2067 return false;
2068 }
2069 } else if (Field->isAnonymousStructOrUnion()) {
2070 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2071 for (auto *I : RD->fields())
2072 // If an anonymous union contains an anonymous struct of which any member
2073 // is initialized, all members must be initialized.
2074 if (!RD->isUnion() || Inits.count(I))
2075 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2076 Kind))
2077 return false;
2078 }
2079 return true;
2080}
2081
2082/// Check the provided statement is allowed in a constexpr function
2083/// definition.
2084static bool
2087 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2088 SourceLocation &Cxx2bLoc,
2090 // - its function-body shall be [...] a compound-statement that contains only
2091 switch (S->getStmtClass()) {
2092 case Stmt::NullStmtClass:
2093 // - null statements,
2094 return true;
2095
2096 case Stmt::DeclStmtClass:
2097 // - static_assert-declarations
2098 // - using-declarations,
2099 // - using-directives,
2100 // - typedef declarations and alias-declarations that do not define
2101 // classes or enumerations,
2102 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::ReturnStmtClass:
2107 // - and exactly one return statement;
2108 if (isa<CXXConstructorDecl>(Dcl)) {
2109 // C++1y allows return statements in constexpr constructors.
2110 if (!Cxx1yLoc.isValid())
2111 Cxx1yLoc = S->getBeginLoc();
2112 return true;
2113 }
2114
2115 ReturnStmts.push_back(S->getBeginLoc());
2116 return true;
2117
2118 case Stmt::AttributedStmtClass:
2119 // Attributes on a statement don't affect its formal kind and hence don't
2120 // affect its validity in a constexpr function.
2122 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2123 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2124
2125 case Stmt::CompoundStmtClass: {
2126 // C++1y allows compound-statements.
2127 if (!Cxx1yLoc.isValid())
2128 Cxx1yLoc = S->getBeginLoc();
2129
2130 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2131 for (auto *BodyIt : CompStmt->body()) {
2132 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2133 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2134 return false;
2135 }
2136 return true;
2137 }
2138
2139 case Stmt::IfStmtClass: {
2140 // C++1y allows if-statements.
2141 if (!Cxx1yLoc.isValid())
2142 Cxx1yLoc = S->getBeginLoc();
2143
2144 IfStmt *If = cast<IfStmt>(S);
2145 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2146 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2147 return false;
2148 if (If->getElse() &&
2149 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2150 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2151 return false;
2152 return true;
2153 }
2154
2155 case Stmt::WhileStmtClass:
2156 case Stmt::DoStmtClass:
2157 case Stmt::ForStmtClass:
2158 case Stmt::CXXForRangeStmtClass:
2159 case Stmt::ContinueStmtClass:
2160 // C++1y allows all of these. We don't allow them as extensions in C++11,
2161 // because they don't make sense without variable mutation.
2162 if (!SemaRef.getLangOpts().CPlusPlus14)
2163 break;
2164 if (!Cxx1yLoc.isValid())
2165 Cxx1yLoc = S->getBeginLoc();
2166 for (Stmt *SubStmt : S->children()) {
2167 if (SubStmt &&
2168 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2170 return false;
2171 }
2172 return true;
2173
2174 case Stmt::SwitchStmtClass:
2175 case Stmt::CaseStmtClass:
2176 case Stmt::DefaultStmtClass:
2177 case Stmt::BreakStmtClass:
2178 // C++1y allows switch-statements, and since they don't need variable
2179 // mutation, we can reasonably allow them in C++11 as an extension.
2180 if (!Cxx1yLoc.isValid())
2181 Cxx1yLoc = S->getBeginLoc();
2182 for (Stmt *SubStmt : S->children()) {
2183 if (SubStmt &&
2184 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2185 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2186 return false;
2187 }
2188 return true;
2189
2190 case Stmt::LabelStmtClass:
2191 case Stmt::GotoStmtClass:
2192 if (Cxx2bLoc.isInvalid())
2193 Cxx2bLoc = S->getBeginLoc();
2194 for (Stmt *SubStmt : S->children()) {
2195 if (SubStmt &&
2196 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2197 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2198 return false;
2199 }
2200 return true;
2201
2202 case Stmt::GCCAsmStmtClass:
2203 case Stmt::MSAsmStmtClass:
2204 // C++2a allows inline assembly statements.
2205 case Stmt::CXXTryStmtClass:
2206 if (Cxx2aLoc.isInvalid())
2207 Cxx2aLoc = S->getBeginLoc();
2208 for (Stmt *SubStmt : S->children()) {
2209 if (SubStmt &&
2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2212 return false;
2213 }
2214 return true;
2215
2216 case Stmt::CXXCatchStmtClass:
2217 // Do not bother checking the language mode (already covered by the
2218 // try block check).
2220 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2221 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222 return false;
2223 return true;
2224
2225 default:
2226 if (!isa<Expr>(S))
2227 break;
2228
2229 // C++1y allows expression-statements.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2236 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2237 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2238 }
2239 return false;
2240}
2241
2242/// Check the body for the given constexpr function declaration only contains
2243/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2244///
2245/// \return true if the body is OK, false if we have found or diagnosed a
2246/// problem.
2248 Stmt *Body,
2251
2252 if (isa<CXXTryStmt>(Body)) {
2253 // C++11 [dcl.constexpr]p3:
2254 // The definition of a constexpr function shall satisfy the following
2255 // constraints: [...]
2256 // - its function-body shall be = delete, = default, or a
2257 // compound-statement
2258 //
2259 // C++11 [dcl.constexpr]p4:
2260 // In the definition of a constexpr constructor, [...]
2261 // - its function-body shall not be a function-try-block;
2262 //
2263 // This restriction is lifted in C++2a, as long as inner statements also
2264 // apply the general constexpr rules.
2265 switch (Kind) {
2267 if (!SemaRef.getLangOpts().CPlusPlus20)
2268 return false;
2269 break;
2270
2272 SemaRef.Diag(Body->getBeginLoc(),
2273 !SemaRef.getLangOpts().CPlusPlus20
2274 ? diag::ext_constexpr_function_try_block_cxx20
2275 : diag::warn_cxx17_compat_constexpr_function_try_block)
2276 << isa<CXXConstructorDecl>(Dcl);
2277 break;
2278 }
2279 }
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 // [... list of cases ...]
2283 //
2284 // Note that walking the children here is enough to properly check for
2285 // CompoundStmt and CXXTryStmt body.
2286 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2287 for (Stmt *SubStmt : Body->children()) {
2288 if (SubStmt &&
2289 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2290 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2291 return false;
2292 }
2293
2295 // If this is only valid as an extension, report that we don't satisfy the
2296 // constraints of the current language.
2297 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2298 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2299 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2300 return false;
2301 } else if (Cxx2bLoc.isValid()) {
2302 SemaRef.Diag(Cxx2bLoc,
2303 SemaRef.getLangOpts().CPlusPlus23
2304 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2305 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2306 << isa<CXXConstructorDecl>(Dcl);
2307 } else if (Cxx2aLoc.isValid()) {
2308 SemaRef.Diag(Cxx2aLoc,
2309 SemaRef.getLangOpts().CPlusPlus20
2310 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2311 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2312 << isa<CXXConstructorDecl>(Dcl);
2313 } else if (Cxx1yLoc.isValid()) {
2314 SemaRef.Diag(Cxx1yLoc,
2315 SemaRef.getLangOpts().CPlusPlus14
2316 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2317 : diag::ext_constexpr_body_invalid_stmt)
2318 << isa<CXXConstructorDecl>(Dcl);
2319 }
2320
2321 if (const CXXConstructorDecl *Constructor
2322 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2323 const CXXRecordDecl *RD = Constructor->getParent();
2324 // DR1359:
2325 // - every non-variant non-static data member and base class sub-object
2326 // shall be initialized;
2327 // DR1460:
2328 // - if the class is a union having variant members, exactly one of them
2329 // shall be initialized;
2330 if (RD->isUnion()) {
2331 if (Constructor->getNumCtorInitializers() == 0 &&
2332 RD->hasVariantMembers()) {
2334 SemaRef.Diag(
2335 Dcl->getLocation(),
2336 SemaRef.getLangOpts().CPlusPlus20
2337 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2338 : diag::ext_constexpr_union_ctor_no_init);
2339 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2340 return false;
2341 }
2342 }
2343 } else if (!Constructor->isDependentContext() &&
2344 !Constructor->isDelegatingConstructor()) {
2345 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2346
2347 // Skip detailed checking if we have enough initializers, and we would
2348 // allow at most one initializer per member.
2349 bool AnyAnonStructUnionMembers = false;
2350 unsigned Fields = 0;
2352 E = RD->field_end(); I != E; ++I, ++Fields) {
2353 if (I->isAnonymousStructOrUnion()) {
2354 AnyAnonStructUnionMembers = true;
2355 break;
2356 }
2357 }
2358 // DR1460:
2359 // - if the class is a union-like class, but is not a union, for each of
2360 // its anonymous union members having variant members, exactly one of
2361 // them shall be initialized;
2362 if (AnyAnonStructUnionMembers ||
2363 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2364 // Check initialization of non-static data members. Base classes are
2365 // always initialized so do not need to be checked. Dependent bases
2366 // might not have initializers in the member initializer list.
2367 llvm::SmallSet<Decl*, 16> Inits;
2368 for (const auto *I: Constructor->inits()) {
2369 if (FieldDecl *FD = I->getMember())
2370 Inits.insert(FD);
2371 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2372 Inits.insert(ID->chain_begin(), ID->chain_end());
2373 }
2374
2375 bool Diagnosed = false;
2376 for (auto *I : RD->fields())
2377 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2378 Kind))
2379 return false;
2380 }
2381 }
2382 } else {
2383 if (ReturnStmts.empty()) {
2384 switch (Kind) {
2387 return false;
2388 break;
2389
2391 // The formal requirements don't include this rule in C++14, even
2392 // though the "must be able to produce a constant expression" rules
2393 // still imply it in some cases.
2394 if (!SemaRef.getLangOpts().CPlusPlus14)
2395 return false;
2396 break;
2397 }
2398 } else if (ReturnStmts.size() > 1) {
2399 switch (Kind) {
2401 SemaRef.Diag(
2402 ReturnStmts.back(),
2403 SemaRef.getLangOpts().CPlusPlus14
2404 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2405 : diag::ext_constexpr_body_multiple_return);
2406 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2407 SemaRef.Diag(ReturnStmts[I],
2408 diag::note_constexpr_body_previous_return);
2409 break;
2410
2412 if (!SemaRef.getLangOpts().CPlusPlus14)
2413 return false;
2414 break;
2415 }
2416 }
2417 }
2418
2419 // C++11 [dcl.constexpr]p5:
2420 // if no function argument values exist such that the function invocation
2421 // substitution would produce a constant expression, the program is
2422 // ill-formed; no diagnostic required.
2423 // C++11 [dcl.constexpr]p3:
2424 // - every constructor call and implicit conversion used in initializing the
2425 // return value shall be one of those allowed in a constant expression.
2426 // C++11 [dcl.constexpr]p4:
2427 // - every constructor involved in initializing non-static data members and
2428 // base class sub-objects shall be a constexpr constructor.
2429 //
2430 // Note that this rule is distinct from the "requirements for a constexpr
2431 // function", so is not checked in CheckValid mode. Because the check for
2432 // constexpr potential is expensive, skip the check if the diagnostic is
2433 // disabled, the function is declared in a system header, or we're in C++23
2434 // or later mode (see https://wg21.link/P2448).
2435 bool SkipCheck =
2436 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2439 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2441 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2443 SemaRef.Diag(Dcl->getLocation(),
2444 diag::ext_constexpr_function_never_constant_expr)
2445 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2446 << Dcl->getNameInfo().getSourceRange();
2447 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2448 SemaRef.Diag(Diags[I].first, Diags[I].second);
2449 // Don't return false here: we allow this for compatibility in
2450 // system headers.
2451 }
2452
2453 return true;
2454}
2455
2457 const FunctionDecl *Dcl) {
2458 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2460 // Skip emitting a missing return error diagnostic for non-void functions
2461 // since C++23 no longer mandates constexpr functions to yield constant
2462 // expressions.
2463 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2464 return true;
2465
2466 // C++14 doesn't require constexpr functions to contain a 'return'
2467 // statement. We still do, unless the return type might be void, because
2468 // otherwise if there's no return statement, the function cannot
2469 // be used in a core constant expression.
2470 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2471 SemaRef.Diag(Dcl->getLocation(),
2472 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2473 : diag::err_constexpr_body_no_return)
2474 << Dcl->isConsteval();
2475 return OK;
2476}
2477
2479 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2481 return true;
2485 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2486 if (it != UndefinedButUsed.end()) {
2487 Diag(it->second, diag::err_immediate_function_used_before_definition)
2488 << it->first;
2489 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2490 if (FD->isImmediateFunction() && !FD->isConsteval())
2492 return false;
2493 }
2494 }
2495 return true;
2496}
2497
2499 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2500 "expected an immediate function");
2501 assert(FD->hasBody() && "expected the function to have a body");
2502 struct ImmediateEscalatingExpressionsVisitor
2503 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2504
2506 Sema &SemaRef;
2507
2508 const FunctionDecl *ImmediateFn;
2509 bool ImmediateFnIsConstructor;
2510 CXXConstructorDecl *CurrentConstructor = nullptr;
2511 CXXCtorInitializer *CurrentInit = nullptr;
2512
2513 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2514 : SemaRef(SemaRef), ImmediateFn(FD),
2515 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2516
2517 bool shouldVisitImplicitCode() const { return true; }
2518 bool shouldVisitLambdaBody() const { return false; }
2519
2520 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2523 if (CurrentConstructor && CurrentInit) {
2524 Loc = CurrentConstructor->getLocation();
2525 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2526 : SourceRange();
2527 }
2528
2529 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2530
2531 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2532 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2533 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2534 << (InitializedField != nullptr)
2535 << (CurrentInit && !CurrentInit->isWritten())
2536 << InitializedField << Range;
2537 }
2538 bool TraverseCallExpr(CallExpr *E) {
2539 if (const auto *DR =
2540 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2541 DR && DR->isImmediateEscalating()) {
2542 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2543 return false;
2544 }
2545
2546 for (Expr *A : E->arguments())
2547 if (!getDerived().TraverseStmt(A))
2548 return false;
2549
2550 return true;
2551 }
2552
2553 bool VisitDeclRefExpr(DeclRefExpr *E) {
2554 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2555 ReferencedFn && E->isImmediateEscalating()) {
2556 Diag(E, ReferencedFn, /*IsCall=*/false);
2557 return false;
2558 }
2559
2560 return true;
2561 }
2562
2563 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2564 CXXConstructorDecl *D = E->getConstructor();
2565 if (E->isImmediateEscalating()) {
2566 Diag(E, D, /*IsCall=*/true);
2567 return false;
2568 }
2569 return true;
2570 }
2571
2572 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2573 llvm::SaveAndRestore RAII(CurrentInit, Init);
2574 return Base::TraverseConstructorInitializer(Init);
2575 }
2576
2577 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2578 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2579 return Base::TraverseCXXConstructorDecl(Ctr);
2580 }
2581
2582 bool TraverseType(QualType T) { return true; }
2583 bool VisitBlockExpr(BlockExpr *T) { return true; }
2584
2585 } Visitor(*this, FD);
2586 Visitor.TraverseDecl(FD);
2587}
2588
2590 assert(getLangOpts().CPlusPlus && "No class names in C!");
2591
2592 if (SS && SS->isInvalid())
2593 return nullptr;
2594
2595 if (SS && SS->isNotEmpty()) {
2596 DeclContext *DC = computeDeclContext(*SS, true);
2597 return dyn_cast_or_null<CXXRecordDecl>(DC);
2598 }
2599
2600 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2601}
2602
2604 const CXXScopeSpec *SS) {
2605 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2606 return CurDecl && &II == CurDecl->getIdentifier();
2607}
2608
2610 assert(getLangOpts().CPlusPlus && "No class names in C!");
2611
2612 if (!getLangOpts().SpellChecking)
2613 return false;
2614
2615 CXXRecordDecl *CurDecl;
2616 if (SS && SS->isSet() && !SS->isInvalid()) {
2617 DeclContext *DC = computeDeclContext(*SS, true);
2618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2619 } else
2620 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2621
2622 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2623 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2624 < II->getLength()) {
2625 II = CurDecl->getIdentifier();
2626 return true;
2627 }
2628
2629 return false;
2630}
2631
2633 SourceRange SpecifierRange,
2634 bool Virtual, AccessSpecifier Access,
2635 TypeSourceInfo *TInfo,
2636 SourceLocation EllipsisLoc) {
2637 QualType BaseType = TInfo->getType();
2638 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2639 if (BaseType->containsErrors()) {
2640 // Already emitted a diagnostic when parsing the error type.
2641 return nullptr;
2642 }
2643
2644 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2645 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2646 << TInfo->getTypeLoc().getSourceRange();
2647 EllipsisLoc = SourceLocation();
2648 }
2649
2650 auto *BaseDecl =
2651 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2652 // C++ [class.derived.general]p2:
2653 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2654 // that is not an incompletely defined class; any cv-qualifiers are
2655 // ignored.
2656 if (BaseDecl) {
2657 // C++ [class.union.general]p4:
2658 // [...] A union shall not be used as a base class.
2659 if (BaseDecl->isUnion()) {
2660 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2661 return nullptr;
2662 }
2663
2664 // For the MS ABI, propagate DLL attributes to base class templates.
2666 Context.getTargetInfo().getTriple().isPS()) {
2667 if (Attr *ClassAttr = getDLLAttr(Class)) {
2668 if (auto *BaseSpec =
2669 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2670 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2671 BaseLoc);
2672 }
2673 }
2674 }
2675
2676 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2677 SpecifierRange)) {
2678 Class->setInvalidDecl();
2679 return nullptr;
2680 }
2681
2682 BaseDecl = BaseDecl->getDefinition();
2683 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2684
2685 // Microsoft docs say:
2686 // "If a base-class has a code_seg attribute, derived classes must have the
2687 // same attribute."
2688 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2689 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2690 if ((DerivedCSA || BaseCSA) &&
2691 (!BaseCSA || !DerivedCSA ||
2692 BaseCSA->getName() != DerivedCSA->getName())) {
2693 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2694 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2695 << BaseDecl;
2696 return nullptr;
2697 }
2698
2699 // A class which contains a flexible array member is not suitable for use as
2700 // a base class:
2701 // - If the layout determines that a base comes before another base,
2702 // the flexible array member would index into the subsequent base.
2703 // - If the layout determines that base comes before the derived class,
2704 // the flexible array member would index into the derived class.
2705 if (BaseDecl->hasFlexibleArrayMember()) {
2706 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2707 << BaseDecl->getDeclName();
2708 return nullptr;
2709 }
2710
2711 // C++ [class]p3:
2712 // If a class is marked final and it appears as a base-type-specifier in
2713 // base-clause, the program is ill-formed.
2714 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2715 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2716 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2717 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2718 << BaseDecl->getDeclName() << FA->getRange();
2719 return nullptr;
2720 }
2721
2722 // If the base class is invalid the derived class is as well.
2723 if (BaseDecl->isInvalidDecl())
2724 Class->setInvalidDecl();
2725 } else if (BaseType->isDependentType()) {
2726 // Make sure that we don't make an ill-formed AST where the type of the
2727 // Class is non-dependent and its attached base class specifier is an
2728 // dependent type, which violates invariants in many clang code paths (e.g.
2729 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2730 // explicitly mark the Class decl invalid. The diagnostic was already
2731 // emitted.
2732 if (!Class->isDependentContext())
2733 Class->setInvalidDecl();
2734 } else {
2735 // The base class is some non-dependent non-class type.
2736 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2737 return nullptr;
2738 }
2739
2740 // In HLSL, unspecified class access is public rather than private.
2741 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2742 Access == AS_none)
2743 Access = AS_public;
2744
2745 // Create the base specifier.
2746 return new (Context) CXXBaseSpecifier(
2747 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2748 Access, TInfo, EllipsisLoc);
2749}
2750
2752 const ParsedAttributesView &Attributes,
2753 bool Virtual, AccessSpecifier Access,
2754 ParsedType basetype, SourceLocation BaseLoc,
2755 SourceLocation EllipsisLoc) {
2756 if (!classdecl)
2757 return true;
2758
2759 AdjustDeclIfTemplate(classdecl);
2760 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2761 if (!Class)
2762 return true;
2763
2764 // We haven't yet attached the base specifiers.
2765 Class->setIsParsingBaseSpecifiers();
2766
2767 // We do not support any C++11 attributes on base-specifiers yet.
2768 // Diagnose any attributes we see.
2769 for (const ParsedAttr &AL : Attributes) {
2770 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2771 continue;
2772 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2773 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2774 << AL << AL.getRange();
2775 else
2776 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2777 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2778 }
2779
2780 TypeSourceInfo *TInfo = nullptr;
2781 GetTypeFromParser(basetype, &TInfo);
2782
2783 if (EllipsisLoc.isInvalid() &&
2784 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2786 return true;
2787
2788 // C++ [class.union.general]p4:
2789 // [...] A union shall not have base classes.
2790 if (Class->isUnion()) {
2791 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2792 << SpecifierRange;
2793 return true;
2794 }
2795
2796 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2797 Virtual, Access, TInfo,
2798 EllipsisLoc))
2799 return BaseSpec;
2800
2801 Class->setInvalidDecl();
2802 return true;
2803}
2804
2805/// Use small set to collect indirect bases. As this is only used
2806/// locally, there's no need to abstract the small size parameter.
2808
2809/// Recursively add the bases of Type. Don't add Type itself.
2810static void
2812 const QualType &Type)
2813{
2814 // Even though the incoming type is a base, it might not be
2815 // a class -- it could be a template parm, for instance.
2816 if (auto Rec = Type->getAs<RecordType>()) {
2817 auto Decl = Rec->getAsCXXRecordDecl();
2818
2819 // Iterate over its bases.
2820 for (const auto &BaseSpec : Decl->bases()) {
2821 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2823 if (Set.insert(Base).second)
2824 // If we've not already seen it, recurse.
2826 }
2827 }
2828}
2829
2832 if (Bases.empty())
2833 return false;
2834
2835 // Used to keep track of which base types we have already seen, so
2836 // that we can properly diagnose redundant direct base types. Note
2837 // that the key is always the unqualified canonical type of the base
2838 // class.
2839 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2840
2841 // Used to track indirect bases so we can see if a direct base is
2842 // ambiguous.
2843 IndirectBaseSet IndirectBaseTypes;
2844
2845 // Copy non-redundant base specifiers into permanent storage.
2846 unsigned NumGoodBases = 0;
2847 bool Invalid = false;
2848 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2849 QualType NewBaseType
2850 = Context.getCanonicalType(Bases[idx]->getType());
2851 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2852
2853 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2854 if (KnownBase) {
2855 // C++ [class.mi]p3:
2856 // A class shall not be specified as a direct base class of a
2857 // derived class more than once.
2858 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2859 << KnownBase->getType() << Bases[idx]->getSourceRange();
2860
2861 // Delete the duplicate base class specifier; we're going to
2862 // overwrite its pointer later.
2863 Context.Deallocate(Bases[idx]);
2864
2865 Invalid = true;
2866 } else {
2867 // Okay, add this new base class.
2868 KnownBase = Bases[idx];
2869 Bases[NumGoodBases++] = Bases[idx];
2870
2871 if (NewBaseType->isDependentType())
2872 continue;
2873 // Note this base's direct & indirect bases, if there could be ambiguity.
2874 if (Bases.size() > 1)
2875 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2876
2877 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2878 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2879 if (Class->isInterface() &&
2880 (!RD->isInterfaceLike() ||
2881 KnownBase->getAccessSpecifier() != AS_public)) {
2882 // The Microsoft extension __interface does not permit bases that
2883 // are not themselves public interfaces.
2884 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2885 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2886 << RD->getSourceRange();
2887 Invalid = true;
2888 }
2889 if (RD->hasAttr<WeakAttr>())
2890 Class->addAttr(WeakAttr::CreateImplicit(Context));
2891 }
2892 }
2893 }
2894
2895 // Attach the remaining base class specifiers to the derived class.
2896 Class->setBases(Bases.data(), NumGoodBases);
2897
2898 // Check that the only base classes that are duplicate are virtual.
2899 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2900 // Check whether this direct base is inaccessible due to ambiguity.
2901 QualType BaseType = Bases[idx]->getType();
2902
2903 // Skip all dependent types in templates being used as base specifiers.
2904 // Checks below assume that the base specifier is a CXXRecord.
2905 if (BaseType->isDependentType())
2906 continue;
2907
2908 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2910
2911 if (IndirectBaseTypes.count(CanonicalBase)) {
2912 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2913 /*DetectVirtual=*/true);
2914 bool found
2915 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2916 assert(found);
2917 (void)found;
2918
2919 if (Paths.isAmbiguous(CanonicalBase))
2920 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2921 << BaseType << getAmbiguousPathsDisplayString(Paths)
2922 << Bases[idx]->getSourceRange();
2923 else
2924 assert(Bases[idx]->isVirtual());
2925 }
2926
2927 // Delete the base class specifier, since its data has been copied
2928 // into the CXXRecordDecl.
2929 Context.Deallocate(Bases[idx]);
2930 }
2931
2932 return Invalid;
2933}
2934
2937 if (!ClassDecl || Bases.empty())
2938 return;
2939
2940 AdjustDeclIfTemplate(ClassDecl);
2941 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2942}
2943
2945 if (!getLangOpts().CPlusPlus)
2946 return false;
2947
2948 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2949 if (!DerivedRD)
2950 return false;
2951
2952 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2953 if (!BaseRD)
2954 return false;
2955
2956 // If either the base or the derived type is invalid, don't try to
2957 // check whether one is derived from the other.
2958 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2959 return false;
2960
2961 // FIXME: In a modules build, do we need the entire path to be visible for us
2962 // to be able to use the inheritance relationship?
2963 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2964 return false;
2965
2966 return DerivedRD->isDerivedFrom(BaseRD);
2967}
2968
2970 CXXBasePaths &Paths) {
2971 if (!getLangOpts().CPlusPlus)
2972 return false;
2973
2974 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2975 if (!DerivedRD)
2976 return false;
2977
2978 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2979 if (!BaseRD)
2980 return false;
2981
2982 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2983 return false;
2984
2985 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2986}
2987
2989 CXXCastPath &BasePathArray) {
2990 // We first go backward and check if we have a virtual base.
2991 // FIXME: It would be better if CXXBasePath had the base specifier for
2992 // the nearest virtual base.
2993 unsigned Start = 0;
2994 for (unsigned I = Path.size(); I != 0; --I) {
2995 if (Path[I - 1].Base->isVirtual()) {
2996 Start = I - 1;
2997 break;
2998 }
2999 }
3000
3001 // Now add all bases.
3002 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3003 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3004}
3005
3006
3008 CXXCastPath &BasePathArray) {
3009 assert(BasePathArray.empty() && "Base path array must be empty!");
3010 assert(Paths.isRecordingPaths() && "Must record paths!");
3011 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3012}
3013
3014bool
3016 unsigned InaccessibleBaseID,
3017 unsigned AmbiguousBaseConvID,
3019 DeclarationName Name,
3020 CXXCastPath *BasePath,
3021 bool IgnoreAccess) {
3022 // First, determine whether the path from Derived to Base is
3023 // ambiguous. This is slightly more expensive than checking whether
3024 // the Derived to Base conversion exists, because here we need to
3025 // explore multiple paths to determine if there is an ambiguity.
3026 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3027 /*DetectVirtual=*/false);
3028 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3029 if (!DerivationOkay)
3030 return true;
3031
3032 const CXXBasePath *Path = nullptr;
3033 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3034 Path = &Paths.front();
3035
3036 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3037 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3038 // user to access such bases.
3039 if (!Path && getLangOpts().MSVCCompat) {
3040 for (const CXXBasePath &PossiblePath : Paths) {
3041 if (PossiblePath.size() == 1) {
3042 Path = &PossiblePath;
3043 if (AmbiguousBaseConvID)
3044 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3045 << Base << Derived << Range;
3046 break;
3047 }
3048 }
3049 }
3050
3051 if (Path) {
3052 if (!IgnoreAccess) {
3053 // Check that the base class can be accessed.
3054 switch (
3055 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3056 case AR_inaccessible:
3057 return true;
3058 case AR_accessible:
3059 case AR_dependent:
3060 case AR_delayed:
3061 break;
3062 }
3063 }
3064
3065 // Build a base path if necessary.
3066 if (BasePath)
3067 ::BuildBasePathArray(*Path, *BasePath);
3068 return false;
3069 }
3070
3071 if (AmbiguousBaseConvID) {
3072 // We know that the derived-to-base conversion is ambiguous, and
3073 // we're going to produce a diagnostic. Perform the derived-to-base
3074 // search just one more time to compute all of the possible paths so
3075 // that we can print them out. This is more expensive than any of
3076 // the previous derived-to-base checks we've done, but at this point
3077 // performance isn't as much of an issue.
3078 Paths.clear();
3079 Paths.setRecordingPaths(true);
3080 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3081 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3082 (void)StillOkay;
3083
3084 // Build up a textual representation of the ambiguous paths, e.g.,
3085 // D -> B -> A, that will be used to illustrate the ambiguous
3086 // conversions in the diagnostic. We only print one of the paths
3087 // to each base class subobject.
3088 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3089
3090 Diag(Loc, AmbiguousBaseConvID)
3091 << Derived << Base << PathDisplayStr << Range << Name;
3092 }
3093 return true;
3094}
3095
3096bool
3099 CXXCastPath *BasePath,
3100 bool IgnoreAccess) {
3102 Derived, Base, diag::err_upcast_to_inaccessible_base,
3103 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3104 BasePath, IgnoreAccess);
3105}
3106
3108 std::string PathDisplayStr;
3109 std::set<unsigned> DisplayedPaths;
3110 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3111 Path != Paths.end(); ++Path) {
3112 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3113 // We haven't displayed a path to this particular base
3114 // class subobject yet.
3115 PathDisplayStr += "\n ";
3116 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3117 for (CXXBasePath::const_iterator Element = Path->begin();
3118 Element != Path->end(); ++Element)
3119 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3120 }
3121 }
3122
3123 return PathDisplayStr;
3124}
3125
3126//===----------------------------------------------------------------------===//
3127// C++ class member Handling
3128//===----------------------------------------------------------------------===//
3129
3131 SourceLocation ColonLoc,
3132 const ParsedAttributesView &Attrs) {
3133 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3135 ASLoc, ColonLoc);
3136 CurContext->addHiddenDecl(ASDecl);
3137 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3138}
3139
3141 if (D->isInvalidDecl())
3142 return;
3143
3144 // We only care about "override" and "final" declarations.
3145 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3146 return;
3147
3148 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3149
3150 // We can't check dependent instance methods.
3151 if (MD && MD->isInstance() &&
3152 (MD->getParent()->hasAnyDependentBases() ||
3153 MD->getType()->isDependentType()))
3154 return;
3155
3156 if (MD && !MD->isVirtual()) {
3157 // If we have a non-virtual method, check if it hides a virtual method.
3158 // (In that case, it's most likely the method has the wrong type.)
3159 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3160 FindHiddenVirtualMethods(MD, OverloadedMethods);
3161
3162 if (!OverloadedMethods.empty()) {
3163 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3164 Diag(OA->getLocation(),
3165 diag::override_keyword_hides_virtual_member_function)
3166 << "override" << (OverloadedMethods.size() > 1);
3167 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3168 Diag(FA->getLocation(),
3169 diag::override_keyword_hides_virtual_member_function)
3170 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3171 << (OverloadedMethods.size() > 1);
3172 }
3173 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3174 MD->setInvalidDecl();
3175 return;
3176 }
3177 // Fall through into the general case diagnostic.
3178 // FIXME: We might want to attempt typo correction here.
3179 }
3180
3181 if (!MD || !MD->isVirtual()) {
3182 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3183 Diag(OA->getLocation(),
3184 diag::override_keyword_only_allowed_on_virtual_member_functions)
3185 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3186 D->dropAttr<OverrideAttr>();
3187 }
3188 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3189 Diag(FA->getLocation(),
3190 diag::override_keyword_only_allowed_on_virtual_member_functions)
3191 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3192 << FixItHint::CreateRemoval(FA->getLocation());
3193 D->dropAttr<FinalAttr>();
3194 }
3195 return;
3196 }
3197
3198 // C++11 [class.virtual]p5:
3199 // If a function is marked with the virt-specifier override and
3200 // does not override a member function of a base class, the program is
3201 // ill-formed.
3202 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3203 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3204 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3205 << MD->getDeclName();
3206}
3207
3209 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3210 return;
3211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3212 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3213 return;
3214
3216 SourceLocation SpellingLoc = Loc;
3217 if (getSourceManager().isMacroArgExpansion(Loc))
3219 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3220 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3221 return;
3222
3223 if (MD->size_overridden_methods() > 0) {
3224 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3225 unsigned DiagID =
3226 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3227 ? DiagInconsistent
3228 : DiagSuggest;
3229 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3230 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3231 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3232 };
3233 if (isa<CXXDestructorDecl>(MD))
3234 EmitDiag(
3235 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3236 diag::warn_suggest_destructor_marked_not_override_overriding);
3237 else
3238 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3239 diag::warn_suggest_function_marked_not_override_overriding);
3240 }
3241}
3242
3244 const CXXMethodDecl *Old) {
3245 FinalAttr *FA = Old->getAttr<FinalAttr>();
3246 if (!FA)
3247 return false;
3248
3249 Diag(New->getLocation(), diag::err_final_function_overridden)
3250 << New->getDeclName()
3251 << FA->isSpelledAsSealed();
3252 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3253 return true;
3254}
3255
3257 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3258 // FIXME: Destruction of ObjC lifetime types has side-effects.
3259 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3260 return !RD->isCompleteDefinition() ||
3261 !RD->hasTrivialDefaultConstructor() ||
3262 !RD->hasTrivialDestructor();
3263 return false;
3264}
3265
3266void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3267 DeclarationName FieldName,
3268 const CXXRecordDecl *RD,
3269 bool DeclIsField) {
3270 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3271 return;
3272
3273 // To record a shadowed field in a base
3274 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3275 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3276 CXXBasePath &Path) {
3277 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3278 // Record an ambiguous path directly
3279 if (Bases.find(Base) != Bases.end())
3280 return true;
3281 for (const auto Field : Base->lookup(FieldName)) {
3282 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3283 Field->getAccess() != AS_private) {
3284 assert(Field->getAccess() != AS_none);
3285 assert(Bases.find(Base) == Bases.end());
3286 Bases[Base] = Field;
3287 return true;
3288 }
3289 }
3290 return false;
3291 };
3292
3293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3294 /*DetectVirtual=*/true);
3295 if (!RD->lookupInBases(FieldShadowed, Paths))
3296 return;
3297
3298 for (const auto &P : Paths) {
3299 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3300 auto It = Bases.find(Base);
3301 // Skip duplicated bases
3302 if (It == Bases.end())
3303 continue;
3304 auto BaseField = It->second;
3305 assert(BaseField->getAccess() != AS_private);
3306 if (AS_none !=
3307 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3308 Diag(Loc, diag::warn_shadow_field)
3309 << FieldName << RD << Base << DeclIsField;
3310 Diag(BaseField->getLocation(), diag::note_shadow_field);
3311 Bases.erase(It);
3312 }
3313 }
3314}
3315
3316NamedDecl *
3318 MultiTemplateParamsArg TemplateParameterLists,
3319 Expr *BW, const VirtSpecifiers &VS,
3320 InClassInitStyle InitStyle) {
3321 const DeclSpec &DS = D.getDeclSpec();
3323 DeclarationName Name = NameInfo.getName();
3324 SourceLocation Loc = NameInfo.getLoc();
3325
3326 // For anonymous bitfields, the location should point to the type.
3327 if (Loc.isInvalid())
3328 Loc = D.getBeginLoc();
3329
3330 Expr *BitWidth = static_cast<Expr*>(BW);
3331
3332 assert(isa<CXXRecordDecl>(CurContext));
3333 assert(!DS.isFriendSpecified());
3334
3335 bool isFunc = D.isDeclarationOfFunction();
3336 const ParsedAttr *MSPropertyAttr =
3337 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3338
3339 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3340 // The Microsoft extension __interface only permits public member functions
3341 // and prohibits constructors, destructors, operators, non-public member
3342 // functions, static methods and data members.
3343 unsigned InvalidDecl;
3344 bool ShowDeclName = true;
3345 if (!isFunc &&
3346 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3347 InvalidDecl = 0;
3348 else if (!isFunc)
3349 InvalidDecl = 1;
3350 else if (AS != AS_public)
3351 InvalidDecl = 2;
3353 InvalidDecl = 3;
3354 else switch (Name.getNameKind()) {
3356 InvalidDecl = 4;
3357 ShowDeclName = false;
3358 break;
3359
3361 InvalidDecl = 5;
3362 ShowDeclName = false;
3363 break;
3364
3367 InvalidDecl = 6;
3368 break;
3369
3370 default:
3371 InvalidDecl = 0;
3372 break;
3373 }
3374
3375 if (InvalidDecl) {
3376 if (ShowDeclName)
3377 Diag(Loc, diag::err_invalid_member_in_interface)
3378 << (InvalidDecl-1) << Name;
3379 else
3380 Diag(Loc, diag::err_invalid_member_in_interface)
3381 << (InvalidDecl-1) << "";
3382 return nullptr;
3383 }
3384 }
3385
3386 // C++ 9.2p6: A member shall not be declared to have automatic storage
3387 // duration (auto, register) or with the extern storage-class-specifier.
3388 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3389 // data members and cannot be applied to names declared const or static,
3390 // and cannot be applied to reference members.
3391 switch (DS.getStorageClassSpec()) {
3395 break;
3397 if (isFunc) {
3398 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3399
3400 // FIXME: It would be nicer if the keyword was ignored only for this
3401 // declarator. Otherwise we could get follow-up errors.
3402 D.getMutableDeclSpec().ClearStorageClassSpecs();
3403 }
3404 break;
3405 default:
3407 diag::err_storageclass_invalid_for_member);
3408 D.getMutableDeclSpec().ClearStorageClassSpecs();
3409 break;
3410 }
3411
3412 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3414 !isFunc && TemplateParameterLists.empty();
3415
3416 if (DS.hasConstexprSpecifier() && isInstField) {
3418 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3419 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3420 if (InitStyle == ICIS_NoInit) {
3421 B << 0 << 0;
3422 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3423 B << FixItHint::CreateRemoval(ConstexprLoc);
3424 else {
3425 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3426 D.getMutableDeclSpec().ClearConstexprSpec();
3427 const char *PrevSpec;
3428 unsigned DiagID;
3429 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3430 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3431 (void)Failed;
3432 assert(!Failed && "Making a constexpr member const shouldn't fail");
3433 }
3434 } else {
3435 B << 1;
3436 const char *PrevSpec;
3437 unsigned DiagID;
3438 if (D.getMutableDeclSpec().SetStorageClassSpec(
3439 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3442 "This is the only DeclSpec that should fail to be applied");
3443 B << 1;
3444 } else {
3445 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3446 isInstField = false;
3447 }
3448 }
3449 }
3450
3452 if (isInstField) {
3453 CXXScopeSpec &SS = D.getCXXScopeSpec();
3454
3455 // Data members must have identifiers for names.
3456 if (!Name.isIdentifier()) {
3457 Diag(Loc, diag::err_bad_variable_name)
3458 << Name;
3459 return nullptr;
3460 }
3461
3462 IdentifierInfo *II = Name.getAsIdentifierInfo();
3463 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3464 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3465 << II
3466 << SourceRange(D.getName().TemplateId->LAngleLoc,
3467 D.getName().TemplateId->RAngleLoc)
3468 << D.getName().TemplateId->LAngleLoc;
3469 D.SetIdentifier(II, Loc);
3470 }
3471
3472 if (SS.isSet() && !SS.isInvalid()) {
3473 // The user provided a superfluous scope specifier inside a class
3474 // definition:
3475 //
3476 // class X {
3477 // int X::member;
3478 // };
3479 if (DeclContext *DC = computeDeclContext(SS, false)) {
3480 TemplateIdAnnotation *TemplateId =
3482 ? D.getName().TemplateId
3483 : nullptr;
3484 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3485 TemplateId,
3486 /*IsMemberSpecialization=*/false);
3487 } else {
3488 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3489 << Name << SS.getRange();
3490 }
3491 SS.clear();
3492 }
3493
3494 if (MSPropertyAttr) {
3495 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3496 BitWidth, InitStyle, AS, *MSPropertyAttr);
3497 if (!Member)
3498 return nullptr;
3499 isInstField = false;
3500 } else {
3501 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3502 BitWidth, InitStyle, AS);
3503 if (!Member)
3504 return nullptr;
3505 }
3506
3507 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3508 } else {
3509 Member = HandleDeclarator(S, D, TemplateParameterLists);
3510 if (!Member)
3511 return nullptr;
3512
3513 // Non-instance-fields can't have a bitfield.
3514 if (BitWidth) {
3515 if (Member->isInvalidDecl()) {
3516 // don't emit another diagnostic.
3517 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3518 // C++ 9.6p3: A bit-field shall not be a static member.
3519 // "static member 'A' cannot be a bit-field"
3520 Diag(Loc, diag::err_static_not_bitfield)
3521 << Name << BitWidth->getSourceRange();
3522 } else if (isa<TypedefDecl>(Member)) {
3523 // "typedef member 'x' cannot be a bit-field"
3524 Diag(Loc, diag::err_typedef_not_bitfield)
3525 << Name << BitWidth->getSourceRange();
3526 } else {
3527 // A function typedef ("typedef int f(); f a;").
3528 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3529 Diag(Loc, diag::err_not_integral_type_bitfield)
3530 << Name << cast<ValueDecl>(Member)->getType()
3531 << BitWidth->getSourceRange();
3532 }
3533
3534 BitWidth = nullptr;
3535 Member->setInvalidDecl();
3536 }
3537
3538 NamedDecl *NonTemplateMember = Member;
3539 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3540 NonTemplateMember = FunTmpl->getTemplatedDecl();
3541 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3542 NonTemplateMember = VarTmpl->getTemplatedDecl();
3543
3544 Member->setAccess(AS);
3545
3546 // If we have declared a member function template or static data member
3547 // template, set the access of the templated declaration as well.
3548 if (NonTemplateMember != Member)
3549 NonTemplateMember->setAccess(AS);
3550
3551 // C++ [temp.deduct.guide]p3:
3552 // A deduction guide [...] for a member class template [shall be
3553 // declared] with the same access [as the template].
3554 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3555 auto *TD = DG->getDeducedTemplate();
3556 // Access specifiers are only meaningful if both the template and the
3557 // deduction guide are from the same scope.
3558 if (AS != TD->getAccess() &&
3559 TD->getDeclContext()->getRedeclContext()->Equals(
3560 DG->getDeclContext()->getRedeclContext())) {
3561 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3562 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3563 << TD->getAccess();
3564 const AccessSpecDecl *LastAccessSpec = nullptr;
3565 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3566 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3567 LastAccessSpec = AccessSpec;
3568 }
3569 assert(LastAccessSpec && "differing access with no access specifier");
3570 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3571 << AS;
3572 }
3573 }
3574 }
3575
3576 if (VS.isOverrideSpecified())
3577 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3578 if (VS.isFinalSpecified())
3579 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3581 ? FinalAttr::Keyword_sealed
3582 : FinalAttr::Keyword_final));
3583
3584 if (VS.getLastLocation().isValid()) {
3585 // Update the end location of a method that has a virt-specifiers.
3586 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3587 MD->setRangeEnd(VS.getLastLocation());
3588 }
3589
3591
3592 assert((Name || isInstField) && "No identifier for non-field ?");
3593
3594 if (isInstField) {
3595 FieldDecl *FD = cast<FieldDecl>(Member);
3596 FieldCollector->Add(FD);
3597
3598 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3599 // Remember all explicit private FieldDecls that have a name, no side
3600 // effects and are not part of a dependent type declaration.
3601
3602 auto DeclHasUnusedAttr = [](const QualType &T) {
3603 if (const TagDecl *TD = T->getAsTagDecl())
3604 return TD->hasAttr<UnusedAttr>();
3605 if (const TypedefType *TDT = T->getAs<TypedefType>())
3606 return TDT->getDecl()->hasAttr<UnusedAttr>();
3607 return false;
3608 };
3609
3610 if (!FD->isImplicit() && FD->getDeclName() &&
3611 FD->getAccess() == AS_private &&
3612 !FD->hasAttr<UnusedAttr>() &&
3613 !FD->getParent()->isDependentContext() &&
3614 !DeclHasUnusedAttr(FD->getType()) &&
3616 UnusedPrivateFields.insert(FD);
3617 }
3618 }
3619
3620 return Member;
3621}
3622
3623namespace {
3624 class UninitializedFieldVisitor
3625 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3626 Sema &S;
3627 // List of Decls to generate a warning on. Also remove Decls that become
3628 // initialized.
3629 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3630 // List of base classes of the record. Classes are removed after their
3631 // initializers.
3632 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3633 // Vector of decls to be removed from the Decl set prior to visiting the
3634 // nodes. These Decls may have been initialized in the prior initializer.
3636 // If non-null, add a note to the warning pointing back to the constructor.
3637 const CXXConstructorDecl *Constructor;
3638 // Variables to hold state when processing an initializer list. When
3639 // InitList is true, special case initialization of FieldDecls matching
3640 // InitListFieldDecl.
3641 bool InitList;
3642 FieldDecl *InitListFieldDecl;
3643 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3644
3645 public:
3647 UninitializedFieldVisitor(Sema &S,
3648 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3649 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3650 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3651 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3652
3653 // Returns true if the use of ME is not an uninitialized use.
3654 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3655 bool CheckReferenceOnly) {
3657 bool ReferenceField = false;
3658 while (ME) {
3659 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3660 if (!FD)
3661 return false;
3662 Fields.push_back(FD);
3663 if (FD->getType()->isReferenceType())
3664 ReferenceField = true;
3665 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3666 }
3667
3668 // Binding a reference to an uninitialized field is not an
3669 // uninitialized use.
3670 if (CheckReferenceOnly && !ReferenceField)
3671 return true;
3672
3673 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3674 // Discard the first field since it is the field decl that is being
3675 // initialized.
3676 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3677 UsedFieldIndex.push_back(FD->getFieldIndex());
3678
3679 for (auto UsedIter = UsedFieldIndex.begin(),
3680 UsedEnd = UsedFieldIndex.end(),
3681 OrigIter = InitFieldIndex.begin(),
3682 OrigEnd = InitFieldIndex.end();
3683 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3684 if (*UsedIter < *OrigIter)
3685 return true;
3686 if (*UsedIter > *OrigIter)
3687 break;
3688 }
3689
3690 return false;
3691 }
3692
3693 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3694 bool AddressOf) {
3695 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3696 return;
3697
3698 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3699 // or union.
3700 MemberExpr *FieldME = ME;
3701
3702 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3703
3704 Expr *Base = ME;
3705 while (MemberExpr *SubME =
3706 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3707
3708 if (isa<VarDecl>(SubME->getMemberDecl()))
3709 return;
3710
3711 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3712 if (!FD->isAnonymousStructOrUnion())
3713 FieldME = SubME;
3714
3715 if (!FieldME->getType().isPODType(S.Context))
3716 AllPODFields = false;
3717
3718 Base = SubME->getBase();
3719 }
3720
3721 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3722 Visit(Base);
3723 return;
3724 }
3725
3726 if (AddressOf && AllPODFields)
3727 return;
3728
3729 ValueDecl* FoundVD = FieldME->getMemberDecl();
3730
3731 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3732 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3733 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3734 }
3735
3736 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3737 QualType T = BaseCast->getType();
3738 if (T->isPointerType() &&
3739 BaseClasses.count(T->getPointeeType())) {
3740 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3741 << T->getPointeeType() << FoundVD;
3742 }
3743 }
3744 }
3745
3746 if (!Decls.count(FoundVD))
3747 return;
3748
3749 const bool IsReference = FoundVD->getType()->isReferenceType();
3750
3751 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3752 // Special checking for initializer lists.
3753 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3754 return;
3755 }
3756 } else {
3757 // Prevent double warnings on use of unbounded references.
3758 if (CheckReferenceOnly && !IsReference)
3759 return;
3760 }
3761
3762 unsigned diag = IsReference
3763 ? diag::warn_reference_field_is_uninit
3764 : diag::warn_field_is_uninit;
3765 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3766 if (Constructor)
3767 S.Diag(Constructor->getLocation(),
3768 diag::note_uninit_in_this_constructor)
3769 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3770
3771 }
3772
3773 void HandleValue(Expr *E, bool AddressOf) {
3774 E = E->IgnoreParens();
3775
3776 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3777 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3778 AddressOf /*AddressOf*/);
3779 return;
3780 }
3781
3782 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3783 Visit(CO->getCond());
3784 HandleValue(CO->getTrueExpr(), AddressOf);
3785 HandleValue(CO->getFalseExpr(), AddressOf);
3786 return;
3787 }
3788
3789 if (BinaryConditionalOperator *BCO =
3790 dyn_cast<BinaryConditionalOperator>(E)) {
3791 Visit(BCO->getCond());
3792 HandleValue(BCO->getFalseExpr(), AddressOf);
3793 return;
3794 }
3795
3796 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3797 HandleValue(OVE->getSourceExpr(), AddressOf);
3798 return;
3799 }
3800
3801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3802 switch (BO->getOpcode()) {
3803 default:
3804 break;
3805 case(BO_PtrMemD):
3806 case(BO_PtrMemI):
3807 HandleValue(BO->getLHS(), AddressOf);
3808 Visit(BO->getRHS());
3809 return;
3810 case(BO_Comma):
3811 Visit(BO->getLHS());
3812 HandleValue(BO->getRHS(), AddressOf);
3813 return;
3814 }
3815 }
3816
3817 Visit(E);
3818 }
3819
3820 void CheckInitListExpr(InitListExpr *ILE) {
3821 InitFieldIndex.push_back(0);
3822 for (auto *Child : ILE->children()) {
3823 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3824 CheckInitListExpr(SubList);
3825 } else {
3826 Visit(Child);
3827 }
3828 ++InitFieldIndex.back();
3829 }
3830 InitFieldIndex.pop_back();
3831 }
3832
3833 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3834 FieldDecl *Field, const Type *BaseClass) {
3835 // Remove Decls that may have been initialized in the previous
3836 // initializer.
3837 for (ValueDecl* VD : DeclsToRemove)
3838 Decls.erase(VD);
3839 DeclsToRemove.clear();
3840
3841 Constructor = FieldConstructor;
3842 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3843
3844 if (ILE && Field) {
3845 InitList = true;
3846 InitListFieldDecl = Field;
3847 InitFieldIndex.clear();
3848 CheckInitListExpr(ILE);
3849 } else {
3850 InitList = false;
3851 Visit(E);
3852 }
3853
3854 if (Field)
3855 Decls.erase(Field);
3856 if (BaseClass)
3857 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3858 }
3859
3860 void VisitMemberExpr(MemberExpr *ME) {
3861 // All uses of unbounded reference fields will warn.
3862 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3863 }
3864
3865 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3866 if (E->getCastKind() == CK_LValueToRValue) {
3867 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3868 return;
3869 }
3870
3871 Inherited::VisitImplicitCastExpr(E);
3872 }
3873
3874 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3875 if (E->getConstructor()->isCopyConstructor()) {
3876 Expr *ArgExpr = E->getArg(0);
3877 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3878 if (ILE->getNumInits() == 1)
3879 ArgExpr = ILE->getInit(0);
3880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3881 if (ICE->getCastKind() == CK_NoOp)
3882 ArgExpr = ICE->getSubExpr();
3883 HandleValue(ArgExpr, false /*AddressOf*/);
3884 return;
3885 }
3886 Inherited::VisitCXXConstructExpr(E);
3887 }
3888
3889 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3890 Expr *Callee = E->getCallee();
3891 if (isa<MemberExpr>(Callee)) {
3892 HandleValue(Callee, false /*AddressOf*/);
3893 for (auto *Arg : E->arguments())
3894 Visit(Arg);
3895 return;
3896 }
3897
3898 Inherited::VisitCXXMemberCallExpr(E);
3899 }
3900
3901 void VisitCallExpr(CallExpr *E) {
3902 // Treat std::move as a use.
3903 if (E->isCallToStdMove()) {
3904 HandleValue(E->getArg(0), /*AddressOf=*/false);
3905 return;
3906 }
3907
3908 Inherited::VisitCallExpr(E);
3909 }
3910
3911 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3912 Expr *Callee = E->getCallee();
3913
3914 if (isa<UnresolvedLookupExpr>(Callee))
3915 return Inherited::VisitCXXOperatorCallExpr(E);
3916
3917 Visit(Callee);
3918 for (auto *Arg : E->arguments())
3919 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3920 }
3921
3922 void VisitBinaryOperator(BinaryOperator *E) {
3923 // If a field assignment is detected, remove the field from the
3924 // uninitiailized field set.
3925 if (E->getOpcode() == BO_Assign)
3926 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3927 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3928 if (!FD->getType()->isReferenceType())
3929 DeclsToRemove.push_back(FD);
3930
3931 if (E->isCompoundAssignmentOp()) {
3932 HandleValue(E->getLHS(), false /*AddressOf*/);
3933 Visit(E->getRHS());
3934 return;
3935 }
3936
3937 Inherited::VisitBinaryOperator(E);
3938 }
3939
3940 void VisitUnaryOperator(UnaryOperator *E) {
3941 if (E->isIncrementDecrementOp()) {
3942 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3943 return;
3944 }
3945 if (E->getOpcode() == UO_AddrOf) {
3946 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3947 HandleValue(ME->getBase(), true /*AddressOf*/);
3948 return;
3949 }
3950 }
3951
3952 Inherited::VisitUnaryOperator(E);
3953 }
3954 };
3955
3956 // Diagnose value-uses of fields to initialize themselves, e.g.
3957 // foo(foo)
3958 // where foo is not also a parameter to the constructor.
3959 // Also diagnose across field uninitialized use such as
3960 // x(y), y(x)
3961 // TODO: implement -Wuninitialized and fold this into that framework.
3962 static void DiagnoseUninitializedFields(
3963 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3964
3965 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3966 Constructor->getLocation())) {
3967 return;
3968 }
3969
3970 if (Constructor->isInvalidDecl())
3971 return;
3972
3973 const CXXRecordDecl *RD = Constructor->getParent();
3974
3975 if (RD->isDependentContext())
3976 return;
3977
3978 // Holds fields that are uninitialized.
3979 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3980
3981 // At the beginning, all fields are uninitialized.
3982 for (auto *I : RD->decls()) {
3983 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3984 UninitializedFields.insert(FD);
3985 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3986 UninitializedFields.insert(IFD->getAnonField());
3987 }
3988 }
3989
3990 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3991 for (const auto &I : RD->bases())
3992 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3993
3994 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3995 return;
3996
3997 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3998 UninitializedFields,
3999 UninitializedBaseClasses);
4000
4001 for (const auto *FieldInit : Constructor->inits()) {
4002 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4003 break;
4004
4005 Expr *InitExpr = FieldInit->getInit();
4006 if (!InitExpr)
4007 continue;
4008
4010 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4011 InitExpr = Default->getExpr();
4012 if (!InitExpr)
4013 continue;
4014 // In class initializers will point to the constructor.
4015 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4016 FieldInit->getAnyMember(),
4017 FieldInit->getBaseClass());
4018 } else {
4019 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4020 FieldInit->getAnyMember(),
4021 FieldInit->getBaseClass());
4022 }
4023 }
4024 }
4025} // namespace
4026
4028 // Create a synthetic function scope to represent the call to the constructor
4029 // that notionally surrounds a use of this initializer.
4031}
4032
4034 if (!D.isFunctionDeclarator())
4035 return;
4036 auto &FTI = D.getFunctionTypeInfo();
4037 if (!FTI.Params)
4038 return;
4039 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4040 FTI.NumParams)) {
4041 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4042 if (ParamDecl->getDeclName())
4043 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4044 }
4045}
4046
4048 return ActOnRequiresClause(ConstraintExpr);
4049}
4050
4052 if (ConstraintExpr.isInvalid())
4053 return ExprError();
4054
4055 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4056 if (ConstraintExpr.isInvalid())
4057 return ExprError();
4058
4059 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4061 return ExprError();
4062
4063 return ConstraintExpr;
4064}
4065
4067 Expr *InitExpr,
4068 SourceLocation InitLoc) {
4069 InitializedEntity Entity =
4071 InitializationKind Kind =
4074 InitExpr->getBeginLoc(),
4075 InitExpr->getEndLoc())
4076 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4077 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4078 return Seq.Perform(*this, Entity, Kind, InitExpr);
4079}
4080
4082 SourceLocation InitLoc,
4083 Expr *InitExpr) {
4084 // Pop the notional constructor scope we created earlier.
4085 PopFunctionScopeInfo(nullptr, D);
4086
4087 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4088 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4089 "must set init style when field is created");
4090
4091 if (!InitExpr) {
4092 D->setInvalidDecl();
4093 if (FD)
4095 return;
4096 }
4097
4099 FD->setInvalidDecl();
4101 return;
4102 }
4103
4104 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4105 /*RecoverUncorrectedTypos=*/true);
4106 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4107 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4108 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4109 // C++11 [class.base.init]p7:
4110 // The initialization of each base and member constitutes a
4111 // full-expression.
4112 if (!Init.isInvalid())
4113 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4114 if (Init.isInvalid()) {
4115 FD->setInvalidDecl();
4116 return;
4117 }
4118 }
4119
4120 FD->setInClassInitializer(Init.get());
4121}
4122
4123/// Find the direct and/or virtual base specifiers that
4124/// correspond to the given base type, for use in base initialization
4125/// within a constructor.
4127 CXXRecordDecl *ClassDecl,
4128 QualType BaseType,
4129 const CXXBaseSpecifier *&DirectBaseSpec,
4130 const CXXBaseSpecifier *&VirtualBaseSpec) {
4131 // First, check for a direct base class.
4132 DirectBaseSpec = nullptr;
4133 for (const auto &Base : ClassDecl->bases()) {
4134 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4135 // We found a direct base of this type. That's what we're
4136 // initializing.
4137 DirectBaseSpec = &Base;
4138 break;
4139 }
4140 }
4141
4142 // Check for a virtual base class.
4143 // FIXME: We might be able to short-circuit this if we know in advance that
4144 // there are no virtual bases.
4145 VirtualBaseSpec = nullptr;
4146 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4147 // We haven't found a base yet; search the class hierarchy for a
4148 // virtual base class.
4149 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4150 /*DetectVirtual=*/false);
4151 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4152 SemaRef.Context.getTypeDeclType(ClassDecl),
4153 BaseType, Paths)) {
4154 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4155 Path != Paths.end(); ++Path) {
4156 if (Path->back().Base->isVirtual()) {
4157 VirtualBaseSpec = Path->back().Base;
4158 break;
4159 }
4160 }
4161 }
4162 }
4163
4164 return DirectBaseSpec || VirtualBaseSpec;
4165}
4166
4169 Scope *S,
4170 CXXScopeSpec &SS,
4171 IdentifierInfo *MemberOrBase,
4172 ParsedType TemplateTypeTy,
4173 const DeclSpec &DS,
4174 SourceLocation IdLoc,
4175 Expr *InitList,
4176 SourceLocation EllipsisLoc) {
4177 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4178 DS, IdLoc, InitList,
4179 EllipsisLoc);
4180}
4181
4184 Scope *S,
4185 CXXScopeSpec &SS,
4186 IdentifierInfo *MemberOrBase,
4187 ParsedType TemplateTypeTy,
4188 const DeclSpec &DS,
4189 SourceLocation IdLoc,
4190 SourceLocation LParenLoc,
4191 ArrayRef<Expr *> Args,
4192 SourceLocation RParenLoc,
4193 SourceLocation EllipsisLoc) {
4194 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4195 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4196 DS, IdLoc, List, EllipsisLoc);
4197}
4198
4199namespace {
4200
4201// Callback to only accept typo corrections that can be a valid C++ member
4202// initializer: either a non-static field member or a base class.
4203class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4204public:
4205 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4206 : ClassDecl(ClassDecl) {}
4207
4208 bool ValidateCandidate(const TypoCorrection &candidate) override {
4209 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4210 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4211 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4212 return isa<TypeDecl>(ND);
4213 }
4214 return false;
4215 }
4216
4217 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4218 return std::make_unique<MemInitializerValidatorCCC>(*this);
4219 }
4220
4221private:
4222 CXXRecordDecl *ClassDecl;
4223};
4224
4225}
4226
4228 RecordDecl *ClassDecl,
4229 const IdentifierInfo *Name) {
4230 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4232 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4233 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4235 });
4236 // We did not find a placeholder variable
4237 if (Found == Result.end())
4238 return false;
4239 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4240 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4241 const NamedDecl *ND = *It;
4242 if (ND->getDeclContext() != ND->getDeclContext())
4243 break;
4244 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4246 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4247 }
4248 return true;
4249}
4250
4251ValueDecl *
4253 const IdentifierInfo *MemberOrBase) {
4254 ValueDecl *ND = nullptr;
4255 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4256 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4257 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4258 if (ND) {
4259 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4260 return nullptr;
4261 break;
4262 }
4263 if (!IsPlaceholder)
4264 return cast<ValueDecl>(D);
4265 ND = cast<ValueDecl>(D);
4266 }
4267 }
4268 return ND;
4269}
4270
4272 CXXScopeSpec &SS,
4273 ParsedType TemplateTypeTy,
4274 IdentifierInfo *MemberOrBase) {
4275 if (SS.getScopeRep() || TemplateTypeTy)
4276 return nullptr;
4277 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4278}
4279
4282 Scope *S,
4283 CXXScopeSpec &SS,
4284 IdentifierInfo *MemberOrBase,
4285 ParsedType TemplateTypeTy,
4286 const DeclSpec &DS,
4287 SourceLocation IdLoc,
4288 Expr *Init,
4289 SourceLocation EllipsisLoc) {
4290 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4291 /*RecoverUncorrectedTypos=*/true);
4292 if (!Res.isUsable())
4293 return true;
4294 Init = Res.get();
4295
4296 if (!ConstructorD)
4297 return true;
4298
4299 AdjustDeclIfTemplate(ConstructorD);
4300
4301 CXXConstructorDecl *Constructor
4302 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4303 if (!Constructor) {
4304 // The user wrote a constructor initializer on a function that is
4305 // not a C++ constructor. Ignore the error for now, because we may
4306 // have more member initializers coming; we'll diagnose it just
4307 // once in ActOnMemInitializers.
4308 return true;
4309 }
4310
4311 CXXRecordDecl *ClassDecl = Constructor->getParent();
4312
4313 // C++ [class.base.init]p2:
4314 // Names in a mem-initializer-id are looked up in the scope of the
4315 // constructor's class and, if not found in that scope, are looked
4316 // up in the scope containing the constructor's definition.
4317 // [Note: if the constructor's class contains a member with the
4318 // same name as a direct or virtual base class of the class, a
4319 // mem-initializer-id naming the member or base class and composed
4320 // of a single identifier refers to the class member. A
4321 // mem-initializer-id for the hidden base class may be specified
4322 // using a qualified name. ]
4323
4324 // Look for a member, first.
4326 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4327 if (EllipsisLoc.isValid())
4328 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4329 << MemberOrBase
4330 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4331
4332 return BuildMemberInitializer(Member, Init, IdLoc);
4333 }
4334 // It didn't name a member, so see if it names a class.
4335 QualType BaseType;
4336 TypeSourceInfo *TInfo = nullptr;
4337
4338 if (TemplateTypeTy) {
4339 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4340 if (BaseType.isNull())
4341 return true;
4342 } else if (DS.getTypeSpecType() == TST_decltype) {
4343 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4344 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4345 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4346 return true;
4347 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4348 BaseType =
4350 DS.getBeginLoc(), DS.getEllipsisLoc());
4351 } else {
4352 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4353 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4354
4355 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4356 if (!TyD) {
4357 if (R.isAmbiguous()) return true;
4358
4359 // We don't want access-control diagnostics here.
4361
4362 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4363 bool NotUnknownSpecialization = false;
4364 DeclContext *DC = computeDeclContext(SS, false);
4365 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4366 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4367
4368 if (!NotUnknownSpecialization) {
4369 // When the scope specifier can refer to a member of an unknown
4370 // specialization, we take it as a type name.
4371 BaseType = CheckTypenameType(
4373 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4374 if (BaseType.isNull())
4375 return true;
4376
4377 TInfo = Context.CreateTypeSourceInfo(BaseType);
4380 if (!TL.isNull()) {
4381 TL.setNameLoc(IdLoc);
4384 }
4385
4386 R.clear();
4387 R.setLookupName(MemberOrBase);
4388 }
4389 }
4390
4391 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4392 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4393 auto *TempSpec = cast<TemplateSpecializationType>(
4394 UnqualifiedBase->getInjectedClassNameSpecialization());
4395 TemplateName TN = TempSpec->getTemplateName();
4396 for (auto const &Base : ClassDecl->bases()) {
4397 auto BaseTemplate =
4398 Base.getType()->getAs<TemplateSpecializationType>();
4399 if (BaseTemplate && Context.hasSameTemplateName(
4400 BaseTemplate->getTemplateName(), TN)) {
4401 Diag(IdLoc, diag::ext_unqualified_base_class)
4402 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4403 BaseType = Base.getType();
4404 break;
4405 }
4406 }
4407 }
4408 }
4409
4410 // If no results were found, try to correct typos.
4411 TypoCorrection Corr;
4412 MemInitializerValidatorCCC CCC(ClassDecl);
4413 if (R.empty() && BaseType.isNull() &&
4414 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4415 CCC, CTK_ErrorRecovery, ClassDecl))) {
4417 // We have found a non-static data member with a similar
4418 // name to what was typed; complain and initialize that
4419 // member.
4420 diagnoseTypo(Corr,
4421 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4422 << MemberOrBase << true);
4423 return BuildMemberInitializer(Member, Init, IdLoc);
4424 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4425 const CXXBaseSpecifier *DirectBaseSpec;
4426 const CXXBaseSpecifier *VirtualBaseSpec;
4427 if (FindBaseInitializer(*this, ClassDecl,
4429 DirectBaseSpec, VirtualBaseSpec)) {
4430 // We have found a direct or virtual base class with a
4431 // similar name to what was typed; complain and initialize
4432 // that base class.
4433 diagnoseTypo(Corr,
4434 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4435 << MemberOrBase << false,
4436 PDiag() /*Suppress note, we provide our own.*/);
4437
4438 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4439 : VirtualBaseSpec;
4440 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4441 << BaseSpec->getType() << BaseSpec->getSourceRange();
4442
4443 TyD = Type;
4444 }
4445 }
4446 }
4447
4448 if (!TyD && BaseType.isNull()) {
4449 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4450 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4451 return true;
4452 }
4453 }
4454
4455 if (BaseType.isNull()) {
4458 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4459 TInfo = Context.CreateTypeSourceInfo(BaseType);
4461 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4464 }
4465 }
4466
4467 if (!TInfo)
4468 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4469
4470 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4471}
4472
4475 SourceLocation IdLoc) {
4476 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4477 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4478 assert((DirectMember || IndirectMember) &&
4479 "Member must be a FieldDecl or IndirectFieldDecl");
4480
4482 return true;
4483
4484 if (Member->isInvalidDecl())
4485 return true;
4486
4487 MultiExprArg Args;
4488 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4489 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4490 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4491 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4492 } else {
4493 // Template instantiation doesn't reconstruct ParenListExprs for us.
4494 Args = Init;
4495 }
4496
4497 SourceRange InitRange = Init->getSourceRange();
4498
4499 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4500 // Can't check initialization for a member of dependent type or when
4501 // any of the arguments are type-dependent expressions.
4503 } else {
4504 bool InitList = false;
4505 if (isa<InitListExpr>(Init)) {
4506 InitList = true;
4507 Args = Init;
4508 }
4509
4510 // Initialize the member.
4511 InitializedEntity MemberEntity =
4512 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4513 : InitializedEntity::InitializeMember(IndirectMember,
4514 nullptr);
4515 InitializationKind Kind =
4517 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4518 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4519 InitRange.getEnd());
4520
4521 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4522 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4523 nullptr);
4524 if (!MemberInit.isInvalid()) {
4525 // C++11 [class.base.init]p7:
4526 // The initialization of each base and member constitutes a
4527 // full-expression.
4528 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4529 /*DiscardedValue*/ false);
4530 }
4531
4532 if (MemberInit.isInvalid()) {
4533 // Args were sensible expressions but we couldn't initialize the member
4534 // from them. Preserve them in a RecoveryExpr instead.
4535 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4536 Member->getType())
4537 .get();
4538 if (!Init)
4539 return true;
4540 } else {
4541 Init = MemberInit.get();
4542 }
4543 }
4544
4545 if (DirectMember) {
4546 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4547 InitRange.getBegin(), Init,
4548 InitRange.getEnd());
4549 } else {
4550 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4551 InitRange.getBegin(), Init,
4552 InitRange.getEnd());
4553 }
4554}
4555
4558 CXXRecordDecl *ClassDecl) {
4559 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4560 if (!LangOpts.CPlusPlus11)
4561 return Diag(NameLoc, diag::err_delegating_ctor)
4562 << TInfo->getTypeLoc().getSourceRange();
4563 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4564
4565 bool InitList = true;
4566 MultiExprArg Args = Init;
4567 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4568 InitList = false;
4569 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4570 }
4571
4572 SourceRange InitRange = Init->getSourceRange();
4573 // Initialize the object.
4575 QualType(ClassDecl->getTypeForDecl(), 0));
4576 InitializationKind Kind =
4578 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4579 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4580 InitRange.getEnd());
4581 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4582 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4583 Args, nullptr);
4584 if (!DelegationInit.isInvalid()) {
4585 assert((DelegationInit.get()->containsErrors() ||
4586 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4587 "Delegating constructor with no target?");
4588
4589 // C++11 [class.base.init]p7:
4590 // The initialization of each base and member constitutes a
4591 // full-expression.
4592 DelegationInit = ActOnFinishFullExpr(
4593 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4594 }
4595
4596 if (DelegationInit.isInvalid()) {
4597 DelegationInit =
4598 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4599 QualType(ClassDecl->getTypeForDecl(), 0));
4600 if (DelegationInit.isInvalid())
4601 return true;
4602 } else {
4603 // If we are in a dependent context, template instantiation will
4604 // perform this type-checking again. Just save the arguments that we
4605 // received in a ParenListExpr.
4606 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4607 // of the information that we have about the base
4608 // initializer. However, deconstructing the ASTs is a dicey process,
4609 // and this approach is far more likely to get the corner cases right.
4611 DelegationInit = Init;
4612 }
4613
4614 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4615 DelegationInit.getAs<Expr>(),
4616 InitRange.getEnd());
4617}
4618
4621 Expr *Init, CXXRecordDecl *ClassDecl,
4622 SourceLocation EllipsisLoc) {
4623 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4624
4625 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4626 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4627 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4628
4629 // C++ [class.base.init]p2:
4630 // [...] Unless the mem-initializer-id names a nonstatic data
4631 // member of the constructor's class or a direct or virtual base
4632 // of that class, the mem-initializer is ill-formed. A
4633 // mem-initializer-list can initialize a base class using any
4634 // name that denotes that base class type.
4635
4636 // We can store the initializers in "as-written" form and delay analysis until
4637 // instantiation if the constructor is dependent. But not for dependent
4638 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4640 (BaseType->isDependentType() || Init->isTypeDependent());
4641
4642 SourceRange InitRange = Init->getSourceRange();
4643 if (EllipsisLoc.isValid()) {
4644 // This is a pack expansion.
4645 if (!BaseType->containsUnexpandedParameterPack()) {
4646 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4647 << SourceRange(BaseLoc, InitRange.getEnd());
4648
4649 EllipsisLoc = SourceLocation();
4650 }
4651 } else {
4652 // Check for any unexpanded parameter packs.
4653 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4654 return true;
4655
4657 return true;
4658 }
4659
4660 // Check for direct and virtual base classes.
4661 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4662 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4663 if (!Dependent) {
4665 BaseType))
4666 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4667
4668 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4669 VirtualBaseSpec);
4670
4671 // C++ [base.class.init]p2:
4672 // Unless the mem-initializer-id names a nonstatic data member of the
4673 // constructor's class or a direct or virtual base of that class, the
4674 // mem-initializer is ill-formed.
4675 if (!DirectBaseSpec && !VirtualBaseSpec) {
4676 // If the class has any dependent bases, then it's possible that
4677 // one of those types will resolve to the same type as
4678 // BaseType. Therefore, just treat this as a dependent base
4679 // class initialization. FIXME: Should we try to check the
4680 // initialization anyway? It seems odd.
4681 if (ClassDecl->hasAnyDependentBases())
4682 Dependent = true;
4683 else
4684 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4685 << BaseType << Context.getTypeDeclType(ClassDecl)
4686 << BaseTInfo->getTypeLoc().getSourceRange();
4687 }
4688 }
4689
4690 if (Dependent) {
4692
4693 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4694 /*IsVirtual=*/false,
4695 InitRange.getBegin(), Init,
4696 InitRange.getEnd(), EllipsisLoc);
4697 }
4698
4699 // C++ [base.class.init]p2:
4700 // If a mem-initializer-id is ambiguous because it designates both
4701 // a direct non-virtual base class and an inherited virtual base
4702 // class, the mem-initializer is ill-formed.
4703 if (DirectBaseSpec && VirtualBaseSpec)
4704 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4705 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4706
4707 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4708 if (!BaseSpec)
4709 BaseSpec = VirtualBaseSpec;
4710
4711 // Initialize the base.
4712 bool InitList = true;
4713 MultiExprArg Args = Init;
4714 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4715 InitList = false;
4716 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4717 }
4718
4719 InitializedEntity BaseEntity =
4720 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4721 InitializationKind Kind =
4722 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4723 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4724 InitRange.getEnd());
4725 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4726 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4727 if (!BaseInit.isInvalid()) {
4728 // C++11 [class.base.init]p7:
4729 // The initialization of each base and member constitutes a
4730 // full-expression.
4731 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4732 /*DiscardedValue*/ false);
4733 }
4734
4735 if (BaseInit.isInvalid()) {
4736 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4737 Args, BaseType);
4738 if (BaseInit.isInvalid())
4739 return true;
4740 } else {
4741 // If we are in a dependent context, template instantiation will
4742 // perform this type-checking again. Just save the arguments that we
4743 // received in a ParenListExpr.
4744 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4745 // of the information that we have about the base
4746 // initializer. However, deconstructing the ASTs is a dicey process,
4747 // and this approach is far more likely to get the corner cases right.
4749 BaseInit = Init;
4750 }
4751
4752 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4753 BaseSpec->isVirtual(),
4754 InitRange.getBegin(),
4755 BaseInit.getAs<Expr>(),
4756 InitRange.getEnd(), EllipsisLoc);
4757}
4758
4759// Create a static_cast<T&&>(expr).
4761 QualType TargetType =
4762 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4764 SourceLocation ExprLoc = E->getBeginLoc();
4766 TargetType, ExprLoc);
4767
4768 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4769 SourceRange(ExprLoc, ExprLoc),
4770 E->getSourceRange()).get();
4771}
4772
4773/// ImplicitInitializerKind - How an implicit base or member initializer should
4774/// initialize its base or member.
4781
4782static bool
4784 ImplicitInitializerKind ImplicitInitKind,
4785 CXXBaseSpecifier *BaseSpec,
4786 bool IsInheritedVirtualBase,
4787 CXXCtorInitializer *&CXXBaseInit) {
4788 InitializedEntity InitEntity
4790 IsInheritedVirtualBase);
4791
4792 ExprResult BaseInit;
4793
4794 switch (ImplicitInitKind) {
4795 case IIK_Inherit:
4796 case IIK_Default: {
4797 InitializationKind InitKind
4798 = InitializationKind::CreateDefault(Constructor->getLocation());
4799 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4800 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4801 break;
4802 }
4803
4804 case IIK_Move:
4805 case IIK_Copy: {
4806 bool Moving = ImplicitInitKind == IIK_Move;
4807 ParmVarDecl *Param = Constructor->getParamDecl(0);
4808 QualType ParamType = Param->getType().getNonReferenceType();
4809
4810 Expr *CopyCtorArg =
4812 SourceLocation(), Param, false,
4813 Constructor->getLocation(), ParamType,
4814 VK_LValue, nullptr);
4815
4816 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4817
4818 // Cast to the base class to avoid ambiguities.
4819 QualType ArgTy =
4821 ParamType.getQualifiers());
4822
4823 if (Moving) {
4824 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4825 }
4826
4827 CXXCastPath BasePath;
4828 BasePath.push_back(BaseSpec);
4829 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4830 CK_UncheckedDerivedToBase,
4831 Moving ? VK_XValue : VK_LValue,
4832 &BasePath).get();
4833
4834 InitializationKind InitKind
4835 = InitializationKind::CreateDirect(Constructor->getLocation(),
4837 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4838 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4839 break;
4840 }
4841 }
4842
4843 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4844 if (BaseInit.isInvalid())
4845 return true;
4846
4847 CXXBaseInit =
4850 SourceLocation()),
4851 BaseSpec->isVirtual(),
4853 BaseInit.getAs<Expr>(),
4855 SourceLocation());
4856
4857 return false;
4858}
4859
4860static bool RefersToRValueRef(Expr *MemRef) {
4861 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4862 return Referenced->getType()->isRValueReferenceType();
4863}
4864
4865static bool
4867 ImplicitInitializerKind ImplicitInitKind,
4869 CXXCtorInitializer *&CXXMemberInit) {
4870 if (Field->isInvalidDecl())
4871 return true;
4872
4873 SourceLocation Loc = Constructor->getLocation();
4874
4875 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4876 bool Moving = ImplicitInitKind == IIK_Move;
4877 ParmVarDecl *Param = Constructor->getParamDecl(0);
4878 QualType ParamType = Param->getType().getNonReferenceType();
4879
4880 // Suppress copying zero-width bitfields.
4881 if (Field->isZeroLengthBitField(SemaRef.Context))
4882 return false;
4883
4884 Expr *MemberExprBase =
4886 SourceLocation(), Param, false,
4887 Loc, ParamType, VK_LValue, nullptr);
4888
4889 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4890
4891 if (Moving) {
4892 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4893 }
4894
4895 // Build a reference to this field within the parameter.
4896 CXXScopeSpec SS;
4897 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4899 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4900 : cast<ValueDecl>(Field), AS_public);
4901 MemberLookup.resolveKind();
4902 ExprResult CtorArg
4903 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4904 ParamType, Loc,
4905 /*IsArrow=*/false,
4906 SS,
4907 /*TemplateKWLoc=*/SourceLocation(),
4908 /*FirstQualifierInScope=*/nullptr,
4909 MemberLookup,
4910 /*TemplateArgs=*/nullptr,
4911 /*S*/nullptr);
4912 if (CtorArg.isInvalid())
4913 return true;
4914
4915 // C++11 [class.copy]p15:
4916 // - if a member m has rvalue reference type T&&, it is direct-initialized
4917 // with static_cast<T&&>(x.m);
4918 if (RefersToRValueRef(CtorArg.get())) {
4919 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4920 }
4921
4922 InitializedEntity Entity =
4924 /*Implicit*/ true)
4925 : InitializedEntity::InitializeMember(Field, nullptr,
4926 /*Implicit*/ true);
4927
4928 // Direct-initialize to use the copy constructor.
4929 InitializationKind InitKind =
4931
4932 Expr *CtorArgE = CtorArg.getAs<Expr>();
4933 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4934 ExprResult MemberInit =
4935 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4936 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4937 if (MemberInit.isInvalid())
4938 return true;
4939
4940 if (Indirect)
4941 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4942 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4943 else
4944 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4945 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4946 return false;
4947 }
4948
4949 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4950 "Unhandled implicit init kind!");
4951
4952 QualType FieldBaseElementType =
4953 SemaRef.Context.getBaseElementType(Field->getType());
4954
4955 if (FieldBaseElementType->isRecordType()) {
4956 InitializedEntity InitEntity =
4958 /*Implicit*/ true)
4959 : InitializedEntity::InitializeMember(Field, nullptr,
4960 /*Implicit*/ true);
4961 InitializationKind InitKind =
4963
4964 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4965 ExprResult MemberInit =
4966 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4967
4968 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4969 if (MemberInit.isInvalid())
4970 return true;
4971
4972 if (Indirect)
4973 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4974 Indirect, Loc,
4975 Loc,
4976 MemberInit.get(),
4977 Loc);
4978 else
4979 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4980 Field, Loc, Loc,
4981 MemberInit.get(),
4982 Loc);
4983 return false;
4984 }
4985
4986 if (!Field->getParent()->isUnion()) {
4987 if (FieldBaseElementType->isReferenceType()) {
4988 SemaRef.Diag(Constructor->getLocation(),
4989 diag::err_uninitialized_member_in_ctor)
4990 << (int)Constructor->isImplicit()
4991 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4992 << 0 << Field->getDeclName();
4993 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4994 return true;
4995 }
4996
4997 if (FieldBaseElementType.isConstQualified()) {
4998 SemaRef.Diag(Constructor->getLocation(),
4999 diag::err_uninitialized_member_in_ctor)
5000 << (int)Constructor->isImplicit()
5001 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5002 << 1 << Field->getDeclName();
5003 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5004 return true;
5005 }
5006 }
5007
5008 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5009 // ARC and Weak:
5010 // Default-initialize Objective-C pointers to NULL.
5011 CXXMemberInit
5013 Loc, Loc,
5014 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5015 Loc);
5016 return false;
5017 }
5018
5019 // Nothing to initialize.
5020 CXXMemberInit = nullptr;
5021 return false;
5022}
5023
5024namespace {
5025struct BaseAndFieldInfo {
5026 Sema &S;
5027 CXXConstructorDecl *Ctor;
5028 bool AnyErrorsInInits;
5030 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5032 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5033
5034 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5035 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5036 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5037 if (Ctor->getInheritedConstructor())
5038 IIK = IIK_Inherit;
5039 else if (Generated && Ctor->isCopyConstructor())
5040 IIK = IIK_Copy;
5041 else if (Generated && Ctor->isMoveConstructor())
5042 IIK = IIK_Move;
5043 else
5044 IIK = IIK_Default;
5045 }
5046
5047 bool isImplicitCopyOrMove() const {
5048 switch (IIK) {
5049 case IIK_Copy:
5050 case IIK_Move:
5051 return true;
5052
5053 case IIK_Default:
5054 case IIK_Inherit:
5055 return false;
5056 }
5057
5058 llvm_unreachable("Invalid ImplicitInitializerKind!");
5059 }
5060
5061 bool addFieldInitializer(CXXCtorInitializer *Init) {
5062 AllToInit.push_back(Init);
5063
5064 // Check whether this initializer makes the field "used".
5065 if (Init->getInit()->HasSideEffects(S.Context))
5066 S.UnusedPrivateFields.remove(Init->getAnyMember());
5067
5068 return false;
5069 }
5070
5071 bool isInactiveUnionMember(FieldDecl *Field) {
5072 RecordDecl *Record = Field->getParent();
5073 if (!Record->isUnion())
5074 return false;
5075
5076 if (FieldDecl *Active =
5077 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5078 return Active != Field->getCanonicalDecl();
5079
5080 // In an implicit copy or move constructor, ignore any in-class initializer.
5081 if (isImplicitCopyOrMove())
5082 return true;
5083
5084 // If there's no explicit initialization, the field is active only if it
5085 // has an in-class initializer...
5086 if (Field->hasInClassInitializer())
5087 return false;
5088 // ... or it's an anonymous struct or union whose class has an in-class
5089 // initializer.
5090 if (!Field->isAnonymousStructOrUnion())
5091 return true;
5092 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5093 return !FieldRD->hasInClassInitializer();
5094 }
5095
5096 /// Determine whether the given field is, or is within, a union member
5097 /// that is inactive (because there was an initializer given for a different
5098 /// member of the union, or because the union was not initialized at all).
5099 bool isWithinInactiveUnionMember(FieldDecl *Field,
5101 if (!Indirect)
5102 return isInactiveUnionMember(Field);
5103
5104 for (auto *C : Indirect->chain()) {
5105 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5106 if (Field && isInactiveUnionMember(Field))
5107 return true;
5108 }
5109 return false;
5110 }
5111};
5112}
5113
5114/// Determine whether the given type is an incomplete or zero-lenfgth
5115/// array type.
5117 if (T->isIncompleteArrayType())
5118 return true;
5119
5120 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5121 if (ArrayT->isZeroSize())
5122 return true;
5123
5124 T = ArrayT->getElementType();
5125 }
5126
5127 return false;
5128}
5129
5130static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5131 FieldDecl *Field,
5132 IndirectFieldDecl *Indirect = nullptr) {
5133 if (Field->isInvalidDecl())
5134 return false;
5135
5136 // Overwhelmingly common case: we have a direct initializer for this field.
5138 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5139 return Info.addFieldInitializer(Init);
5140
5141 // C++11 [class.base.init]p8:
5142 // if the entity is a non-static data member that has a
5143 // brace-or-equal-initializer and either
5144 // -- the constructor's class is a union and no other variant member of that
5145 // union is designated by a mem-initializer-id or
5146 // -- the constructor's class is not a union, and, if the entity is a member
5147 // of an anonymous union, no other member of that union is designated by
5148 // a mem-initializer-id,
5149 // the entity is initialized as specified in [dcl.init].
5150 //
5151 // We also apply the same rules to handle anonymous structs within anonymous
5152 // unions.
5153 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5154 return false;
5155
5156 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5157 ExprResult DIE =
5158 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5159 if (DIE.isInvalid())
5160 return true;
5161
5162 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5163 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5164
5166 if (Indirect)
5167 Init = new (SemaRef.Context)
5169 SourceLocation(), DIE.get(), SourceLocation());
5170 else
5171 Init = new (SemaRef.Context)
5173 SourceLocation(), DIE.get(), SourceLocation());
5174 return Info.addFieldInitializer(Init);
5175 }
5176
5177 // Don't initialize incomplete or zero-length arrays.
5178 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5179 return false;
5180
5181 // Don't try to build an implicit initializer if there were semantic
5182 // errors in any of the initializers (and therefore we might be
5183 // missing some that the user actually wrote).
5184 if (Info.AnyErrorsInInits)
5185 return false;
5186
5187 CXXCtorInitializer *Init = nullptr;
5188 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5189 Indirect, Init))
5190 return true;
5191
5192 if (!Init)
5193 return false;
5194
5195 return Info.addFieldInitializer(Init);
5196}
5197
5198bool
5201 assert(Initializer->isDelegatingInitializer());
5202 Constructor->setNumCtorInitializers(1);
5203 CXXCtorInitializer **initializer =
5204 new (Context) CXXCtorInitializer*[1];
5205 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5206 Constructor->setCtorInitializers(initializer);
5207
5208 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5209 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5210 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5211 }
5212
5213 DelegatingCtorDecls.push_back(Constructor);
5214
5215 DiagnoseUninitializedFields(*this, Constructor);
5216
5217 return false;
5218}
5219
5220bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5221 ArrayRef<CXXCtorInitializer *> Initializers) {
5222 if (Constructor->isDependentContext()) {
5223 // Just store the initializers as written, they will be checked during
5224 // instantiation.
5225 if (!Initializers.empty()) {
5226 Constructor->setNumCtorInitializers(Initializers.size());
5227 CXXCtorInitializer **baseOrMemberInitializers =
5228 new (Context) CXXCtorInitializer*[Initializers.size()];
5229 memcpy(baseOrMemberInitializers, Initializers.data(),
5230 Initializers.size() * sizeof(CXXCtorInitializer*));
5231 Constructor->setCtorInitializers(baseOrMemberInitializers);
5232 }
5233
5234 // Let template instantiation know whether we had errors.
5235 if (AnyErrors)
5236 Constructor->setInvalidDecl();
5237
5238 return false;
5239 }
5240
5241 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5242
5243 // We need to build the initializer AST according to order of construction
5244 // and not what user specified in the Initializers list.
5245 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5246 if (!ClassDecl)
5247 return true;
5248
5249 bool HadError = false;
5250
5251 for (unsigned i = 0; i < Initializers.size(); i++) {
5252 CXXCtorInitializer *Member = Initializers[i];
5253
5254 if (Member->isBaseInitializer())
5255 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5256 else {
5257 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5258
5259 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5260 for (auto *C : F->chain()) {
5261 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5262 if (FD && FD->getParent()->isUnion())
5263 Info.ActiveUnionMember.insert(std::make_pair(
5265 }
5266 } else if (FieldDecl *FD = Member->getMember()) {
5267 if (FD->getParent()->isUnion())
5268 Info.ActiveUnionMember.insert(std::make_pair(
5270 }
5271 }
5272 }
5273
5274 // Keep track of the direct virtual bases.
5276 for (auto &I : ClassDecl->bases()) {
5277 if (I.isVirtual())
5278 DirectVBases.insert(&I);
5279 }
5280
5281 // Push virtual bases before others.
5282 for (auto &VBase : ClassDecl->vbases()) {
5284 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5285 // [class.base.init]p7, per DR257:
5286 // A mem-initializer where the mem-initializer-id names a virtual base
5287 // class is ignored during execution of a constructor of any class that
5288 // is not the most derived class.
5289 if (ClassDecl->isAbstract()) {
5290 // FIXME: Provide a fixit to remove the base specifier. This requires
5291 // tracking the location of the associated comma for a base specifier.
5292 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5293 << VBase.getType() << ClassDecl;
5294 DiagnoseAbstractType(ClassDecl);
5295 }
5296
5297 Info.AllToInit.push_back(Value);
5298 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5299 // [class.base.init]p8, per DR257:
5300 // If a given [...] base class is not named by a mem-initializer-id
5301 // [...] and the entity is not a virtual base class of an abstract
5302 // class, then [...] the entity is default-initialized.
5303 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5304 CXXCtorInitializer *CXXBaseInit;
5305 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5306 &VBase, IsInheritedVirtualBase,
5307 CXXBaseInit)) {
5308 HadError = true;
5309 continue;
5310 }
5311
5312 Info.AllToInit.push_back(CXXBaseInit);
5313 }
5314 }
5315
5316 // Non-virtual bases.
5317 for (auto &Base : ClassDecl->bases()) {
5318 // Virtuals are in the virtual base list and already constructed.
5319 if (Base.isVirtual())
5320 continue;
5321
5323 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5324 Info.AllToInit.push_back(Value);
5325 } else if (!AnyErrors) {
5326 CXXCtorInitializer *CXXBaseInit;
5327 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5328 &Base, /*IsInheritedVirtualBase=*/false,
5329 CXXBaseInit)) {
5330 HadError = true;
5331 continue;
5332 }
5333
5334 Info.AllToInit.push_back(CXXBaseInit);
5335 }
5336 }
5337
5338 // Fields.
5339 for (auto *Mem : ClassDecl->decls()) {
5340 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5341 // C++ [class.bit]p2:
5342 // A declaration for a bit-field that omits the identifier declares an
5343 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5344 // initialized.
5345 if (F->isUnnamedBitField())
5346 continue;
5347
5348 // If we're not generating the implicit copy/move constructor, then we'll
5349 // handle anonymous struct/union fields based on their individual
5350 // indirect fields.
5351 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5352 continue;
5353
5354 if (CollectFieldInitializer(*this, Info, F))
5355 HadError = true;
5356 continue;
5357 }
5358
5359 // Beyond this point, we only consider default initialization.
5360 if (Info.isImplicitCopyOrMove())
5361 continue;
5362
5363 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5364 if (F->getType()->isIncompleteArrayType()) {
5365 assert(ClassDecl->hasFlexibleArrayMember() &&
5366 "Incomplete array type is not valid");
5367 continue;
5368 }
5369
5370 // Initialize each field of an anonymous struct individually.
5371 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5372 HadError = true;
5373
5374 continue;
5375 }
5376 }
5377
5378 unsigned NumInitializers = Info.AllToInit.size();
5379 if (NumInitializers > 0) {
5380 Constructor->setNumCtorInitializers(NumInitializers);
5381 CXXCtorInitializer **baseOrMemberInitializers =
5382 new (Context) CXXCtorInitializer*[NumInitializers];
5383 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5384 NumInitializers * sizeof(CXXCtorInitializer*));
5385 Constructor->setCtorInitializers(baseOrMemberInitializers);
5386
5387 // Constructors implicitly reference the base and member
5388 // destructors.
5389 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5390 Constructor->getParent());
5391 }
5392
5393 return HadError;
5394}
5395
5397 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5398 const RecordDecl *RD = RT->getDecl();
5399 if (RD->isAnonymousStructOrUnion()) {
5400 for (auto *Field : RD->fields())
5401 PopulateKeysForFields(Field, IdealInits);
5402 return;
5403 }
5404 }
5405 IdealInits.push_back(Field->getCanonicalDecl());
5406}
5407
5408static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5409 return Context.getCanonicalType(BaseType).getTypePtr();
5410}
5411
5414 if (!Member->isAnyMemberInitializer())
5415 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5416
5417 return Member->getAnyMember()->getCanonicalDecl();
5418}
5419
5422 const CXXCtorInitializer *Current) {
5423 if (Previous->isAnyMemberInitializer())
5424 Diag << 0 << Previous->getAnyMember();
5425 else
5426 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5427
5428 if (Current->isAnyMemberInitializer())
5429 Diag << 0 << Current->getAnyMember();
5430 else
5431 Diag << 1 << Current->getTypeSourceInfo()->getType();
5432}
5433
5435 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5437 if (Constructor->getDeclContext()->isDependentContext())
5438 return;
5439
5440 // Don't check initializers order unless the warning is enabled at the
5441 // location of at least one initializer.
5442 bool ShouldCheckOrder = false;
5443 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5444 CXXCtorInitializer *Init = Inits[InitIndex];
5445 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5446 Init->getSourceLocation())) {
5447 ShouldCheckOrder = true;
5448 break;
5449 }
5450 }
5451 if (!ShouldCheckOrder)
5452 return;
5453
5454 // Build the list of bases and members in the order that they'll
5455 // actually be initialized. The explicit initializers should be in
5456 // this same order but may be missing things.
5457 SmallVector<const void*, 32> IdealInitKeys;
5458
5459 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5460
5461 // 1. Virtual bases.
5462 for (const auto &VBase : ClassDecl->vbases())
5463 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5464
5465 // 2. Non-virtual bases.
5466 for (const auto &Base : ClassDecl->bases()) {
5467 if (Base.isVirtual())
5468 continue;
5469 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5470 }
5471
5472 // 3. Direct fields.
5473 for (auto *Field : ClassDecl->fields()) {
5474 if (Field->isUnnamedBitField())
5475 continue;
5476
5477 PopulateKeysForFields(Field, IdealInitKeys);
5478 }
5479
5480 unsigned NumIdealInits = IdealInitKeys.size();
5481 unsigned IdealIndex = 0;
5482
5483 // Track initializers that are in an incorrect order for either a warning or
5484 // note if multiple ones occur.
5485 SmallVector<unsigned> WarnIndexes;
5486 // Correlates the index of an initializer in the init-list to the index of
5487 // the field/base in the class.
5488 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5489
5490 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5491 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5492
5493 // Scan forward to try to find this initializer in the idealized
5494 // initializers list.
5495 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5496 if (InitKey == IdealInitKeys[IdealIndex])
5497 break;
5498
5499 // If we didn't find this initializer, it must be because we
5500 // scanned past it on a previous iteration. That can only
5501 // happen if we're out of order; emit a warning.
5502 if (IdealIndex == NumIdealInits && InitIndex) {
5503 WarnIndexes.push_back(InitIndex);
5504
5505 // Move back to the initializer's location in the ideal list.
5506 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5507 if (InitKey == IdealInitKeys[IdealIndex])
5508 break;
5509
5510 assert(IdealIndex < NumIdealInits &&
5511 "initializer not found in initializer list");
5512 }
5513 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5514 }
5515
5516 if (WarnIndexes.empty())
5517 return;
5518
5519 // Sort based on the ideal order, first in the pair.
5520 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5521
5522 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5523 // emit the diagnostic before we can try adding notes.
5524 {
5526 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5527 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5528 : diag::warn_some_initializers_out_of_order);
5529
5530 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5531 if (CorrelatedInitOrder[I].second == I)
5532 continue;
5533 // Ideally we would be using InsertFromRange here, but clang doesn't
5534 // appear to handle InsertFromRange correctly when the source range is
5535 // modified by another fix-it.
5537 Inits[I]->getSourceRange(),
5540 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5542 }
5543
5544 // If there is only 1 item out of order, the warning expects the name and
5545 // type of each being added to it.
5546 if (WarnIndexes.size() == 1) {
5547 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5548 Inits[WarnIndexes.front()]);
5549 return;
5550 }
5551 }
5552 // More than 1 item to warn, create notes letting the user know which ones
5553 // are bad.
5554 for (unsigned WarnIndex : WarnIndexes) {
5555 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5556 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5557 diag::note_initializer_out_of_order);
5558 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5559 D << PrevInit->getSourceRange();
5560 }
5561}
5562
5563namespace {
5564bool CheckRedundantInit(Sema &S,
5566 CXXCtorInitializer *&PrevInit) {
5567 if (!PrevInit) {
5568 PrevInit = Init;
5569 return false;
5570 }
5571
5572 if (FieldDecl *Field = Init->getAnyMember())
5573 S.Diag(Init->getSourceLocation(),
5574 diag::err_multiple_mem_initialization)
5575 << Field->getDeclName()
5576 << Init->getSourceRange();
5577 else {
5578 const Type *BaseClass = Init->getBaseClass();
5579 assert(BaseClass && "neither field nor base");
5580 S.Diag(Init->getSourceLocation(),
5581 diag::err_multiple_base_initialization)
5582 << QualType(BaseClass, 0)
5583 << Init->getSourceRange();
5584 }
5585 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5586 << 0 << PrevInit->getSourceRange();
5587
5588 return true;
5589}
5590
5591typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5592typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5593
5594bool CheckRedundantUnionInit(Sema &S,
5596 RedundantUnionMap &Unions) {
5597 FieldDecl *Field = Init->getAnyMember();
5598 RecordDecl *Parent = Field->getParent();
5599 NamedDecl *Child = Field;
5600
5601 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5602 if (Parent->isUnion()) {
5603 UnionEntry &En = Unions[Parent];
5604 if (En.first && En.first != Child) {
5605 S.Diag(Init->getSourceLocation(),
5606 diag::err_multiple_mem_union_initialization)
5607 << Field->getDeclName()
5608 << Init->getSourceRange();
5609 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5610 << 0 << En.second->getSourceRange();
5611 return true;
5612 }
5613 if (!En.first) {
5614 En.first = Child;
5615 En.second = Init;
5616 }
5617 if (!Parent->isAnonymousStructOrUnion())
5618 return false;
5619 }
5620
5621 Child = Parent;
5622 Parent = cast<RecordDecl>(Parent->getDeclContext());
5623 }
5624
5625 return false;
5626}
5627} // namespace
5628
5629void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5630 SourceLocation ColonLoc,
5632 bool AnyErrors) {
5633 if (!ConstructorDecl)
5634 return;
5635
5636 AdjustDeclIfTemplate(ConstructorDecl);
5637
5638 CXXConstructorDecl *Constructor
5639 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5640
5641 if (!Constructor) {
5642 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5643 return;
5644 }
5645
5646 // Mapping for the duplicate initializers check.
5647 // For member initializers, this is keyed with a FieldDecl*.
5648 // For base initializers, this is keyed with a Type*.
5649 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5650
5651 // Mapping for the inconsistent anonymous-union initializers check.
5652 RedundantUnionMap MemberUnions;
5653
5654 bool HadError = false;
5655 for (unsigned i = 0; i < MemInits.size(); i++) {
5656 CXXCtorInitializer *Init = MemInits[i];
5657
5658 // Set the source order index.
5659 Init->setSourceOrder(i);
5660
5661 if (Init->isAnyMemberInitializer()) {
5662 const void *Key = GetKeyForMember(Context, Init);
5663 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5664 CheckRedundantUnionInit(*this, Init, MemberUnions))
5665 HadError = true;
5666 } else if (Init->isBaseInitializer()) {
5667 const void *Key = GetKeyForMember(Context, Init);
5668 if (CheckRedundantInit(*this, Init, Members[Key]))
5669 HadError = true;
5670 } else {
5671 assert(Init->isDelegatingInitializer());
5672 // This must be the only initializer
5673 if (MemInits.size() != 1) {
5674 Diag(Init->getSourceLocation(),
5675 diag::err_delegating_initializer_alone)
5676 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5677 // We will treat this as being the only initializer.
5678 }
5679 SetDelegatingInitializer(Constructor, MemInits[i]);
5680 // Return immediately as the initializer is set.
5681 return;
5682 }
5683 }
5684
5685 if (HadError)
5686 return;
5687
5688 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5689
5690 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5691
5692 DiagnoseUninitializedFields(*this, Constructor);
5693}
5694
5695void
5697 CXXRecordDecl *ClassDecl) {
5698 // Ignore dependent contexts. Also ignore unions, since their members never
5699 // have destructors implicitly called.
5700 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5701 return;
5702
5703 // FIXME: all the access-control diagnostics are positioned on the
5704 // field/base declaration. That's probably good; that said, the
5705 // user might reasonably want to know why the destructor is being
5706 // emitted, and we currently don't say.
5707
5708 // Non-static data members.
5709 for (auto *Field : ClassDecl->fields()) {
5710 if (Field->isInvalidDecl())
5711 continue;
5712
5713 // Don't destroy incomplete or zero-length arrays.
5714 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5715 continue;
5716
5717 QualType FieldType = Context.getBaseElementType(Field->getType());
5718
5719 const RecordType* RT = FieldType->getAs<RecordType>();
5720 if (!RT)
5721 continue;
5722
5723 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5724 if (FieldClassDecl->isInvalidDecl())
5725 continue;
5726 if (FieldClassDecl->hasIrrelevantDestructor())
5727 continue;
5728 // The destructor for an implicit anonymous union member is never invoked.
5729 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5730 continue;
5731
5732 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5733 // Dtor might still be missing, e.g because it's invalid.
5734 if (!Dtor)
5735 continue;
5736 CheckDestructorAccess(Field->getLocation(), Dtor,
5737 PDiag(diag::err_access_dtor_field)
5738 << Field->getDeclName()
5739 << FieldType);
5740
5741 MarkFunctionReferenced(Location, Dtor);
5742 DiagnoseUseOfDecl(Dtor, Location);
5743 }
5744
5745 // We only potentially invoke the destructors of potentially constructed
5746 // subobjects.
5747 bool VisitVirtualBases = !ClassDecl->isAbstract();
5748
5749 // If the destructor exists and has already been marked used in the MS ABI,
5750 // then virtual base destructors have already been checked and marked used.
5751 // Skip checking them again to avoid duplicate diagnostics.
5753 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5754 if (Dtor && Dtor->isUsed())
5755 VisitVirtualBases = false;
5756 }
5757
5759
5760 // Bases.
5761 for (const auto &Base : ClassDecl->bases()) {
5762 const RecordType *RT = Base.getType()->getAs<RecordType>();
5763 if (!RT)
5764 continue;
5765
5766 // Remember direct virtual bases.
5767 if (Base.isVirtual()) {
5768 if (!VisitVirtualBases)
5769 continue;
5770 DirectVirtualBases.insert(RT);
5771 }
5772
5773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5774 // If our base class is invalid, we probably can't get its dtor anyway.
5775 if (BaseClassDecl->isInvalidDecl())
5776 continue;
5777 if (BaseClassDecl->hasIrrelevantDestructor())
5778 continue;
5779
5780 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5781 // Dtor might still be missing, e.g because it's invalid.
5782 if (!Dtor)
5783 continue;
5784
5785 // FIXME: caret should be on the start of the class name
5786 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5787 PDiag(diag::err_access_dtor_base)
5788 << Base.getType() << Base.getSourceRange(),
5789 Context.getTypeDeclType(ClassDecl));
5790
5791 MarkFunctionReferenced(Location, Dtor);
5792 DiagnoseUseOfDecl(Dtor, Location);
5793 }
5794
5795 if (VisitVirtualBases)
5796 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5797 &DirectVirtualBases);
5798}
5799
5801 SourceLocation Location, CXXRecordDecl *ClassDecl,
5802 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5803 // Virtual bases.
5804 for (const auto &VBase : ClassDecl->vbases()) {
5805 // Bases are always records in a well-formed non-dependent class.
5806 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5807
5808 // Ignore already visited direct virtual bases.
5809 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5810 continue;
5811
5812 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5813 // If our base class is invalid, we probably can't get its dtor anyway.
5814 if (BaseClassDecl->isInvalidDecl())
5815 continue;
5816 if (BaseClassDecl->hasIrrelevantDestructor())
5817 continue;
5818
5819 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5820 // Dtor might still be missing, e.g because it's invalid.
5821 if (!Dtor)
5822 continue;
5824 ClassDecl->getLocation(), Dtor,
5825 PDiag(diag::err_access_dtor_vbase)
5826 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5827 Context.getTypeDeclType(ClassDecl)) ==
5828 AR_accessible) {
5830 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5831 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5832 SourceRange(), DeclarationName(), nullptr);
5833 }
5834
5835 MarkFunctionReferenced(Location, Dtor);
5836 DiagnoseUseOfDecl(Dtor, Location);
5837 }
5838}
5839
5841 if (!CDtorDecl)
5842 return;
5843
5844 if (CXXConstructorDecl *Constructor
5845 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5846 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5847 !ClassDecl || ClassDecl->isInvalidDecl()) {
5848 return;
5849 }
5850 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5851 DiagnoseUninitializedFields(*this, Constructor);
5852 }
5853}
5854
5856 if (!getLangOpts().CPlusPlus)
5857 return false;
5858
5859 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5860 if (!RD)
5861 return false;
5862
5863 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5864 // class template specialization here, but doing so breaks a lot of code.
5865
5866 // We can't answer whether something is abstract until it has a
5867 // definition. If it's currently being defined, we'll walk back
5868 // over all the declarations when we have a full definition.
5869 const CXXRecordDecl *Def = RD->getDefinition();
5870 if (!Def || Def->isBeingDefined())
5871 return false;
5872
5873 return RD->isAbstract();
5874}
5875
5877 TypeDiagnoser &Diagnoser) {
5878 if (!isAbstractType(Loc, T))
5879 return false;
5880
5882 Diagnoser.diagnose(*this, Loc, T);
5884 return true;
5885}
5886
5888 // Check if we've already emitted the list of pure virtual functions
5889 // for this class.
5891 return;
5892
5893 // If the diagnostic is suppressed, don't emit the notes. We're only
5894 // going to emit them once, so try to attach them to a diagnostic we're
5895 // actually going to show.
5897 return;
5898
5899 CXXFinalOverriderMap FinalOverriders;
5900 RD->getFinalOverriders(FinalOverriders);
5901
5902 // Keep a set of seen pure methods so we won't diagnose the same method
5903 // more than once.
5905
5906 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5907 MEnd = FinalOverriders.end();
5908 M != MEnd;
5909 ++M) {
5910 for (OverridingMethods::iterator SO = M->second.begin(),
5911 SOEnd = M->second.end();
5912 SO != SOEnd; ++SO) {
5913 // C++ [class.abstract]p4:
5914 // A class is abstract if it contains or inherits at least one
5915 // pure virtual function for which the final overrider is pure
5916 // virtual.
5917
5918 //
5919 if (SO->second.size() != 1)
5920 continue;
5921
5922 if (!SO->second.front().Method->isPureVirtual())
5923 continue;
5924
5925 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5926 continue;
5927
5928 Diag(SO->second.front().Method->getLocation(),
5929 diag::note_pure_virtual_function)
5930 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5931 }
5932 }
5933
5936 PureVirtualClassDiagSet->insert(RD);
5937}
5938
5939namespace {
5940struct AbstractUsageInfo {
5941 Sema &S;
5943 CanQualType AbstractType;
5944 bool Invalid;
5945
5946 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5947 : S(S), Record(Record),
5948 AbstractType(S.Context.getCanonicalType(
5949 S.Context.getTypeDeclType(Record))),
5950 Invalid(false) {}
5951
5952 void DiagnoseAbstractType() {
5953 if (Invalid) return;
5955 Invalid = true;
5956 }
5957
5958 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5959};
5960
5961struct CheckAbstractUsage {
5962 AbstractUsageInfo &Info;
5963 const NamedDecl *Ctx;
5964
5965 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5966 : Info(Info), Ctx(Ctx) {}
5967
5968 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5969 switch (TL.getTypeLocClass()) {
5970#define ABSTRACT_TYPELOC(CLASS, PARENT)
5971#define TYPELOC(CLASS, PARENT) \
5972 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5973#include "clang/AST/TypeLocNodes.def"
5974 }
5975 }
5976
5977 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5979 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5980 if (!TL.getParam(I))
5981 continue;
5982
5984 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5985 }
5986 }
5987
5988 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5990 }
5991
5993 // Visit the type parameters from a permissive context.
5994 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5995 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5997 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5998 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5999 // TODO: other template argument types?
6000 }
6001 }
6002
6003 // Visit pointee types from a permissive context.
6004#define CheckPolymorphic(Type) \
6005 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6006 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6007 }
6013
6014 /// Handle all the types we haven't given a more specific
6015 /// implementation for above.
6016 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6017 // Every other kind of type that we haven't called out already
6018 // that has an inner type is either (1) sugar or (2) contains that
6019 // inner type in some way as a subobject.
6020 if (TypeLoc Next = TL.getNextTypeLoc())
6021 return Visit(Next, Sel);
6022
6023 // If there's no inner type and we're in a permissive context,
6024 // don't diagnose.
6025 if (Sel == Sema::AbstractNone) return;
6026
6027 // Check whether the type matches the abstract type.
6028 QualType T = TL.getType();
6029 if (T->isArrayType()) {
6031 T = Info.S.Context.getBaseElementType(T);
6032 }
6034 if (CT != Info.AbstractType) return;
6035
6036 // It matched; do some magic.
6037 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6038 if (Sel == Sema::AbstractArrayType) {
6039 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6040 << T << TL.getSourceRange();
6041 } else {
6042 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6043 << Sel << T << TL.getSourceRange();
6044 }
6045 Info.DiagnoseAbstractType();
6046 }
6047};
6048
6049void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6051 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6052}
6053
6054}
6055
6056/// Check for invalid uses of an abstract type in a function declaration.
6057static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6058 FunctionDecl *FD) {
6059 // Only definitions are required to refer to complete and
6060 // non-abstract types.
6062 return;
6063
6064 // For safety's sake, just ignore it if we don't have type source
6065 // information. This should never happen for non-implicit methods,
6066 // but...
6067 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6068 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6069}
6070
6071/// Check for invalid uses of an abstract type in a variable0 declaration.
6072static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6073 VarDecl *VD) {
6074 // No need to do the check on definitions, which require that
6075 // the type is complete.
6077 return;
6078
6079 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6081}
6082
6083/// Check for invalid uses of an abstract type within a class definition.
6084static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6085 CXXRecordDecl *RD) {
6086 for (auto *D : RD->decls()) {
6087 if (D->isImplicit()) continue;
6088
6089 // Step through friends to the befriended declaration.
6090 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6091 D = FD->getFriendDecl();
6092 if (!D) continue;
6093 }
6094
6095 // Functions and function templates.
6096 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6097 CheckAbstractClassUsage(Info, FD);
6098 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6099 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6100
6101 // Fields and static variables.
6102 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6103 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6104 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6105 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6106 CheckAbstractClassUsage(Info, VD);
6107 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6108 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6109
6110 // Nested classes and class templates.
6111 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6112 CheckAbstractClassUsage(Info, RD);
6113 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6114 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6115 }
6116 }
6117}
6118
6120 Attr *ClassAttr = getDLLAttr(Class);
6121 if (!ClassAttr)
6122 return;
6123
6124 assert(ClassAttr->getKind() == attr::DLLExport);
6125
6126 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6127
6129 // Don't go any further if this is just an explicit instantiation
6130 // declaration.
6131 return;
6132
6133 // Add a context note to explain how we got to any diagnostics produced below.
6134 struct MarkingClassDllexported {
6135 Sema &S;
6136 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6137 SourceLocation AttrLoc)
6138 : S(S) {
6141 Ctx.PointOfInstantiation = AttrLoc;
6142 Ctx.Entity = Class;
6144 }
6145 ~MarkingClassDllexported() {
6147 }
6148 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6149
6150 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6151 S.MarkVTableUsed(Class->getLocation(), Class, true);
6152
6153 for (Decl *Member : Class->decls()) {
6154 // Skip members that were not marked exported.
6155 if (!Member->hasAttr<DLLExportAttr>())
6156 continue;
6157
6158 // Defined static variables that are members of an exported base
6159 // class must be marked export too.
6160 auto *VD = dyn_cast<VarDecl>(Member);
6161 if (VD && VD->getStorageClass() == SC_Static &&
6163 S.MarkVariableReferenced(VD->getLocation(), VD);
6164
6165 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6166 if (!MD)
6167 continue;
6168
6169 if (MD->isUserProvided()) {
6170 // Instantiate non-default class member functions ...
6171
6172 // .. except for certain kinds of template specializations.
6173 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6174 continue;
6175
6176 // If this is an MS ABI dllexport default constructor, instantiate any
6177 // default arguments.
6179 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6180 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6182 }
6183 }
6184
6185 S.MarkFunctionReferenced(Class->getLocation(), MD);
6186
6187 // The function will be passed to the consumer when its definition is
6188 // encountered.
6189 } else if (MD->isExplicitlyDefaulted()) {
6190 // Synthesize and instantiate explicitly defaulted methods.
6191 S.MarkFunctionReferenced(Class->getLocation(), MD);
6192
6194 // Except for explicit instantiation defs, we will not see the
6195 // definition again later, so pass it to the consumer now.
6197 }
6198 } else if (!MD->isTrivial() ||
6199 MD->isCopyAssignmentOperator() ||
6200 MD->isMoveAssignmentOperator()) {
6201 // Synthesize and instantiate non-trivial implicit methods, and the copy
6202 // and move assignment operators. The latter are exported even if they
6203 // are trivial, because the address of an operator can be taken and
6204 // should compare equal across libraries.
6205 S.MarkFunctionReferenced(Class->getLocation(), MD);
6206
6207 // There is no later point when we will see the definition of this
6208 // function, so pass it to the consumer now.
6210 }
6211 }
6212}
6213
6216 // Only the MS ABI has default constructor closures, so we don't need to do
6217 // this semantic checking anywhere else.
6219 return;
6220
6221 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6222 for (Decl *Member : Class->decls()) {
6223 // Look for exported default constructors.
6224 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6225 if (!CD || !CD->isDefaultConstructor())
6226 continue;
6227 auto *Attr = CD->getAttr<DLLExportAttr>();
6228 if (!Attr)
6229 continue;
6230
6231 // If the class is non-dependent, mark the default arguments as ODR-used so
6232 // that we can properly codegen the constructor closure.
6233 if (!Class->isDependentContext()) {
6234 for (ParmVarDecl *PD : CD->parameters()) {
6235 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6237 }
6238 }
6239
6240 if (LastExportedDefaultCtor) {
6241 S.Diag(LastExportedDefaultCtor->getLocation(),
6242 diag::err_attribute_dll_ambiguous_default_ctor)
6243 << Class;
6244 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6245 << CD->getDeclName();
6246 return;
6247 }
6248 LastExportedDefaultCtor = CD;
6249 }
6250}
6251
6254 bool ErrorReported = false;
6255 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6256 ClassTemplateDecl *TD) {
6257 if (ErrorReported)
6258 return;
6259 S.Diag(TD->getLocation(),
6260 diag::err_cuda_device_builtin_surftex_cls_template)
6261 << /*surface*/ 0 << TD;
6262 ErrorReported = true;
6263 };
6264
6265 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6266 if (!TD) {
6267 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6268 if (!SD) {
6269 S.Diag(Class->getLocation(),
6270 diag::err_cuda_device_builtin_surftex_ref_decl)
6271 << /*surface*/ 0 << Class;
6272 S.Diag(Class->getLocation(),
6273 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6274 << Class;
6275 return;
6276 }
6277 TD = SD->getSpecializedTemplate();
6278 }
6279
6281 unsigned N = Params->size();
6282
6283 if (N != 2) {
6284 reportIllegalClassTemplate(S, TD);
6285 S.Diag(TD->getLocation(),
6286 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6287 << TD << 2;
6288 }
6289 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6290 reportIllegalClassTemplate(S, TD);
6291 S.Diag(TD->getLocation(),
6292 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6293 << TD << /*1st*/ 0 << /*type*/ 0;
6294 }
6295 if (N > 1) {
6296 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6297 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6298 reportIllegalClassTemplate(S, TD);
6299 S.Diag(TD->getLocation(),
6300 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6301 << TD << /*2nd*/ 1 << /*integer*/ 1;
6302 }
6303 }
6304}
6305
6308 bool ErrorReported = false;
6309 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6310 ClassTemplateDecl *TD) {
6311 if (ErrorReported)
6312 return;
6313 S.Diag(TD->getLocation(),
6314 diag::err_cuda_device_builtin_surftex_cls_template)
6315 << /*texture*/ 1 << TD;
6316 ErrorReported = true;
6317 };
6318
6319 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6320 if (!TD) {
6321 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6322 if (!SD) {
6323 S.Diag(Class->getLocation(),
6324 diag::err_cuda_device_builtin_surftex_ref_decl)
6325 << /*texture*/ 1 << Class;
6326 S.Diag(Class->getLocation(),
6327 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6328 << Class;
6329 return;
6330 }
6331 TD = SD->getSpecializedTemplate();
6332 }
6333
6335 unsigned N = Params->size();
6336
6337 if (N != 3) {
6338 reportIllegalClassTemplate(S, TD);
6339 S.Diag(TD->getLocation(),
6340 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6341 << TD << 3;
6342 }
6343 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6344 reportIllegalClassTemplate(S, TD);
6345 S.Diag(TD->getLocation(),
6346 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6347 << TD << /*1st*/ 0 << /*type*/ 0;
6348 }
6349 if (N > 1) {
6350 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6351 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6352 reportIllegalClassTemplate(S, TD);
6353 S.Diag(TD->getLocation(),
6354 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6355 << TD << /*2nd*/ 1 << /*integer*/ 1;
6356 }
6357 }
6358 if (N > 2) {
6359 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6360 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6361 reportIllegalClassTemplate(S, TD);
6362 S.Diag(TD->getLocation(),
6363 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6364 << TD << /*3rd*/ 2 << /*integer*/ 1;
6365 }
6366 }
6367}
6368
6370 // Mark any compiler-generated routines with the implicit code_seg attribute.
6371 for (auto *Method : Class->methods()) {
6372 if (Method->isUserProvided())
6373 continue;
6374 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6375 Method->addAttr(A);
6376 }
6377}
6378
6380 Attr *ClassAttr = getDLLAttr(Class);
6381
6382 // MSVC inherits DLL attributes to partial class template specializations.
6383 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6384 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6385 if (Attr *TemplateAttr =
6386 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6387 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6388 A->setInherited(true);
6389 ClassAttr = A;
6390 }
6391 }
6392 }
6393
6394 if (!ClassAttr)
6395 return;
6396
6397 // MSVC allows imported or exported template classes that have UniqueExternal
6398 // linkage. This occurs when the template class has been instantiated with
6399 // a template parameter which itself has internal linkage.
6400 // We drop the attribute to avoid exporting or importing any members.
6402 Context.getTargetInfo().getTriple().isPS()) &&
6403 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6404 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6405 return;
6406 }
6407
6408 if (!Class->isExternallyVisible()) {
6409 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6410 << Class << ClassAttr;
6411 return;
6412 }
6413
6415 !ClassAttr->isInherited()) {
6416 // Diagnose dll attributes on members of class with dll attribute.
6417 for (Decl *Member : Class->decls()) {
6418 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6419 continue;
6420 InheritableAttr *MemberAttr = getDLLAttr(Member);
6421 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6422 continue;
6423
6424 Diag(MemberAttr->getLocation(),
6425 diag::err_attribute_dll_member_of_dll_class)
6426 << MemberAttr << ClassAttr;
6427 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6428 Member->setInvalidDecl();
6429 }
6430 }
6431
6432 if (Class->getDescribedClassTemplate())
6433 // Don't inherit dll attribute until the template is instantiated.
6434 return;
6435
6436 // The class is either imported or exported.
6437 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6438
6439 // Check if this was a dllimport attribute propagated from a derived class to
6440 // a base class template specialization. We don't apply these attributes to
6441 // static data members.
6442 const bool PropagatedImport =
6443 !ClassExported &&
6444 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6445
6446 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6447
6448 // Ignore explicit dllexport on explicit class template instantiation
6449 // declarations, except in MinGW mode.
6450 if (ClassExported && !ClassAttr->isInherited() &&
6452 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6453 Class->dropAttr<DLLExportAttr>();
6454 return;
6455 }
6456
6457 // Force declaration of implicit members so they can inherit the attribute.
6459
6460 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6461 // seem to be true in practice?
6462
6463 for (Decl *Member : Class->decls()) {
6464 VarDecl *VD = dyn_cast<VarDecl>(Member);
6465 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6466
6467 // Only methods and static fields inherit the attributes.
6468 if (!VD && !MD)
6469 continue;
6470
6471 if (MD) {
6472 // Don't process deleted methods.
6473 if (MD->isDeleted())
6474 continue;
6475
6476 if (MD->isInlined()) {
6477 // MinGW does not import or export inline methods. But do it for
6478 // template instantiations.
6482 continue;
6483
6484 // MSVC versions before 2015 don't export the move assignment operators
6485 // and move constructor, so don't attempt to import/export them if
6486 // we have a definition.
6487 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6488 if ((MD->isMoveAssignmentOperator() ||
6489 (Ctor && Ctor->isMoveConstructor())) &&
6490 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6491 continue;
6492
6493 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6494 // operator is exported anyway.
6495 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6496 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6497 continue;
6498 }
6499 }
6500
6501 // Don't apply dllimport attributes to static data members of class template
6502 // instantiations when the attribute is propagated from a derived class.
6503 if (VD && PropagatedImport)
6504 continue;
6505
6506 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6507 continue;
6508
6509 if (!getDLLAttr(Member)) {
6510 InheritableAttr *NewAttr = nullptr;
6511
6512 // Do not export/import inline function when -fno-dllexport-inlines is
6513 // passed. But add attribute for later local static var check.
6514 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6517 if (ClassExported) {
6518 NewAttr = ::new (getASTContext())
6519 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6520 } else {
6521 NewAttr = ::new (getASTContext())
6522 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6523 }
6524 } else {
6525 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6526 }
6527
6528 NewAttr->setInherited(true);
6529 Member->addAttr(NewAttr);
6530
6531 if (MD) {
6532 // Propagate DLLAttr to friend re-declarations of MD that have already
6533 // been constructed.
6534 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6535 FD = FD->getPreviousDecl()) {
6537 continue;
6538 assert(!getDLLAttr(FD) &&
6539 "friend re-decl should not already have a DLLAttr");
6540 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6541 NewAttr->setInherited(true);
6542 FD->addAttr(NewAttr);
6543 }
6544 }
6545 }
6546 }
6547
6548 if (ClassExported)
6549 DelayedDllExportClasses.push_back(Class);
6550}
6551
6553 CXXRecordDecl *Class, Attr *ClassAttr,
6554 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6555 if (getDLLAttr(
6556 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6557 // If the base class template has a DLL attribute, don't try to change it.
6558 return;
6559 }
6560
6561 auto TSK = BaseTemplateSpec->getSpecializationKind();
6562 if (!getDLLAttr(BaseTemplateSpec) &&
6564 TSK == TSK_ImplicitInstantiation)) {
6565 // The template hasn't been instantiated yet (or it has, but only as an
6566 // explicit instantiation declaration or implicit instantiation, which means
6567 // we haven't codegenned any members yet), so propagate the attribute.
6568 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6569 NewAttr->setInherited(true);
6570 BaseTemplateSpec->addAttr(NewAttr);
6571
6572 // If this was an import, mark that we propagated it from a derived class to
6573 // a base class template specialization.
6574 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6575 ImportAttr->setPropagatedToBaseTemplate();
6576
6577 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6578 // needs to be run again to work see the new attribute. Otherwise this will
6579 // get run whenever the template is instantiated.
6580 if (TSK != TSK_Undeclared)
6581 checkClassLevelDLLAttribute(BaseTemplateSpec);
6582
6583 return;
6584 }
6585
6586 if (getDLLAttr(BaseTemplateSpec)) {
6587 // The template has already been specialized or instantiated with an
6588 // attribute, explicitly or through propagation. We should not try to change
6589 // it.
6590 return;
6591 }
6592
6593 // The template was previously instantiated or explicitly specialized without
6594 // a dll attribute, It's too late for us to add an attribute, so warn that
6595 // this is unsupported.
6596 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6597 << BaseTemplateSpec->isExplicitSpecialization();
6598 Diag(ClassAttr->getLocation(), diag::note_attribute);
6599 if (BaseTemplateSpec->isExplicitSpecialization()) {
6600 Diag(BaseTemplateSpec->getLocation(),
6601 diag::note_template_class_explicit_specialization_was_here)
6602 << BaseTemplateSpec;
6603 } else {
6604 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6605 diag::note_template_class_instantiation_was_here)
6606 << BaseTemplateSpec;
6607 }
6608}
6609
6612 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6613 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6614 if (Ctor->isDefaultConstructor())
6616
6617 if (Ctor->isCopyConstructor())
6619
6620 if (Ctor->isMoveConstructor())
6622 }
6623
6624 if (MD->isCopyAssignmentOperator())
6626
6627 if (MD->isMoveAssignmentOperator())
6629
6630 if (isa<CXXDestructorDecl>(FD))
6632 }
6633
6634 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6635 case OO_EqualEqual:
6637
6638 case OO_ExclaimEqual:
6640
6641 case OO_Spaceship:
6642 // No point allowing this if <=> doesn't exist in the current language mode.
6643 if (!getLangOpts().CPlusPlus20)
6644 break;
6646
6647 case OO_Less:
6648 case OO_LessEqual:
6649 case OO_Greater:
6650 case OO_GreaterEqual:
6651 // No point allowing this if <=> doesn't exist in the current language mode.
6652 if (!getLangOpts().CPlusPlus20)
6653 break;
6655
6656 default:
6657 break;
6658 }
6659
6660 // Not defaultable.
6661 return DefaultedFunctionKind();
6662}
6663
6665 SourceLocation DefaultLoc) {
6667 if (DFK.isComparison())
6668 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6669
6670 switch (DFK.asSpecialMember()) {
6673 cast<CXXConstructorDecl>(FD));
6674 break;
6676 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6677 break;
6679 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6680 break;
6682 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6683 break;
6685 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6686 break;
6688 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6689 break;
6691 llvm_unreachable("Invalid special member.");
6692 }
6693}
6694
6695/// Determine whether a type is permitted to be passed or returned in
6696/// registers, per C++ [class.temporary]p3.
6699 if (D->isDependentType() || D->isInvalidDecl())
6700 return false;
6701
6702 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6703 // The PS4 platform ABI follows the behavior of Clang 3.2.
6705 return !D->hasNonTrivialDestructorForCall() &&
6706 !D->hasNonTrivialCopyConstructorForCall();
6707
6708 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6709 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6710 bool DtorIsTrivialForCall = false;
6711
6712 // If a class has at least one eligible, trivial copy constructor, it
6713 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6714 //
6715 // Note: This permits classes with non-trivial copy or move ctors to be
6716 // passed in registers, so long as they *also* have a trivial copy ctor,
6717 // which is non-conforming.
6718 if (D->needsImplicitCopyConstructor()) {
6719 if (!D->defaultedCopyConstructorIsDeleted()) {
6720 if (D->hasTrivialCopyConstructor())
6721 CopyCtorIsTrivial = true;
6722 if (D->hasTrivialCopyConstructorForCall())
6723 CopyCtorIsTrivialForCall = true;
6724 }
6725 } else {
6726 for (const CXXConstructorDecl *CD : D->ctors()) {
6727 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6728 !CD->isIneligibleOrNotSelected()) {
6729 if (CD->isTrivial())
6730 CopyCtorIsTrivial = true;
6731 if (CD->isTrivialForCall())
6732 CopyCtorIsTrivialForCall = true;
6733 }
6734 }
6735 }
6736
6737 if (D->needsImplicitDestructor()) {
6738 if (!D->defaultedDestructorIsDeleted() &&
6739 D->hasTrivialDestructorForCall())
6740 DtorIsTrivialForCall = true;
6741 } else if (const auto *DD = D->getDestructor()) {
6742 if (!DD->isDeleted() && DD->isTrivialForCall())
6743 DtorIsTrivialForCall = true;
6744 }
6745
6746 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6747 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6748 return true;
6749
6750 // If a class has a destructor, we'd really like to pass it indirectly
6751 // because it allows us to elide copies. Unfortunately, MSVC makes that
6752 // impossible for small types, which it will pass in a single register or
6753 // stack slot. Most objects with dtors are large-ish, so handle that early.
6754 // We can't call out all large objects as being indirect because there are
6755 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6756 // how we pass large POD types.
6757
6758 // Note: This permits small classes with nontrivial destructors to be
6759 // passed in registers, which is non-conforming.
6760 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6761 uint64_t TypeSize = isAArch64 ? 128 : 64;
6762
6763 if (CopyCtorIsTrivial &&
6764 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6765 return true;
6766 return false;
6767 }
6768
6769 // Per C++ [class.temporary]p3, the relevant condition is:
6770 // each copy constructor, move constructor, and destructor of X is
6771 // either trivial or deleted, and X has at least one non-deleted copy
6772 // or move constructor
6773 bool HasNonDeletedCopyOrMove = false;
6774
6775 if (D->needsImplicitCopyConstructor() &&
6776 !D->defaultedCopyConstructorIsDeleted()) {
6777 if (!D->hasTrivialCopyConstructorForCall())
6778 return false;
6779 HasNonDeletedCopyOrMove = true;
6780 }
6781
6782 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6783 !D->defaultedMoveConstructorIsDeleted()) {
6784 if (!D->hasTrivialMoveConstructorForCall())
6785 return false;
6786 HasNonDeletedCopyOrMove = true;
6787 }
6788
6789 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6790 !D->hasTrivialDestructorForCall())
6791 return false;
6792
6793 for (const CXXMethodDecl *MD : D->methods()) {
6794 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6795 continue;
6796
6797 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6798 if (CD && CD->isCopyOrMoveConstructor())
6799 HasNonDeletedCopyOrMove = true;
6800 else if (!isa<CXXDestructorDecl>(MD))
6801 continue;
6802
6803 if (!MD->isTrivialForCall())
6804 return false;
6805 }
6806
6807 return HasNonDeletedCopyOrMove;
6808}
6809
6810/// Report an error regarding overriding, along with any relevant
6811/// overridden methods.
6812///
6813/// \param DiagID the primary error to report.
6814/// \param MD the overriding method.
6815static bool
6816ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6817 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6818 bool IssuedDiagnostic = false;
6819 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6820 if (Report(O)) {
6821 if (!IssuedDiagnostic) {
6822 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6823 IssuedDiagnostic = true;
6824 }
6825 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6826 }
6827 }
6828 return IssuedDiagnostic;
6829}
6830
6832 if (!Record)
6833 return;
6834
6835 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6836 AbstractUsageInfo Info(*this, Record);
6838 }
6839
6840 // If this is not an aggregate type and has no user-declared constructor,
6841 // complain about any non-static data members of reference or const scalar
6842 // type, since they will never get initializers.
6843 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6844 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6845 !Record->isLambda()) {
6846 bool Complained = false;
6847 for (const auto *F : Record->fields()) {
6848 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6849 continue;
6850
6851 if (F->getType()->isReferenceType() ||
6852 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6853 if (!Complained) {
6854 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6855 << llvm::to_underlying(Record->getTagKind()) << Record;
6856 Complained = true;
6857 }
6858
6859 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6860 << F->getType()->isReferenceType()
6861 << F->getDeclName();
6862 }
6863 }
6864 }
6865
6866 if (Record->getIdentifier()) {
6867 // C++ [class.mem]p13:
6868 // If T is the name of a class, then each of the following shall have a
6869 // name different from T:
6870 // - every member of every anonymous union that is a member of class T.
6871 //
6872 // C++ [class.mem]p14:
6873 // In addition, if class T has a user-declared constructor (12.1), every
6874 // non-static data member of class T shall have a name different from T.
6875 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6876 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6877 ++I) {
6878 NamedDecl *D = (*I)->getUnderlyingDecl();
6879 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6880 Record->hasUserDeclaredConstructor()) ||
6881 isa<IndirectFieldDecl>(D)) {
6882 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6883 << D->getDeclName();
6884 break;
6885 }
6886 }
6887 }
6888
6889 // Warn if the class has virtual methods but non-virtual public destructor.
6890 if (Record->isPolymorphic() && !Record->isDependentType()) {
6891 CXXDestructorDecl *dtor = Record->getDestructor();
6892 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6893 !Record->hasAttr<FinalAttr>())
6894 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6895 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6896 }
6897
6898 if (Record->isAbstract()) {
6899 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6900 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6901 << FA->isSpelledAsSealed();
6903 }
6904 }
6905
6906 // Warn if the class has a final destructor but is not itself marked final.
6907 if (!Record->hasAttr<FinalAttr>()) {
6908 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6909 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6910 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6911 << FA->isSpelledAsSealed()
6913 getLocForEndOfToken(Record->getLocation()),
6914 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6915 Diag(Record->getLocation(),
6916 diag::note_final_dtor_non_final_class_silence)
6917 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6918 }
6919 }
6920 }
6921
6922 // See if trivial_abi has to be dropped.
6923 if (Record->hasAttr<TrivialABIAttr>())
6925
6926 // Set HasTrivialSpecialMemberForCall if the record has attribute
6927 // "trivial_abi".
6928 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6929
6930 if (HasTrivialABI)
6931 Record->setHasTrivialSpecialMemberForCall();
6932
6933 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6934 // We check these last because they can depend on the properties of the
6935 // primary comparison functions (==, <=>).
6936 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6937
6938 // Perform checks that can't be done until we know all the properties of a
6939 // member function (whether it's defaulted, deleted, virtual, overriding,
6940 // ...).
6941 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6942 // A static function cannot override anything.
6943 if (MD->getStorageClass() == SC_Static) {
6944 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6945 [](const CXXMethodDecl *) { return true; }))
6946 return;
6947 }
6948
6949 // A deleted function cannot override a non-deleted function and vice
6950 // versa.
6951 if (ReportOverrides(*this,
6952 MD->isDeleted() ? diag::err_deleted_override
6953 : diag::err_non_deleted_override,
6954 MD, [&](const CXXMethodDecl *V) {
6955 return MD->isDeleted() != V->isDeleted();
6956 })) {
6957 if (MD->isDefaulted() && MD->isDeleted())
6958 // Explain why this defaulted function was deleted.
6960 return;
6961 }
6962
6963 // A consteval function cannot override a non-consteval function and vice
6964 // versa.
6965 if (ReportOverrides(*this,
6966 MD->isConsteval() ? diag::err_consteval_override
6967 : diag::err_non_consteval_override,
6968 MD, [&](const CXXMethodDecl *V) {
6969 return MD->isConsteval() != V->isConsteval();
6970 })) {
6971 if (MD->isDefaulted() && MD->isDeleted())
6972 // Explain why this defaulted function was deleted.
6974 return;
6975 }
6976 };
6977
6978 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6979 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6980 return false;
6981
6985 DefaultedSecondaryComparisons.push_back(FD);
6986 return true;
6987 }
6988
6990 return false;
6991 };
6992
6993 if (!Record->isInvalidDecl() &&
6994 Record->hasAttr<VTablePointerAuthenticationAttr>())
6996
6997 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6998 // Check whether the explicitly-defaulted members are valid.
6999 bool Incomplete = CheckForDefaultedFunction(M);
7000
7001 // Skip the rest of the checks for a member of a dependent class.
7002 if (Record->isDependentType())
7003 return;
7004
7005 // For an explicitly defaulted or deleted special member, we defer
7006 // determining triviality until the class is complete. That time is now!
7008 if (!M->isImplicit() && !M->isUserProvided()) {
7009 if (CSM != CXXSpecialMemberKind::Invalid) {
7010 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7011 // Inform the class that we've finished declaring this member.
7012 Record->finishedDefaultedOrDeletedMember(M);
7013 M->setTrivialForCall(
7014 HasTrivialABI ||
7016 Record->setTrivialForCallFlags(M);
7017 }
7018 }
7019
7020 // Set triviality for the purpose of calls if this is a user-provided
7021 // copy/move constructor or destructor.
7025 M->isUserProvided()) {
7026 M->setTrivialForCall(HasTrivialABI);
7027 Record->setTrivialForCallFlags(M);
7028 }
7029
7030 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7031 M->hasAttr<DLLExportAttr>()) {
7032 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7033 M->isTrivial() &&
7037 M->dropAttr<DLLExportAttr>();
7038
7039 if (M->hasAttr<DLLExportAttr>()) {
7040 // Define after any fields with in-class initializers have been parsed.
7042 }
7043 }
7044
7045 bool EffectivelyConstexprDestructor = true;
7046 // Avoid triggering vtable instantiation due to a dtor that is not
7047 // "effectively constexpr" for better compatibility.
7048 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7049 if (isa<CXXDestructorDecl>(M)) {
7050 auto Check = [](QualType T, auto &&Check) -> bool {
7051 const CXXRecordDecl *RD =
7053 if (!RD || !RD->isCompleteDefinition())
7054 return true;
7055
7056 if (!RD->hasConstexprDestructor())
7057 return false;
7058
7059 for (const CXXBaseSpecifier &B : RD->bases())
7060 if (!Check(B.getType(), Check))
7061 return false;
7062 for (const FieldDecl *FD : RD->fields())
7063 if (!Check(FD->getType(), Check))
7064 return false;
7065 return true;
7066 };
7067 EffectivelyConstexprDestructor =
7068 Check(QualType(Record->getTypeForDecl(), 0), Check);
7069 }
7070
7071 // Define defaulted constexpr virtual functions that override a base class
7072 // function right away.
7073 // FIXME: We can defer doing this until the vtable is marked as used.
7074 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7075 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7076 EffectivelyConstexprDestructor)
7077 DefineDefaultedFunction(*this, M, M->getLocation());
7078
7079 if (!Incomplete)
7080 CheckCompletedMemberFunction(M);
7081 };
7082
7083 // Check the destructor before any other member function. We need to
7084 // determine whether it's trivial in order to determine whether the claas
7085 // type is a literal type, which is a prerequisite for determining whether
7086 // other special member functions are valid and whether they're implicitly
7087 // 'constexpr'.
7088 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7089 CompleteMemberFunction(Dtor);
7090
7091 bool HasMethodWithOverrideControl = false,
7092 HasOverridingMethodWithoutOverrideControl = false;
7093 for (auto *D : Record->decls()) {
7094 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7095 // FIXME: We could do this check for dependent types with non-dependent
7096 // bases.
7097 if (!Record->isDependentType()) {
7098 // See if a method overloads virtual methods in a base
7099 // class without overriding any.
7100 if (!M->isStatic())
7102 if (M->hasAttr<OverrideAttr>())
7103 HasMethodWithOverrideControl = true;
7104 else if (M->size_overridden_methods() > 0)
7105 HasOverridingMethodWithoutOverrideControl = true;
7106 }
7107
7108 if (!isa<CXXDestructorDecl>(M))
7109 CompleteMemberFunction(M);
7110 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7111 CheckForDefaultedFunction(
7112 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7113 }
7114 }
7115
7116 if (HasOverridingMethodWithoutOverrideControl) {
7117 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7118 for (auto *M : Record->methods())
7119 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7120 }
7121
7122 // Check the defaulted secondary comparisons after any other member functions.
7123 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7125
7126 // If this is a member function, we deferred checking it until now.
7127 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7128 CheckCompletedMemberFunction(MD);
7129 }
7130
7131 // ms_struct is a request to use the same ABI rules as MSVC. Check
7132 // whether this class uses any C++ features that are implemented
7133 // completely differently in MSVC, and if so, emit a diagnostic.
7134 // That diagnostic defaults to an error, but we allow projects to
7135 // map it down to a warning (or ignore it). It's a fairly common
7136 // practice among users of the ms_struct pragma to mass-annotate
7137 // headers, sweeping up a bunch of types that the project doesn't
7138 // really rely on MSVC-compatible layout for. We must therefore
7139 // support "ms_struct except for C++ stuff" as a secondary ABI.
7140 // Don't emit this diagnostic if the feature was enabled as a
7141 // language option (as opposed to via a pragma or attribute), as
7142 // the option -mms-bitfields otherwise essentially makes it impossible
7143 // to build C++ code, unless this diagnostic is turned off.
7144 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7145 (Record->isPolymorphic() || Record->getNumBases())) {
7146 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7147 }
7148
7151
7152 bool ClangABICompat4 =
7153 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7155 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7156 bool CanPass = canPassInRegisters(*this, Record, CCK);
7157
7158 // Do not change ArgPassingRestrictions if it has already been set to
7159 // RecordArgPassingKind::CanNeverPassInRegs.
7160 if (Record->getArgPassingRestrictions() !=
7162 Record->setArgPassingRestrictions(
7165
7166 // If canPassInRegisters returns true despite the record having a non-trivial
7167 // destructor, the record is destructed in the callee. This happens only when
7168 // the record or one of its subobjects has a field annotated with trivial_abi
7169 // or a field qualified with ObjC __strong/__weak.
7171 Record->setParamDestroyedInCallee(true);
7172 else if (Record->hasNonTrivialDestructor())
7173 Record->setParamDestroyedInCallee(CanPass);
7174
7175 if (getLangOpts().ForceEmitVTables) {
7176 // If we want to emit all the vtables, we need to mark it as used. This
7177 // is especially required for cases like vtable assumption loads.
7178 MarkVTableUsed(Record->getInnerLocStart(), Record);
7179 }
7180
7181 if (getLangOpts().CUDA) {
7182 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7184 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7186 }
7187}
7188
7189/// Look up the special member function that would be called by a special
7190/// member function for a subobject of class type.
7191///
7192/// \param Class The class type of the subobject.
7193/// \param CSM The kind of special member function.
7194/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7195/// \param ConstRHS True if this is a copy operation with a const object
7196/// on its RHS, that is, if the argument to the outer special member
7197/// function is 'const' and this is not a field marked 'mutable'.
7200 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7201 bool ConstRHS) {
7202 unsigned LHSQuals = 0;
7205 LHSQuals = FieldQuals;
7206
7207 unsigned RHSQuals = FieldQuals;
7210 RHSQuals = 0;
7211 else if (ConstRHS)
7212 RHSQuals |= Qualifiers::Const;
7213
7214 return S.LookupSpecialMember(Class, CSM,
7215 RHSQuals & Qualifiers::Const,
7216 RHSQuals & Qualifiers::Volatile,
7217 false,
7218 LHSQuals & Qualifiers::Const,
7219 LHSQuals & Qualifiers::Volatile);
7220}
7221
7223 Sema &S;
7224 SourceLocation UseLoc;
7225
7226 /// A mapping from the base classes through which the constructor was
7227 /// inherited to the using shadow declaration in that base class (or a null
7228 /// pointer if the constructor was declared in that base class).
7229 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7230 InheritedFromBases;
7231
7232public:
7235 : S(S), UseLoc(UseLoc) {
7236 bool DiagnosedMultipleConstructedBases = false;
7237 CXXRecordDecl *ConstructedBase = nullptr;
7238 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7239
7240 // Find the set of such base class subobjects and check that there's a
7241 // unique constructed subobject.
7242 for (auto *D : Shadow->redecls()) {
7243 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7244 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7245 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7246
7247 InheritedFromBases.insert(
7248 std::make_pair(DNominatedBase->getCanonicalDecl(),
7249 DShadow->getNominatedBaseClassShadowDecl()));
7250 if (DShadow->constructsVirtualBase())
7251 InheritedFromBases.insert(
7252 std::make_pair(DConstructedBase->getCanonicalDecl(),
7253 DShadow->getConstructedBaseClassShadowDecl()));
7254 else
7255 assert(DNominatedBase == DConstructedBase);
7256
7257 // [class.inhctor.init]p2:
7258 // If the constructor was inherited from multiple base class subobjects
7259 // of type B, the program is ill-formed.
7260 if (!ConstructedBase) {
7261 ConstructedBase = DConstructedBase;
7262 ConstructedBaseIntroducer = D->getIntroducer();
7263 } else if (ConstructedBase != DConstructedBase &&
7264 !Shadow->isInvalidDecl()) {
7265 if (!DiagnosedMultipleConstructedBases) {
7266 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7267 << Shadow->getTargetDecl();
7268 S.Diag(ConstructedBaseIntroducer->getLocation(),
7269 diag::note_ambiguous_inherited_constructor_using)
7270 << ConstructedBase;
7271 DiagnosedMultipleConstructedBases = true;
7272 }
7273 S.Diag(D->getIntroducer()->getLocation(),
7274 diag::note_ambiguous_inherited_constructor_using)
7275 << DConstructedBase;
7276 }
7277 }
7278
7279 if (DiagnosedMultipleConstructedBases)
7280 Shadow->setInvalidDecl();
7281 }
7282
7283 /// Find the constructor to use for inherited construction of a base class,
7284 /// and whether that base class constructor inherits the constructor from a
7285 /// virtual base class (in which case it won't actually invoke it).
7286 std::pair<CXXConstructorDecl *, bool>
7288 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7289 if (It == InheritedFromBases.end())
7290 return std::make_pair(nullptr, false);
7291
7292 // This is an intermediary class.
7293 if (It->second)
7294 return std::make_pair(
7295 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7296 It->second->constructsVirtualBase());
7297
7298 // This is the base class from which the constructor was inherited.
7299 return std::make_pair(Ctor, false);
7300 }
7301};
7302
7303/// Is the special member function which would be selected to perform the
7304/// specified operation on the specified class type a constexpr constructor?
7306 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7307 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7308 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7309 // Suppress duplicate constraint checking here, in case a constraint check
7310 // caused us to decide to do this. Any truely recursive checks will get
7311 // caught during these checks anyway.
7313
7314 // If we're inheriting a constructor, see if we need to call it for this base
7315 // class.
7316 if (InheritedCtor) {
7318 auto BaseCtor =
7319 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7320 if (BaseCtor)
7321 return BaseCtor->isConstexpr();
7322 }
7323
7325 return ClassDecl->hasConstexprDefaultConstructor();
7327 return ClassDecl->hasConstexprDestructor();
7328
7330 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7331 if (!SMOR.getMethod())
7332 // A constructor we wouldn't select can't be "involved in initializing"
7333 // anything.
7334 return true;
7335 return SMOR.getMethod()->isConstexpr();
7336}
7337
7338/// Determine whether the specified special member function would be constexpr
7339/// if it were implicitly defined.
7341 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7342 CXXConstructorDecl *InheritedCtor = nullptr,
7343 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7344 if (!S.getLangOpts().CPlusPlus11)
7345 return false;
7346
7347 // C++11 [dcl.constexpr]p4:
7348 // In the definition of a constexpr constructor [...]
7349 bool Ctor = true;
7350 switch (CSM) {
7352 if (Inherited)
7353 break;
7354 // Since default constructor lookup is essentially trivial (and cannot
7355 // involve, for instance, template instantiation), we compute whether a
7356 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7357 //
7358 // This is important for performance; we need to know whether the default
7359 // constructor is constexpr to determine whether the type is a literal type.
7360 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7361
7364 // For copy or move constructors, we need to perform overload resolution.
7365 break;
7366
7369 if (!S.getLangOpts().CPlusPlus14)
7370 return false;
7371 // In C++1y, we need to perform overload resolution.
7372 Ctor = false;
7373 break;
7374
7376 return ClassDecl->defaultedDestructorIsConstexpr();
7377
7379 return false;
7380 }
7381
7382 // -- if the class is a non-empty union, or for each non-empty anonymous
7383 // union member of a non-union class, exactly one non-static data member
7384 // shall be initialized; [DR1359]
7385 //
7386 // If we squint, this is guaranteed, since exactly one non-static data member
7387 // will be initialized (if the constructor isn't deleted), we just don't know
7388 // which one.
7389 if (Ctor && ClassDecl->isUnion())
7391 ? ClassDecl->hasInClassInitializer() ||
7392 !ClassDecl->hasVariantMembers()
7393 : true;
7394
7395 // -- the class shall not have any virtual base classes;
7396 if (Ctor && ClassDecl->getNumVBases())
7397 return false;
7398
7399 // C++1y [class.copy]p26:
7400 // -- [the class] is a literal type, and
7401 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7402 return false;
7403
7404 // -- every constructor involved in initializing [...] base class
7405 // sub-objects shall be a constexpr constructor;
7406 // -- the assignment operator selected to copy/move each direct base
7407 // class is a constexpr function, and
7408 if (!S.getLangOpts().CPlusPlus23) {
7409 for (const auto &B : ClassDecl->bases()) {
7410 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7411 if (!BaseType)
7412 continue;
7413 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7414 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7415 InheritedCtor, Inherited))
7416 return false;
7417 }
7418 }
7419
7420 // -- every constructor involved in initializing non-static data members
7421 // [...] shall be a constexpr constructor;
7422 // -- every non-static data member and base class sub-object shall be
7423 // initialized
7424 // -- for each non-static data member of X that is of class type (or array
7425 // thereof), the assignment operator selected to copy/move that member is
7426 // a constexpr function
7427 if (!S.getLangOpts().CPlusPlus23) {
7428 for (const auto *F : ClassDecl->fields()) {
7429 if (F->isInvalidDecl())
7430 continue;
7432 F->hasInClassInitializer())
7433 continue;
7434 QualType BaseType = S.Context.getBaseElementType(F->getType());
7435 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7436 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7437 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7438 BaseType.getCVRQualifiers(),
7439 ConstArg && !F->isMutable()))
7440 return false;
7441 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7442 return false;
7443 }
7444 }
7445 }
7446
7447 // All OK, it's constexpr!
7448 return true;
7449}
7450
7451namespace {
7452/// RAII object to register a defaulted function as having its exception
7453/// specification computed.
7454struct ComputingExceptionSpec {
7455 Sema &S;
7456
7457 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7458 : S(S) {
7462 Ctx.Entity = FD;
7464 }
7465 ~ComputingExceptionSpec() {
7467 }
7468};
7469}
7470
7473 CXXMethodDecl *MD,
7476
7479 FunctionDecl *FD,
7481
7484 auto DFK = S.getDefaultedFunctionKind(FD);
7485 if (DFK.isSpecialMember())
7487 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7488 if (DFK.isComparison())
7490 DFK.asComparison());
7491
7492 auto *CD = cast<CXXConstructorDecl>(FD);
7493 assert(CD->getInheritedConstructor() &&
7494 "only defaulted functions and inherited constructors have implicit "
7495 "exception specs");
7497 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7500}
7501
7503 CXXMethodDecl *MD) {
7505
7506 // Build an exception specification pointing back at this member.
7508 EPI.ExceptionSpec.SourceDecl = MD;
7509
7510 // Set the calling convention to the default for C++ instance methods.
7512 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7513 /*IsCXXMethod=*/true));
7514 return EPI;
7515}
7516
7518 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7520 return;
7521
7522 // Evaluate the exception specification.
7523 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7524 auto ESI = IES.getExceptionSpec();
7525
7526 // Update the type of the special member to use it.
7527 UpdateExceptionSpec(FD, ESI);
7528}
7529
7531 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7532
7534 if (!DefKind) {
7535 assert(FD->getDeclContext()->isDependentContext());
7536 return;
7537 }
7538
7539 if (DefKind.isComparison())
7540 UnusedPrivateFields.clear();
7541
7542 if (DefKind.isSpecialMember()
7543 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7544 DefKind.asSpecialMember(),
7545 FD->getDefaultLoc())
7547 FD->setInvalidDecl();
7548}
7549
7552 SourceLocation DefaultLoc) {
7553 CXXRecordDecl *RD = MD->getParent();
7554
7556 "not an explicitly-defaulted special member");
7557
7558 // Defer all checking for special members of a dependent type.
7559 if (RD->isDependentType())
7560 return false;
7561
7562 // Whether this was the first-declared instance of the constructor.
7563 // This affects whether we implicitly add an exception spec and constexpr.
7564 bool First = MD == MD->getCanonicalDecl();
7565
7566 bool HadError = false;
7567
7568 // C++11 [dcl.fct.def.default]p1:
7569 // A function that is explicitly defaulted shall
7570 // -- be a special member function [...] (checked elsewhere),
7571 // -- have the same type (except for ref-qualifiers, and except that a
7572 // copy operation can take a non-const reference) as an implicit
7573 // declaration, and
7574 // -- not have default arguments.
7575 // C++2a changes the second bullet to instead delete the function if it's
7576 // defaulted on its first declaration, unless it's "an assignment operator,
7577 // and its return type differs or its parameter type is not a reference".
7578 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7579 bool ShouldDeleteForTypeMismatch = false;
7580 unsigned ExpectedParams = 1;
7583 ExpectedParams = 0;
7584 if (MD->getNumExplicitParams() != ExpectedParams) {
7585 // This checks for default arguments: a copy or move constructor with a
7586 // default argument is classified as a default constructor, and assignment
7587 // operations and destructors can't have default arguments.
7588 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7589 << llvm::to_underlying(CSM) << MD->getSourceRange();
7590 HadError = true;
7591 } else if (MD->isVariadic()) {
7592 if (DeleteOnTypeMismatch)
7593 ShouldDeleteForTypeMismatch = true;
7594 else {
7595 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7596 << llvm::to_underlying(CSM) << MD->getSourceRange();
7597 HadError = true;
7598 }
7599 }
7600
7602
7603 bool CanHaveConstParam = false;
7605 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7607 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7608
7609 QualType ReturnType = Context.VoidTy;
7612 // Check for return type matching.
7613 ReturnType = Type->getReturnType();
7615
7616 QualType DeclType = Context.getTypeDeclType(RD);
7618 DeclType, nullptr);
7619 DeclType = Context.getAddrSpaceQualType(
7620 DeclType, ThisType.getQualifiers().getAddressSpace());
7621 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7622
7623 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7624 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7626 << ExpectedReturnType;
7627 HadError = true;
7628 }
7629
7630 // A defaulted special member cannot have cv-qualifiers.
7631 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7632 if (DeleteOnTypeMismatch)
7633 ShouldDeleteForTypeMismatch = true;
7634 else {
7635 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7637 << getLangOpts().CPlusPlus14;
7638 HadError = true;
7639 }
7640 }
7641 // [C++23][dcl.fct.def.default]/p2.2
7642 // if F2 has an implicit object parameter of type “reference to C”,
7643 // F1 may be an explicit object member function whose explicit object
7644 // parameter is of (possibly different) type “reference to C”,
7645 // in which case the type of F1 would differ from the type of F2
7646 // in that the type of F1 has an additional parameter;
7647 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7648 ? MD->getParamDecl(0)->getType()
7649 : QualType();
7650 if (!ExplicitObjectParameter.isNull() &&
7651 (!ExplicitObjectParameter->isReferenceType() ||
7652 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7653 Context.getRecordType(RD)))) {
7654 if (DeleteOnTypeMismatch)
7655 ShouldDeleteForTypeMismatch = true;
7656 else {
7657 Diag(MD->getLocation(),
7658 diag::err_defaulted_special_member_explicit_object_mismatch)
7659 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7660 << MD->getSourceRange();
7661 HadError = true;
7662 }
7663 }
7664 }
7665
7666 // Check for parameter type matching.
7667 QualType ArgType =
7668 ExpectedParams
7669 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7670 : QualType();
7671 bool HasConstParam = false;
7672 if (ExpectedParams && ArgType->isReferenceType()) {
7673 // Argument must be reference to possibly-const T.
7674 QualType ReferentType = ArgType->getPointeeType();
7675 HasConstParam = ReferentType.isConstQualified();
7676
7677 if (ReferentType.isVolatileQualified()) {
7678 if (DeleteOnTypeMismatch)
7679 ShouldDeleteForTypeMismatch = true;
7680 else {
7681 Diag(MD->getLocation(),
7682 diag::err_defaulted_special_member_volatile_param)
7683 << llvm::to_underlying(CSM);
7684 HadError = true;
7685 }
7686 }
7687
7688 if (HasConstParam && !CanHaveConstParam) {
7689 if (DeleteOnTypeMismatch)
7690 ShouldDeleteForTypeMismatch = true;
7691 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7693 Diag(MD->getLocation(),
7694 diag::err_defaulted_special_member_copy_const_param)
7696 // FIXME: Explain why this special member can't be const.
7697 HadError = true;
7698 } else {
7699 Diag(MD->getLocation(),
7700 diag::err_defaulted_special_member_move_const_param)
7702 HadError = true;
7703 }
7704 }
7705 } else if (ExpectedParams) {
7706 // A copy assignment operator can take its argument by value, but a
7707 // defaulted one cannot.
7709 "unexpected non-ref argument");
7710 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7711 HadError = true;
7712 }
7713
7714 // C++11 [dcl.fct.def.default]p2:
7715 // An explicitly-defaulted function may be declared constexpr only if it
7716 // would have been implicitly declared as constexpr,
7717 // Do not apply this rule to members of class templates, since core issue 1358
7718 // makes such functions always instantiate to constexpr functions. For
7719 // functions which cannot be constexpr (for non-constructors in C++11 and for
7720 // destructors in C++14 and C++17), this is checked elsewhere.
7721 //
7722 // FIXME: This should not apply if the member is deleted.
7723 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7724 HasConstParam);
7725
7726 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7727 // If the instantiated template specialization of a constexpr function
7728 // template or member function of a class template would fail to satisfy
7729 // the requirements for a constexpr function or constexpr constructor, that
7730 // specialization is still a constexpr function or constexpr constructor,
7731 // even though a call to such a function cannot appear in a constant
7732 // expression.
7733 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7734 Constexpr = true;
7735
7736 if ((getLangOpts().CPlusPlus20 ||
7737 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7738 : isa<CXXConstructorDecl>(MD))) &&
7739 MD->isConstexpr() && !Constexpr &&
7741 if (!MD->isConsteval() && RD->getNumVBases()) {
7742 Diag(MD->getBeginLoc(),
7743 diag::err_incorrect_defaulted_constexpr_with_vb)
7744 << llvm::to_underlying(CSM);
7745 for (const auto &I : RD->vbases())
7746 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7747 } else {
7748 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7749 << llvm::to_underlying(CSM) << MD->isConsteval();
7750 }
7751 HadError = true;
7752 // FIXME: Explain why the special member can't be constexpr.
7753 }
7754
7755 if (First) {
7756 // C++2a [dcl.fct.def.default]p3:
7757 // If a function is explicitly defaulted on its first declaration, it is
7758 // implicitly considered to be constexpr if the implicit declaration
7759 // would be.
7764
7765 if (!Type->hasExceptionSpec()) {
7766 // C++2a [except.spec]p3:
7767 // If a declaration of a function does not have a noexcept-specifier
7768 // [and] is defaulted on its first declaration, [...] the exception
7769 // specification is as specified below
7770 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7772 EPI.ExceptionSpec.SourceDecl = MD;
7773 MD->setType(
7774 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7775 }
7776 }
7777
7778 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7779 if (First) {
7780 SetDeclDeleted(MD, MD->getLocation());
7781 if (!inTemplateInstantiation() && !HadError) {
7782 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7783 << llvm::to_underlying(CSM);
7784 if (ShouldDeleteForTypeMismatch) {
7785 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7786 << llvm::to_underlying(CSM);
7787 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7788 /*Diagnose*/ true) &&
7789 DefaultLoc.isValid()) {
7790 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7791 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7792 }
7793 }
7794 if (ShouldDeleteForTypeMismatch && !HadError) {
7795 Diag(MD->getLocation(),
7796 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7797 << llvm::to_underlying(CSM);
7798 }
7799 } else {
7800 // C++11 [dcl.fct.def.default]p4:
7801 // [For a] user-provided explicitly-defaulted function [...] if such a
7802 // function is implicitly defined as deleted, the program is ill-formed.
7803 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7804 << llvm::to_underlying(CSM);
7805 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7806 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7807 HadError = true;
7808 }
7809 }
7810
7811 return HadError;
7812}
7813
7814namespace {
7815/// Helper class for building and checking a defaulted comparison.
7816///
7817/// Defaulted functions are built in two phases:
7818///
7819/// * First, the set of operations that the function will perform are
7820/// identified, and some of them are checked. If any of the checked
7821/// operations is invalid in certain ways, the comparison function is
7822/// defined as deleted and no body is built.
7823/// * Then, if the function is not defined as deleted, the body is built.
7824///
7825/// This is accomplished by performing two visitation steps over the eventual
7826/// body of the function.
7827template<typename Derived, typename ResultList, typename Result,
7828 typename Subobject>
7829class DefaultedComparisonVisitor {
7830public:
7831 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7832
7833 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7834 DefaultedComparisonKind DCK)
7835 : S(S), RD(RD), FD(FD), DCK(DCK) {
7836 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7837 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7838 // UnresolvedSet to avoid this copy.
7839 Fns.assign(Info->getUnqualifiedLookups().begin(),
7840 Info->getUnqualifiedLookups().end());
7841 }
7842 }
7843
7844 ResultList visit() {
7845 // The type of an lvalue naming a parameter of this function.
7846 QualType ParamLvalType =
7848
7849 ResultList Results;
7850
7851 switch (DCK) {
7852 case DefaultedComparisonKind::None:
7853 llvm_unreachable("not a defaulted comparison");
7854
7855 case DefaultedComparisonKind::Equal:
7856 case DefaultedComparisonKind::ThreeWay:
7857 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7858 return Results;
7859
7860 case DefaultedComparisonKind::NotEqual:
7861 case DefaultedComparisonKind::Relational:
7862 Results.add(getDerived().visitExpandedSubobject(
7863 ParamLvalType, getDerived().getCompleteObject()));
7864 return Results;
7865 }
7866 llvm_unreachable("");
7867 }
7868
7869protected:
7870 Derived &getDerived() { return static_cast<Derived&>(*this); }
7871
7872 /// Visit the expanded list of subobjects of the given type, as specified in
7873 /// C++2a [class.compare.default].
7874 ///
7875 /// \return \c true if the ResultList object said we're done, \c false if not.
7876 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7877 Qualifiers Quals) {
7878 // C++2a [class.compare.default]p4:
7879 // The direct base class subobjects of C
7880 for (CXXBaseSpecifier &Base : Record->bases())
7881 if (Results.add(getDerived().visitSubobject(
7882 S.Context.getQualifiedType(Base.getType(), Quals),
7883 getDerived().getBase(&Base))))
7884 return true;
7885
7886 // followed by the non-static data members of C
7887 for (FieldDecl *Field : Record->fields()) {
7888 // C++23 [class.bit]p2:
7889 // Unnamed bit-fields are not members ...
7890 if (Field->isUnnamedBitField())
7891 continue;
7892 // Recursively expand anonymous structs.
7893 if (Field->isAnonymousStructOrUnion()) {
7894 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7895 Quals))
7896 return true;
7897 continue;
7898 }
7899
7900 // Figure out the type of an lvalue denoting this field.
7901 Qualifiers FieldQuals = Quals;
7902 if (Field->isMutable())
7903 FieldQuals.removeConst();
7904 QualType FieldType =
7905 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7906
7907 if (Results.add(getDerived().visitSubobject(
7908 FieldType, getDerived().getField(Field))))
7909 return true;
7910 }
7911
7912 // form a list of subobjects.
7913 return false;
7914 }
7915
7916 Result visitSubobject(QualType Type, Subobject Subobj) {
7917 // In that list, any subobject of array type is recursively expanded
7918 const ArrayType *AT = S.Context.getAsArrayType(Type);
7919 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7920 return getDerived().visitSubobjectArray(CAT->getElementType(),
7921 CAT->getSize(), Subobj);
7922 return getDerived().visitExpandedSubobject(Type, Subobj);
7923 }
7924
7925 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7926 Subobject Subobj) {
7927 return getDerived().visitSubobject(Type, Subobj);
7928 }
7929
7930protected:
7931 Sema &S;
7932 CXXRecordDecl *RD;
7933 FunctionDecl *FD;
7934 DefaultedComparisonKind DCK;
7936};
7937
7938/// Information about a defaulted comparison, as determined by
7939/// DefaultedComparisonAnalyzer.
7940struct DefaultedComparisonInfo {
7941 bool Deleted = false;
7942 bool Constexpr = true;
7943 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7944
7945 static DefaultedComparisonInfo deleted() {
7946 DefaultedComparisonInfo Deleted;
7947 Deleted.Deleted = true;
7948 return Deleted;
7949 }
7950
7951 bool add(const DefaultedComparisonInfo &R) {
7952 Deleted |= R.Deleted;
7953 Constexpr &= R.Constexpr;
7954 Category = commonComparisonType(Category, R.Category);
7955 return Deleted;
7956 }
7957};
7958
7959/// An element in the expanded list of subobjects of a defaulted comparison, as
7960/// specified in C++2a [class.compare.default]p4.
7961struct DefaultedComparisonSubobject {
7962 enum { CompleteObject, Member, Base } Kind;
7963 NamedDecl *Decl;
7965};
7966
7967/// A visitor over the notional body of a defaulted comparison that determines
7968/// whether that body would be deleted or constexpr.
7969class DefaultedComparisonAnalyzer
7970 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7971 DefaultedComparisonInfo,
7972 DefaultedComparisonInfo,
7973 DefaultedComparisonSubobject> {
7974public:
7975 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7976
7977private:
7978 DiagnosticKind Diagnose;
7979
7980public:
7981 using Base = DefaultedComparisonVisitor;
7982 using Result = DefaultedComparisonInfo;
7983 using Subobject = DefaultedComparisonSubobject;
7984
7985 friend Base;
7986
7987 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7988 DefaultedComparisonKind DCK,
7989 DiagnosticKind Diagnose = NoDiagnostics)
7990 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7991
7992 Result visit() {
7993 if ((DCK == DefaultedComparisonKind::Equal ||
7994 DCK == DefaultedComparisonKind::ThreeWay) &&
7995 RD->hasVariantMembers()) {
7996 // C++2a [class.compare.default]p2 [P2002R0]:
7997 // A defaulted comparison operator function for class C is defined as
7998 // deleted if [...] C has variant members.
7999 if (Diagnose == ExplainDeleted) {
8000 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8001 << FD << RD->isUnion() << RD;
8002 }
8003 return Result::deleted();
8004 }
8005
8006 return Base::visit();
8007 }
8008
8009private:
8010 Subobject getCompleteObject() {
8011 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8012 }
8013
8014 Subobject getBase(CXXBaseSpecifier *Base) {
8015 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8016 Base->getBaseTypeLoc()};
8017 }
8018
8019 Subobject getField(FieldDecl *Field) {
8020 return Subobject{Subobject::Member, Field, Field->getLocation()};
8021 }
8022
8023 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8024 // C++2a [class.compare.default]p2 [P2002R0]:
8025 // A defaulted <=> or == operator function for class C is defined as
8026 // deleted if any non-static data member of C is of reference type
8027 if (Type->isReferenceType()) {
8028 if (Diagnose == ExplainDeleted) {
8029 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8030 << FD << RD;
8031 }
8032 return Result::deleted();
8033 }
8034
8035 // [...] Let xi be an lvalue denoting the ith element [...]
8037 Expr *Args[] = {&Xi, &Xi};
8038
8039 // All operators start by trying to apply that same operator recursively.
8041 assert(OO != OO_None && "not an overloaded operator!");
8042 return visitBinaryOperator(OO, Args, Subobj);
8043 }
8044
8045 Result
8046 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8047 Subobject Subobj,
8048 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8049 // Note that there is no need to consider rewritten candidates here if
8050 // we've already found there is no viable 'operator<=>' candidate (and are
8051 // considering synthesizing a '<=>' from '==' and '<').
8052 OverloadCandidateSet CandidateSet(
8055 OO, FD->getLocation(),
8056 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8057
8058 /// C++2a [class.compare.default]p1 [P2002R0]:
8059 /// [...] the defaulted function itself is never a candidate for overload
8060 /// resolution [...]
8061 CandidateSet.exclude(FD);
8062
8063 if (Args[0]->getType()->isOverloadableType())
8064 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8065 else
8066 // FIXME: We determine whether this is a valid expression by checking to
8067 // see if there's a viable builtin operator candidate for it. That isn't
8068 // really what the rules ask us to do, but should give the right results.
8069 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8070
8071 Result R;
8072
8074 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8075 case OR_Success: {
8076 // C++2a [class.compare.secondary]p2 [P2002R0]:
8077 // The operator function [...] is defined as deleted if [...] the
8078 // candidate selected by overload resolution is not a rewritten
8079 // candidate.
8080 if ((DCK == DefaultedComparisonKind::NotEqual ||
8081 DCK == DefaultedComparisonKind::Relational) &&
8082 !Best->RewriteKind) {
8083 if (Diagnose == ExplainDeleted) {
8084 if (Best->Function) {
8085 S.Diag(Best->Function->getLocation(),
8086 diag::note_defaulted_comparison_not_rewritten_callee)
8087 << FD;
8088 } else {
8089 assert(Best->Conversions.size() == 2 &&
8090 Best->Conversions[0].isUserDefined() &&
8091 "non-user-defined conversion from class to built-in "
8092 "comparison");
8093 S.Diag(Best->Conversions[0]
8094 .UserDefined.FoundConversionFunction.getDecl()
8095 ->getLocation(),
8096 diag::note_defaulted_comparison_not_rewritten_conversion)
8097 << FD;
8098 }
8099 }
8100 return Result::deleted();
8101 }
8102
8103 // Throughout C++2a [class.compare]: if overload resolution does not
8104 // result in a usable function, the candidate function is defined as
8105 // deleted. This requires that we selected an accessible function.
8106 //
8107 // Note that this only considers the access of the function when named
8108 // within the type of the subobject, and not the access path for any
8109 // derived-to-base conversion.
8110 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8111 if (ArgClass && Best->FoundDecl.getDecl() &&
8112 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8113 QualType ObjectType = Subobj.Kind == Subobject::Member
8114 ? Args[0]->getType()
8115 : S.Context.getRecordType(RD);
8117 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8118 Diagnose == ExplainDeleted
8119 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8120 << FD << Subobj.Kind << Subobj.Decl
8121 : S.PDiag()))
8122 return Result::deleted();
8123 }
8124
8125 bool NeedsDeducing =
8126 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8127
8128 if (FunctionDecl *BestFD = Best->Function) {
8129 // C++2a [class.compare.default]p3 [P2002R0]:
8130 // A defaulted comparison function is constexpr-compatible if
8131 // [...] no overlod resolution performed [...] results in a
8132 // non-constexpr function.
8133 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8134 // If it's not constexpr, explain why not.
8135 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8136 if (Subobj.Kind != Subobject::CompleteObject)
8137 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8138 << Subobj.Kind << Subobj.Decl;
8139 S.Diag(BestFD->getLocation(),
8140 diag::note_defaulted_comparison_not_constexpr_here);
8141 // Bail out after explaining; we don't want any more notes.
8142 return Result::deleted();
8143 }
8144 R.Constexpr &= BestFD->isConstexpr();
8145
8146 if (NeedsDeducing) {
8147 // If any callee has an undeduced return type, deduce it now.
8148 // FIXME: It's not clear how a failure here should be handled. For
8149 // now, we produce an eager diagnostic, because that is forward
8150 // compatible with most (all?) other reasonable options.
8151 if (BestFD->getReturnType()->isUndeducedType() &&
8152 S.DeduceReturnType(BestFD, FD->getLocation(),
8153 /*Diagnose=*/false)) {
8154 // Don't produce a duplicate error when asked to explain why the
8155 // comparison is deleted: we diagnosed that when initially checking
8156 // the defaulted operator.
8157 if (Diagnose == NoDiagnostics) {
8158 S.Diag(
8159 FD->getLocation(),
8160 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8161 << Subobj.Kind << Subobj.Decl;
8162 S.Diag(
8163 Subobj.Loc,
8164 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8165 << Subobj.Kind << Subobj.Decl;
8166 S.Diag(BestFD->getLocation(),
8167 diag::note_defaulted_comparison_cannot_deduce_callee)
8168 << Subobj.Kind << Subobj.Decl;
8169 }
8170 return Result::deleted();
8171 }
8173 BestFD->getCallResultType());
8174 if (!Info) {
8175 if (Diagnose == ExplainDeleted) {
8176 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8177 << Subobj.Kind << Subobj.Decl
8178 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8179 S.Diag(BestFD->getLocation(),
8180 diag::note_defaulted_comparison_cannot_deduce_callee)
8181 << Subobj.Kind << Subobj.Decl;
8182 }
8183 return Result::deleted();
8184 }
8185 R.Category = Info->Kind;
8186 }
8187 } else {
8188 QualType T = Best->BuiltinParamTypes[0];
8189 assert(T == Best->BuiltinParamTypes[1] &&
8190 "builtin comparison for different types?");
8191 assert(Best->BuiltinParamTypes[2].isNull() &&
8192 "invalid builtin comparison");
8193
8194 if (NeedsDeducing) {
8195 std::optional<ComparisonCategoryType> Cat =
8197 assert(Cat && "no category for builtin comparison?");
8198 R.Category = *Cat;
8199 }
8200 }
8201
8202 // Note that we might be rewriting to a different operator. That call is
8203 // not considered until we come to actually build the comparison function.
8204 break;
8205 }
8206
8207 case OR_Ambiguous:
8208 if (Diagnose == ExplainDeleted) {
8209 unsigned Kind = 0;
8210 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8211 Kind = OO == OO_EqualEqual ? 1 : 2;
8212 CandidateSet.NoteCandidates(
8214 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8215 << FD << Kind << Subobj.Kind << Subobj.Decl),
8216 S, OCD_AmbiguousCandidates, Args);
8217 }
8218 R = Result::deleted();
8219 break;
8220
8221 case OR_Deleted:
8222 if (Diagnose == ExplainDeleted) {
8223 if ((DCK == DefaultedComparisonKind::NotEqual ||
8224 DCK == DefaultedComparisonKind::Relational) &&
8225 !Best->RewriteKind) {
8226 S.Diag(Best->Function->getLocation(),
8227 diag::note_defaulted_comparison_not_rewritten_callee)
8228 << FD;
8229 } else {
8230 S.Diag(Subobj.Loc,
8231 diag::note_defaulted_comparison_calls_deleted)
8232 << FD << Subobj.Kind << Subobj.Decl;
8233 S.NoteDeletedFunction(Best->Function);
8234 }
8235 }
8236 R = Result::deleted();
8237 break;
8238
8240 // If there's no usable candidate, we're done unless we can rewrite a
8241 // '<=>' in terms of '==' and '<'.
8242 if (OO == OO_Spaceship &&
8244 // For any kind of comparison category return type, we need a usable
8245 // '==' and a usable '<'.
8246 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8247 &CandidateSet)))
8248 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8249 break;
8250 }
8251
8252 if (Diagnose == ExplainDeleted) {
8253 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8254 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8255 << Subobj.Kind << Subobj.Decl;
8256
8257 // For a three-way comparison, list both the candidates for the
8258 // original operator and the candidates for the synthesized operator.
8259 if (SpaceshipCandidates) {
8260 SpaceshipCandidates->NoteCandidates(
8261 S, Args,
8262 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8263 Args, FD->getLocation()));
8264 S.Diag(Subobj.Loc,
8265 diag::note_defaulted_comparison_no_viable_function_synthesized)
8266 << (OO == OO_EqualEqual ? 0 : 1);
8267 }
8268
8269 CandidateSet.NoteCandidates(
8270 S, Args,
8271 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8272 FD->getLocation()));
8273 }
8274 R = Result::deleted();
8275 break;
8276 }
8277
8278 return R;
8279 }
8280};
8281
8282/// A list of statements.
8283struct StmtListResult {
8284 bool IsInvalid = false;
8286
8287 bool add(const StmtResult &S) {
8288 IsInvalid |= S.isInvalid();
8289 if (IsInvalid)
8290 return true;
8291 Stmts.push_back(S.get());
8292 return false;
8293 }
8294};
8295
8296/// A visitor over the notional body of a defaulted comparison that synthesizes
8297/// the actual body.
8298class DefaultedComparisonSynthesizer
8299 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8300 StmtListResult, StmtResult,
8301 std::pair<ExprResult, ExprResult>> {
8303 unsigned ArrayDepth = 0;
8304
8305public:
8306 using Base = DefaultedComparisonVisitor;
8307 using ExprPair = std::pair<ExprResult, ExprResult>;
8308
8309 friend Base;
8310
8311 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8312 DefaultedComparisonKind DCK,
8313 SourceLocation BodyLoc)
8314 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8315
8316 /// Build a suitable function body for this defaulted comparison operator.
8317 StmtResult build() {
8318 Sema::CompoundScopeRAII CompoundScope(S);
8319
8320 StmtListResult Stmts = visit();
8321 if (Stmts.IsInvalid)
8322 return StmtError();
8323
8324 ExprResult RetVal;
8325 switch (DCK) {
8326 case DefaultedComparisonKind::None:
8327 llvm_unreachable("not a defaulted comparison");
8328
8329 case DefaultedComparisonKind::Equal: {
8330 // C++2a [class.eq]p3:
8331 // [...] compar[e] the corresponding elements [...] until the first
8332 // index i where xi == yi yields [...] false. If no such index exists,
8333 // V is true. Otherwise, V is false.
8334 //
8335 // Join the comparisons with '&&'s and return the result. Use a right
8336 // fold (traversing the conditions right-to-left), because that
8337 // short-circuits more naturally.
8338 auto OldStmts = std::move(Stmts.Stmts);
8339 Stmts.Stmts.clear();
8340 ExprResult CmpSoFar;
8341 // Finish a particular comparison chain.
8342 auto FinishCmp = [&] {
8343 if (Expr *Prior = CmpSoFar.get()) {
8344 // Convert the last expression to 'return ...;'
8345 if (RetVal.isUnset() && Stmts.Stmts.empty())
8346 RetVal = CmpSoFar;
8347 // Convert any prior comparison to 'if (!(...)) return false;'
8348 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8349 return true;
8350 CmpSoFar = ExprResult();
8351 }
8352 return false;
8353 };
8354 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8355 Expr *E = dyn_cast<Expr>(EAsStmt);
8356 if (!E) {
8357 // Found an array comparison.
8358 if (FinishCmp() || Stmts.add(EAsStmt))
8359 return StmtError();
8360 continue;
8361 }
8362
8363 if (CmpSoFar.isUnset()) {
8364 CmpSoFar = E;
8365 continue;
8366 }
8367 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8368 if (CmpSoFar.isInvalid())
8369 return StmtError();
8370 }
8371 if (FinishCmp())
8372 return StmtError();
8373 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8374 // If no such index exists, V is true.
8375 if (RetVal.isUnset())
8376 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8377 break;
8378 }
8379
8380 case DefaultedComparisonKind::ThreeWay: {
8381 // Per C++2a [class.spaceship]p3, as a fallback add:
8382 // return static_cast<R>(std::strong_ordering::equal);
8384 ComparisonCategoryType::StrongOrdering, Loc,
8385 Sema::ComparisonCategoryUsage::DefaultedOperator);
8386 if (StrongOrdering.isNull())
8387 return StmtError();
8389 .getValueInfo(ComparisonCategoryResult::Equal)
8390 ->VD;
8391 RetVal = getDecl(EqualVD);
8392 if (RetVal.isInvalid())
8393 return StmtError();
8394 RetVal = buildStaticCastToR(RetVal.get());
8395 break;
8396 }
8397
8398 case DefaultedComparisonKind::NotEqual:
8399 case DefaultedComparisonKind::Relational:
8400 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8401 break;
8402 }
8403
8404 // Build the final return statement.
8405 if (RetVal.isInvalid())
8406 return StmtError();
8408 if (ReturnStmt.isInvalid())
8409 return StmtError();
8410 Stmts.Stmts.push_back(ReturnStmt.get());
8411
8412 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8413 }
8414
8415private:
8416 ExprResult getDecl(ValueDecl *VD) {
8417 return S.BuildDeclarationNameExpr(
8419 }
8420
8421 ExprResult getParam(unsigned I) {
8422 ParmVarDecl *PD = FD->getParamDecl(I);
8423 return getDecl(PD);
8424 }
8425
8426 ExprPair getCompleteObject() {
8427 unsigned Param = 0;
8428 ExprResult LHS;
8429 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8430 MD && MD->isImplicitObjectMemberFunction()) {
8431 // LHS is '*this'.
8432 LHS = S.ActOnCXXThis(Loc);
8433 if (!LHS.isInvalid())
8434 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8435 } else {
8436 LHS = getParam(Param++);
8437 }
8438 ExprResult RHS = getParam(Param++);
8439 assert(Param == FD->getNumParams());
8440 return {LHS, RHS};
8441 }
8442
8443 ExprPair getBase(CXXBaseSpecifier *Base) {
8444 ExprPair Obj = getCompleteObject();
8445 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8446 return {ExprError(), ExprError()};
8447 CXXCastPath Path = {Base};
8448 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8449 CK_DerivedToBase, VK_LValue, &Path),
8450 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8451 CK_DerivedToBase, VK_LValue, &Path)};
8452 }
8453
8454 ExprPair getField(FieldDecl *Field) {
8455 ExprPair Obj = getCompleteObject();
8456 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8457 return {ExprError(), ExprError()};
8458
8459 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8460 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8461 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8462 CXXScopeSpec(), Field, Found, NameInfo),
8463 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8464 CXXScopeSpec(), Field, Found, NameInfo)};
8465 }
8466
8467 // FIXME: When expanding a subobject, register a note in the code synthesis
8468 // stack to say which subobject we're comparing.
8469
8470 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8471 if (Cond.isInvalid())
8472 return StmtError();
8473
8474 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8475 if (NotCond.isInvalid())
8476 return StmtError();
8477
8478 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8479 assert(!False.isInvalid() && "should never fail");
8480 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8481 if (ReturnFalse.isInvalid())
8482 return StmtError();
8483
8484 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8485 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8486 Sema::ConditionKind::Boolean),
8487 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8488 }
8489
8490 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8491 ExprPair Subobj) {
8492 QualType SizeType = S.Context.getSizeType();
8493 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8494
8495 // Build 'size_t i$n = 0'.
8496 IdentifierInfo *IterationVarName = nullptr;
8497 {
8498 SmallString<8> Str;
8499 llvm::raw_svector_ostream OS(Str);
8500 OS << "i" << ArrayDepth;
8501 IterationVarName = &S.Context.Idents.get(OS.str());
8502 }
8503 VarDecl *IterationVar = VarDecl::Create(
8504 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8506 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8507 IterationVar->setInit(
8508 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8509 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8510
8511 auto IterRef = [&] {
8513 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8514 IterationVar);
8515 assert(!Ref.isInvalid() && "can't reference our own variable?");
8516 return Ref.get();
8517 };
8518
8519 // Build 'i$n != Size'.
8521 Loc, BO_NE, IterRef(),
8522 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8523 assert(!Cond.isInvalid() && "should never fail");
8524
8525 // Build '++i$n'.
8526 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8527 assert(!Inc.isInvalid() && "should never fail");
8528
8529 // Build 'a[i$n]' and 'b[i$n]'.
8530 auto Index = [&](ExprResult E) {
8531 if (E.isInvalid())
8532 return ExprError();
8533 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8534 };
8535 Subobj.first = Index(Subobj.first);
8536 Subobj.second = Index(Subobj.second);
8537
8538 // Compare the array elements.
8539 ++ArrayDepth;
8540 StmtResult Substmt = visitSubobject(Type, Subobj);
8541 --ArrayDepth;
8542
8543 if (Substmt.isInvalid())
8544 return StmtError();
8545
8546 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8547 // For outer levels or for an 'operator<=>' we already have a suitable
8548 // statement that returns as necessary.
8549 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8550 assert(DCK == DefaultedComparisonKind::Equal &&
8551 "should have non-expression statement");
8552 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8553 if (Substmt.isInvalid())
8554 return StmtError();
8555 }
8556
8557 // Build 'for (...) ...'
8558 return S.ActOnForStmt(Loc, Loc, Init,
8559 S.ActOnCondition(nullptr, Loc, Cond.get(),
8560 Sema::ConditionKind::Boolean),
8562 Substmt.get());
8563 }
8564
8565 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8566 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8567 return StmtError();
8568
8571 ExprResult Op;
8572 if (Type->isOverloadableType())
8573 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8574 Obj.second.get(), /*PerformADL=*/true,
8575 /*AllowRewrittenCandidates=*/true, FD);
8576 else
8577 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8578 if (Op.isInvalid())
8579 return StmtError();
8580
8581 switch (DCK) {
8582 case DefaultedComparisonKind::None:
8583 llvm_unreachable("not a defaulted comparison");
8584
8585 case DefaultedComparisonKind::Equal:
8586 // Per C++2a [class.eq]p2, each comparison is individually contextually
8587 // converted to bool.
8589 if (Op.isInvalid())
8590 return StmtError();
8591 return Op.get();
8592
8593 case DefaultedComparisonKind::ThreeWay: {
8594 // Per C++2a [class.spaceship]p3, form:
8595 // if (R cmp = static_cast<R>(op); cmp != 0)
8596 // return cmp;
8597 QualType R = FD->getReturnType();
8598 Op = buildStaticCastToR(Op.get());
8599 if (Op.isInvalid())
8600 return StmtError();
8601
8602 // R cmp = ...;
8603 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8604 VarDecl *VD =
8605 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8607 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8608 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8609
8610 // cmp != 0
8611 ExprResult VDRef = getDecl(VD);
8612 if (VDRef.isInvalid())
8613 return StmtError();
8614 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8615 Expr *Zero =
8618 if (VDRef.get()->getType()->isOverloadableType())
8619 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8620 true, FD);
8621 else
8622 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8623 if (Comp.isInvalid())
8624 return StmtError();
8626 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8627 if (Cond.isInvalid())
8628 return StmtError();
8629
8630 // return cmp;
8631 VDRef = getDecl(VD);
8632 if (VDRef.isInvalid())
8633 return StmtError();
8635 if (ReturnStmt.isInvalid())
8636 return StmtError();
8637
8638 // if (...)
8639 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8640 Loc, ReturnStmt.get(),
8641 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8642 }
8643
8644 case DefaultedComparisonKind::NotEqual:
8645 case DefaultedComparisonKind::Relational:
8646 // C++2a [class.compare.secondary]p2:
8647 // Otherwise, the operator function yields x @ y.
8648 return Op.get();
8649 }
8650 llvm_unreachable("");
8651 }
8652
8653 /// Build "static_cast<R>(E)".
8654 ExprResult buildStaticCastToR(Expr *E) {
8655 QualType R = FD->getReturnType();
8656 assert(!R->isUndeducedType() && "type should have been deduced already");
8657
8658 // Don't bother forming a no-op cast in the common case.
8659 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8660 return E;
8661 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8664 }
8665};
8666}
8667
8668/// Perform the unqualified lookups that might be needed to form a defaulted
8669/// comparison function for the given operator.
8671 UnresolvedSetImpl &Operators,
8673 auto Lookup = [&](OverloadedOperatorKind OO) {
8674 Self.LookupOverloadedOperatorName(OO, S, Operators);
8675 };
8676
8677 // Every defaulted operator looks up itself.
8678 Lookup(Op);
8679 // ... and the rewritten form of itself, if any.
8681 Lookup(ExtraOp);
8682
8683 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8684 // synthesize a three-way comparison from '<' and '=='. In a dependent
8685 // context, we also need to look up '==' in case we implicitly declare a
8686 // defaulted 'operator=='.
8687 if (Op == OO_Spaceship) {
8688 Lookup(OO_ExclaimEqual);
8689 Lookup(OO_Less);
8690 Lookup(OO_EqualEqual);
8691 }
8692}
8693
8696 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8697
8698 // Perform any unqualified lookups we're going to need to default this
8699 // function.
8700 if (S) {
8701 UnresolvedSet<32> Operators;
8702 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8703 FD->getOverloadedOperator());
8706 Context, Operators.pairs()));
8707 }
8708
8709 // C++2a [class.compare.default]p1:
8710 // A defaulted comparison operator function for some class C shall be a
8711 // non-template function declared in the member-specification of C that is
8712 // -- a non-static const non-volatile member of C having one parameter of
8713 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8714 // -- a friend of C having two parameters of type const C& or two
8715 // parameters of type C.
8716
8717 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8718 bool IsMethod = isa<CXXMethodDecl>(FD);
8719 if (IsMethod) {
8720 auto *MD = cast<CXXMethodDecl>(FD);
8721 assert(!MD->isStatic() && "comparison function cannot be a static member");
8722
8723 if (MD->getRefQualifier() == RQ_RValue) {
8724 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8725
8726 // Remove the ref qualifier to recover.
8727 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8728 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8729 EPI.RefQualifier = RQ_None;
8730 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8731 FPT->getParamTypes(), EPI));
8732 }
8733
8734 // If we're out-of-class, this is the class we're comparing.
8735 if (!RD)
8736 RD = MD->getParent();
8738 if (!T.getNonReferenceType().isConstQualified() &&
8740 SourceLocation Loc, InsertLoc;
8742 Loc = MD->getParamDecl(0)->getBeginLoc();
8743 InsertLoc = getLocForEndOfToken(
8745 } else {
8746 Loc = MD->getLocation();
8748 InsertLoc = Loc.getRParenLoc();
8749 }
8750 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8751 // corresponding defaulted 'operator<=>' already.
8752 if (!MD->isImplicit()) {
8753 Diag(Loc, diag::err_defaulted_comparison_non_const)
8754 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8755 }
8756
8757 // Add the 'const' to the type to recover.
8759 assert(T->isLValueReferenceType());
8761 T.getNonReferenceType().withConst()));
8762 } else {
8763 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8764 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8765 EPI.TypeQuals.addConst();
8766 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8767 FPT->getParamTypes(), EPI));
8768 }
8769 }
8770
8771 if (MD->isVolatile()) {
8772 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8773
8774 // Remove the 'volatile' from the type to recover.
8775 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8776 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8778 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8779 FPT->getParamTypes(), EPI));
8780 }
8781 }
8782
8783 if ((FD->getNumParams() -
8784 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8785 (IsMethod ? 1 : 2)) {
8786 // Let's not worry about using a variadic template pack here -- who would do
8787 // such a thing?
8788 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8789 << int(IsMethod) << int(DCK);
8790 return true;
8791 }
8792
8793 const ParmVarDecl *KnownParm = nullptr;
8794 for (const ParmVarDecl *Param : FD->parameters()) {
8795 QualType ParmTy = Param->getType();
8796 if (!KnownParm) {
8797 auto CTy = ParmTy;
8798 // Is it `T const &`?
8799 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8800 QualType ExpectedTy;
8801 if (RD)
8802 ExpectedTy = Context.getRecordType(RD);
8803 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8804 CTy = Ref->getPointeeType();
8805 if (RD)
8806 ExpectedTy.addConst();
8807 Ok = true;
8808 }
8809
8810 // Is T a class?
8811 if (RD) {
8812 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
8813 } else {
8814 RD = CTy->getAsCXXRecordDecl();
8815 Ok &= RD != nullptr;
8816 }
8817
8818 if (Ok) {
8819 KnownParm = Param;
8820 } else {
8821 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8822 // corresponding defaulted 'operator<=>' already.
8823 if (!FD->isImplicit()) {
8824 if (RD) {
8825 QualType PlainTy = Context.getRecordType(RD);
8826 QualType RefTy =
8828 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8829 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8830 << Param->getSourceRange();
8831 } else {
8832 assert(!IsMethod && "should know expected type for method");
8833 Diag(FD->getLocation(),
8834 diag::err_defaulted_comparison_param_unknown)
8835 << int(DCK) << ParmTy << Param->getSourceRange();
8836 }
8837 }
8838 return true;
8839 }
8840 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8841 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8842 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8843 << ParmTy << Param->getSourceRange();
8844 return true;
8845 }
8846 }
8847
8848 assert(RD && "must have determined class");
8849 if (IsMethod) {
8850 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8851 // In-class, must be a friend decl.
8852 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8853 } else {
8854 // Out of class, require the defaulted comparison to be a friend (of a
8855 // complete type, per CWG2547).
8857 diag::err_defaulted_comparison_not_friend, int(DCK),
8858 int(1)))
8859 return true;
8860
8861 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8862 return FD->getCanonicalDecl() ==
8863 F->getFriendDecl()->getCanonicalDecl();
8864 })) {
8865 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8866 << int(DCK) << int(0) << RD;
8867 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8868 return true;
8869 }
8870 }
8871
8872 // C++2a [class.eq]p1, [class.rel]p1:
8873 // A [defaulted comparison other than <=>] shall have a declared return
8874 // type bool.
8878 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8879 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8880 << FD->getReturnTypeSourceRange();
8881 return true;
8882 }
8883 // C++2a [class.spaceship]p2 [P2002R0]:
8884 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8885 // R shall not contain a placeholder type.
8886 if (QualType RT = FD->getDeclaredReturnType();
8888 RT->getContainedDeducedType() &&
8890 RT->getContainedAutoType()->isConstrained())) {
8891 Diag(FD->getLocation(),
8892 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8893 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8894 << FD->getReturnTypeSourceRange();
8895 return true;
8896 }
8897
8898 // For a defaulted function in a dependent class, defer all remaining checks
8899 // until instantiation.
8900 if (RD->isDependentType())
8901 return false;
8902
8903 // Determine whether the function should be defined as deleted.
8904 DefaultedComparisonInfo Info =
8905 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8906
8907 bool First = FD == FD->getCanonicalDecl();
8908
8909 if (!First) {
8910 if (Info.Deleted) {
8911 // C++11 [dcl.fct.def.default]p4:
8912 // [For a] user-provided explicitly-defaulted function [...] if such a
8913 // function is implicitly defined as deleted, the program is ill-formed.
8914 //
8915 // This is really just a consequence of the general rule that you can
8916 // only delete a function on its first declaration.
8917 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8918 << FD->isImplicit() << (int)DCK;
8919 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8920 DefaultedComparisonAnalyzer::ExplainDeleted)
8921 .visit();
8922 return true;
8923 }
8924 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8925 // C++20 [class.compare.default]p1:
8926 // [...] A definition of a comparison operator as defaulted that appears
8927 // in a class shall be the first declaration of that function.
8928 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8929 << (int)DCK;
8931 diag::note_previous_declaration);
8932 return true;
8933 }
8934 }
8935
8936 // If we want to delete the function, then do so; there's nothing else to
8937 // check in that case.
8938 if (Info.Deleted) {
8939 SetDeclDeleted(FD, FD->getLocation());
8940 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8941 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8942 << (int)DCK;
8943 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8944 DefaultedComparisonAnalyzer::ExplainDeleted)
8945 .visit();
8946 if (FD->getDefaultLoc().isValid())
8947 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8948 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8949 }
8950 return false;
8951 }
8952
8953 // C++2a [class.spaceship]p2:
8954 // The return type is deduced as the common comparison type of R0, R1, ...
8958 if (RetLoc.isInvalid())
8959 RetLoc = FD->getBeginLoc();
8960 // FIXME: Should we really care whether we have the complete type and the
8961 // 'enumerator' constants here? A forward declaration seems sufficient.
8963 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8964 if (Cat.isNull())
8965 return true;
8967 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8968 }
8969
8970 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8971 // An explicitly-defaulted function that is not defined as deleted may be
8972 // declared constexpr or consteval only if it is constexpr-compatible.
8973 // C++2a [class.compare.default]p3 [P2002R0]:
8974 // A defaulted comparison function is constexpr-compatible if it satisfies
8975 // the requirements for a constexpr function [...]
8976 // The only relevant requirements are that the parameter and return types are
8977 // literal types. The remaining conditions are checked by the analyzer.
8978 //
8979 // We support P2448R2 in language modes earlier than C++23 as an extension.
8980 // The concept of constexpr-compatible was removed.
8981 // C++23 [dcl.fct.def.default]p3 [P2448R2]
8982 // A function explicitly defaulted on its first declaration is implicitly
8983 // inline, and is implicitly constexpr if it is constexpr-suitable.
8984 // C++23 [dcl.constexpr]p3
8985 // A function is constexpr-suitable if
8986 // - it is not a coroutine, and
8987 // - if the function is a constructor or destructor, its class does not
8988 // have any virtual base classes.
8989 if (FD->isConstexpr()) {
8990 if (!getLangOpts().CPlusPlus23 &&
8993 !Info.Constexpr) {
8994 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
8995 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8996 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8997 DefaultedComparisonAnalyzer::ExplainConstexpr)
8998 .visit();
8999 }
9000 }
9001
9002 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9003 // If a constexpr-compatible function is explicitly defaulted on its first
9004 // declaration, it is implicitly considered to be constexpr.
9005 // FIXME: Only applying this to the first declaration seems problematic, as
9006 // simple reorderings can affect the meaning of the program.
9007 if (First && !FD->isConstexpr() && Info.Constexpr)
9009
9010 // C++2a [except.spec]p3:
9011 // If a declaration of a function does not have a noexcept-specifier
9012 // [and] is defaulted on its first declaration, [...] the exception
9013 // specification is as specified below
9014 if (FD->getExceptionSpecType() == EST_None) {
9015 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9016 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9018 EPI.ExceptionSpec.SourceDecl = FD;
9019 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9020 FPT->getParamTypes(), EPI));
9021 }
9022
9023 return false;
9024}
9025
9027 FunctionDecl *Spaceship) {
9030 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9031 Ctx.Entity = Spaceship;
9033
9034 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9035 EqualEqual->setImplicit();
9036
9038}
9039
9042 assert(FD->isDefaulted() && !FD->isDeleted() &&
9044 if (FD->willHaveBody() || FD->isInvalidDecl())
9045 return;
9046
9048
9049 // Add a context note for diagnostics produced after this point.
9050 Scope.addContextNote(UseLoc);
9051
9052 {
9053 // Build and set up the function body.
9054 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9055 // the type of the class being compared.
9056 auto PT = FD->getParamDecl(0)->getType();
9057 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9058 SourceLocation BodyLoc =
9059 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9060 StmtResult Body =
9061 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9062 if (Body.isInvalid()) {
9063 FD->setInvalidDecl();
9064 return;
9065 }
9066 FD->setBody(Body.get());
9067 FD->markUsed(Context);
9068 }
9069
9070 // The exception specification is needed because we are defining the
9071 // function. Note that this will reuse the body we just built.
9073
9075 L->CompletedImplicitDefinition(FD);
9076}
9077
9080 FunctionDecl *FD,
9082 ComputingExceptionSpec CES(S, FD, Loc);
9084
9085 if (FD->isInvalidDecl())
9086 return ExceptSpec;
9087
9088 // The common case is that we just defined the comparison function. In that
9089 // case, just look at whether the body can throw.
9090 if (FD->hasBody()) {
9091 ExceptSpec.CalledStmt(FD->getBody());
9092 } else {
9093 // Otherwise, build a body so we can check it. This should ideally only
9094 // happen when we're not actually marking the function referenced. (This is
9095 // only really important for efficiency: we don't want to build and throw
9096 // away bodies for comparison functions more than we strictly need to.)
9097
9098 // Pretend to synthesize the function body in an unevaluated context.
9099 // Note that we can't actually just go ahead and define the function here:
9100 // we are not permitted to mark its callees as referenced.
9104
9105 CXXRecordDecl *RD =
9106 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9107 ? FD->getDeclContext()
9108 : FD->getLexicalDeclContext());
9109 SourceLocation BodyLoc =
9110 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9111 StmtResult Body =
9112 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9113 if (!Body.isInvalid())
9114 ExceptSpec.CalledStmt(Body.get());
9115
9116 // FIXME: Can we hold onto this body and just transform it to potentially
9117 // evaluated when we're asked to define the function rather than rebuilding
9118 // it? Either that, or we should only build the bits of the body that we
9119 // need (the expressions, not the statements).
9120 }
9121
9122 return ExceptSpec;
9123}
9124
9126 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9128
9129 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9131
9132 // Perform any deferred checking of exception specifications for virtual
9133 // destructors.
9134 for (auto &Check : Overriding)
9135 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9136
9137 // Perform any deferred checking of exception specifications for befriended
9138 // special members.
9139 for (auto &Check : Equivalent)
9140 CheckEquivalentExceptionSpec(Check.second, Check.first);
9141}
9142
9143namespace {
9144/// CRTP base class for visiting operations performed by a special member
9145/// function (or inherited constructor).
9146template<typename Derived>
9147struct SpecialMemberVisitor {
9148 Sema &S;
9149 CXXMethodDecl *MD;
9152
9153 // Properties of the special member, computed for convenience.
9154 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9155
9156 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9158 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9159 switch (CSM) {
9160 case CXXSpecialMemberKind::DefaultConstructor:
9161 case CXXSpecialMemberKind::CopyConstructor:
9162 case CXXSpecialMemberKind::MoveConstructor:
9163 IsConstructor = true;
9164 break;
9165 case CXXSpecialMemberKind::CopyAssignment:
9166 case CXXSpecialMemberKind::MoveAssignment:
9167 IsAssignment = true;
9168 break;
9169 case CXXSpecialMemberKind::Destructor:
9170 break;
9171 case CXXSpecialMemberKind::Invalid:
9172 llvm_unreachable("invalid special member kind");
9173 }
9174
9175 if (MD->getNumExplicitParams()) {
9176 if (const ReferenceType *RT =
9178 ConstArg = RT->getPointeeType().isConstQualified();
9179 }
9180 }
9181
9182 Derived &getDerived() { return static_cast<Derived&>(*this); }
9183
9184 /// Is this a "move" special member?
9185 bool isMove() const {
9186 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9187 CSM == CXXSpecialMemberKind::MoveAssignment;
9188 }
9189
9190 /// Look up the corresponding special member in the given class.
9192 unsigned Quals, bool IsMutable) {
9193 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9194 ConstArg && !IsMutable);
9195 }
9196
9197 /// Look up the constructor for the specified base class to see if it's
9198 /// overridden due to this being an inherited constructor.
9199 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9200 if (!ICI)
9201 return {};
9202 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9203 auto *BaseCtor =
9204 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9205 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9206 return MD;
9207 return {};
9208 }
9209
9210 /// A base or member subobject.
9211 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9212
9213 /// Get the location to use for a subobject in diagnostics.
9214 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9215 // FIXME: For an indirect virtual base, the direct base leading to
9216 // the indirect virtual base would be a more useful choice.
9217 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9218 return B->getBaseTypeLoc();
9219 else
9220 return Subobj.get<FieldDecl*>()->getLocation();
9221 }
9222
9223 enum BasesToVisit {
9224 /// Visit all non-virtual (direct) bases.
9225 VisitNonVirtualBases,
9226 /// Visit all direct bases, virtual or not.
9227 VisitDirectBases,
9228 /// Visit all non-virtual bases, and all virtual bases if the class
9229 /// is not abstract.
9230 VisitPotentiallyConstructedBases,
9231 /// Visit all direct or virtual bases.
9232 VisitAllBases
9233 };
9234
9235 // Visit the bases and members of the class.
9236 bool visit(BasesToVisit Bases) {
9237 CXXRecordDecl *RD = MD->getParent();
9238
9239 if (Bases == VisitPotentiallyConstructedBases)
9240 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9241
9242 for (auto &B : RD->bases())
9243 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9244 getDerived().visitBase(&B))
9245 return true;
9246
9247 if (Bases == VisitAllBases)
9248 for (auto &B : RD->vbases())
9249 if (getDerived().visitBase(&B))
9250 return true;
9251
9252 for (auto *F : RD->fields())
9253 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9254 getDerived().visitField(F))
9255 return true;
9256
9257 return false;
9258 }
9259};
9260}
9261
9262namespace {
9263struct SpecialMemberDeletionInfo
9264 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9265 bool Diagnose;
9266
9268
9269 bool AllFieldsAreConst;
9270
9271 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9273 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9274 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9275 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9276
9277 bool inUnion() const { return MD->getParent()->isUnion(); }
9278
9279 CXXSpecialMemberKind getEffectiveCSM() {
9280 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9281 }
9282
9283 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9284
9285 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9286 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9287
9288 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9289 bool shouldDeleteForField(FieldDecl *FD);
9290 bool shouldDeleteForAllConstMembers();
9291
9292 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9293 unsigned Quals);
9294 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9296 bool IsDtorCallInCtor);
9297
9298 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9299};
9300}
9301
9302/// Is the given special member inaccessible when used on the given
9303/// sub-object.
9304bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9305 CXXMethodDecl *target) {
9306 /// If we're operating on a base class, the object type is the
9307 /// type of this special member.
9308 QualType objectTy;
9309 AccessSpecifier access = target->getAccess();
9310 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9311 objectTy = S.Context.getTypeDeclType(MD->getParent());
9312 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9313
9314 // If we're operating on a field, the object type is the type of the field.
9315 } else {
9316 objectTy = S.Context.getTypeDeclType(target->getParent());
9317 }
9318
9320 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9321}
9322
9323/// Check whether we should delete a special member due to the implicit
9324/// definition containing a call to a special member of a subobject.
9325bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9326 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9327 bool IsDtorCallInCtor) {
9328 CXXMethodDecl *Decl = SMOR.getMethod();
9329 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9330
9331 int DiagKind = -1;
9332
9334 DiagKind = !Decl ? 0 : 1;
9336 DiagKind = 2;
9337 else if (!isAccessible(Subobj, Decl))
9338 DiagKind = 3;
9339 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9340 !Decl->isTrivial()) {
9341 // A member of a union must have a trivial corresponding special member.
9342 // As a weird special case, a destructor call from a union's constructor
9343 // must be accessible and non-deleted, but need not be trivial. Such a
9344 // destructor is never actually called, but is semantically checked as
9345 // if it were.
9347 // [class.default.ctor]p2:
9348 // A defaulted default constructor for class X is defined as deleted if
9349 // - X is a union that has a variant member with a non-trivial default
9350 // constructor and no variant member of X has a default member
9351 // initializer
9352 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9353 if (!RD->hasInClassInitializer())
9354 DiagKind = 4;
9355 } else {
9356 DiagKind = 4;
9357 }
9358 }
9359
9360 if (DiagKind == -1)
9361 return false;
9362
9363 if (Diagnose) {
9364 if (Field) {
9365 S.Diag(Field->getLocation(),
9366 diag::note_deleted_special_member_class_subobject)
9367 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9368 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9369 << /*IsObjCPtr*/ false;
9370 } else {
9371 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9372 S.Diag(Base->getBeginLoc(),
9373 diag::note_deleted_special_member_class_subobject)
9374 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9375 << /*IsField*/ false << Base->getType() << DiagKind
9376 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9377 }
9378
9379 if (DiagKind == 1)
9381 // FIXME: Explain inaccessibility if DiagKind == 3.
9382 }
9383
9384 return true;
9385}
9386
9387/// Check whether we should delete a special member function due to having a
9388/// direct or virtual base class or non-static data member of class type M.
9389bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9390 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9391 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9392 bool IsMutable = Field && Field->isMutable();
9393
9394 // C++11 [class.ctor]p5:
9395 // -- any direct or virtual base class, or non-static data member with no
9396 // brace-or-equal-initializer, has class type M (or array thereof) and
9397 // either M has no default constructor or overload resolution as applied
9398 // to M's default constructor results in an ambiguity or in a function
9399 // that is deleted or inaccessible
9400 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9401 // -- a direct or virtual base class B that cannot be copied/moved because
9402 // overload resolution, as applied to B's corresponding special member,
9403 // results in an ambiguity or a function that is deleted or inaccessible
9404 // from the defaulted special member
9405 // C++11 [class.dtor]p5:
9406 // -- any direct or virtual base class [...] has a type with a destructor
9407 // that is deleted or inaccessible
9408 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9409 Field->hasInClassInitializer()) &&
9410 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9411 false))
9412 return true;
9413
9414 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9415 // -- any direct or virtual base class or non-static data member has a
9416 // type with a destructor that is deleted or inaccessible
9417 if (IsConstructor) {
9420 false, false, false, false);
9421 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9422 return true;
9423 }
9424
9425 return false;
9426}
9427
9428bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9429 FieldDecl *FD, QualType FieldType) {
9430 // The defaulted special functions are defined as deleted if this is a variant
9431 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9432 // type under ARC.
9433 if (!FieldType.hasNonTrivialObjCLifetime())
9434 return false;
9435
9436 // Don't make the defaulted default constructor defined as deleted if the
9437 // member has an in-class initializer.
9440 return false;
9441
9442 if (Diagnose) {
9443 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9444 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9445 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9446 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9447 << /*IsObjCPtr*/ true;
9448 }
9449
9450 return true;
9451}
9452
9453/// Check whether we should delete a special member function due to the class
9454/// having a particular direct or virtual base class.
9455bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9456 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9457 // If program is correct, BaseClass cannot be null, but if it is, the error
9458 // must be reported elsewhere.
9459 if (!BaseClass)
9460 return false;
9461 // If we have an inheriting constructor, check whether we're calling an
9462 // inherited constructor instead of a default constructor.
9463 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9464 if (auto *BaseCtor = SMOR.getMethod()) {
9465 // Note that we do not check access along this path; other than that,
9466 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9467 // FIXME: Check that the base has a usable destructor! Sink this into
9468 // shouldDeleteForClassSubobject.
9469 if (BaseCtor->isDeleted() && Diagnose) {
9470 S.Diag(Base->getBeginLoc(),
9471 diag::note_deleted_special_member_class_subobject)
9472 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9473 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9474 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9475 S.NoteDeletedFunction(BaseCtor);
9476 }
9477 return BaseCtor->isDeleted();
9478 }
9479 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9480}
9481
9482/// Check whether we should delete a special member function due to the class
9483/// having a particular non-static data member.
9484bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9485 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9486 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9487
9488 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9489 return true;
9490
9492 // For a default constructor, all references must be initialized in-class
9493 // and, if a union, it must have a non-const member.
9494 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9495 if (Diagnose)
9496 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9497 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9498 return true;
9499 }
9500 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9501 // data member of const-qualified type (or array thereof) with no
9502 // brace-or-equal-initializer is not const-default-constructible.
9503 if (!inUnion() && FieldType.isConstQualified() &&
9504 !FD->hasInClassInitializer() &&
9505 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9506 if (Diagnose)
9507 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9508 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9509 return true;
9510 }
9511
9512 if (inUnion() && !FieldType.isConstQualified())
9513 AllFieldsAreConst = false;
9514 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9515 // For a copy constructor, data members must not be of rvalue reference
9516 // type.
9517 if (FieldType->isRValueReferenceType()) {
9518 if (Diagnose)
9519 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9520 << MD->getParent() << FD << FieldType;
9521 return true;
9522 }
9523 } else if (IsAssignment) {
9524 // For an assignment operator, data members must not be of reference type.
9525 if (FieldType->isReferenceType()) {
9526 if (Diagnose)
9527 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9528 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9529 return true;
9530 }
9531 if (!FieldRecord && FieldType.isConstQualified()) {
9532 // C++11 [class.copy]p23:
9533 // -- a non-static data member of const non-class type (or array thereof)
9534 if (Diagnose)
9535 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9536 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9537 return true;
9538 }
9539 }
9540
9541 if (FieldRecord) {
9542 // Some additional restrictions exist on the variant members.
9543 if (!inUnion() && FieldRecord->isUnion() &&
9544 FieldRecord->isAnonymousStructOrUnion()) {
9545 bool AllVariantFieldsAreConst = true;
9546
9547 // FIXME: Handle anonymous unions declared within anonymous unions.
9548 for (auto *UI : FieldRecord->fields()) {
9549 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9550
9551 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9552 return true;
9553
9554 if (!UnionFieldType.isConstQualified())
9555 AllVariantFieldsAreConst = false;
9556
9557 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9558 if (UnionFieldRecord &&
9559 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9560 UnionFieldType.getCVRQualifiers()))
9561 return true;
9562 }
9563
9564 // At least one member in each anonymous union must be non-const
9566 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9567 if (Diagnose)
9568 S.Diag(FieldRecord->getLocation(),
9569 diag::note_deleted_default_ctor_all_const)
9570 << !!ICI << MD->getParent() << /*anonymous union*/1;
9571 return true;
9572 }
9573
9574 // Don't check the implicit member of the anonymous union type.
9575 // This is technically non-conformant but supported, and we have a
9576 // diagnostic for this elsewhere.
9577 return false;
9578 }
9579
9580 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9581 FieldType.getCVRQualifiers()))
9582 return true;
9583 }
9584
9585 return false;
9586}
9587
9588/// C++11 [class.ctor] p5:
9589/// A defaulted default constructor for a class X is defined as deleted if
9590/// X is a union and all of its variant members are of const-qualified type.
9591bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9592 // This is a silly definition, because it gives an empty union a deleted
9593 // default constructor. Don't do that.
9594 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9595 AllFieldsAreConst) {
9596 bool AnyFields = false;
9597 for (auto *F : MD->getParent()->fields())
9598 if ((AnyFields = !F->isUnnamedBitField()))
9599 break;
9600 if (!AnyFields)
9601 return false;
9602 if (Diagnose)
9603 S.Diag(MD->getParent()->getLocation(),
9604 diag::note_deleted_default_ctor_all_const)
9605 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9606 return true;
9607 }
9608 return false;
9609}
9610
9611/// Determine whether a defaulted special member function should be defined as
9612/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9613/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9617 bool Diagnose) {
9618 if (MD->isInvalidDecl())
9619 return false;
9620 CXXRecordDecl *RD = MD->getParent();
9621 assert(!RD->isDependentType() && "do deletion after instantiation");
9622 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9623 RD->isInvalidDecl())
9624 return false;
9625
9626 // C++11 [expr.lambda.prim]p19:
9627 // The closure type associated with a lambda-expression has a
9628 // deleted (8.4.3) default constructor and a deleted copy
9629 // assignment operator.
9630 // C++2a adds back these operators if the lambda has no lambda-capture.
9634 if (Diagnose)
9635 Diag(RD->getLocation(), diag::note_lambda_decl);
9636 return true;
9637 }
9638
9639 // For an anonymous struct or union, the copy and assignment special members
9640 // will never be used, so skip the check. For an anonymous union declared at
9641 // namespace scope, the constructor and destructor are used.
9644 return false;
9645
9646 // C++11 [class.copy]p7, p18:
9647 // If the class definition declares a move constructor or move assignment
9648 // operator, an implicitly declared copy constructor or copy assignment
9649 // operator is defined as deleted.
9652 CXXMethodDecl *UserDeclaredMove = nullptr;
9653
9654 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9655 // deletion of the corresponding copy operation, not both copy operations.
9656 // MSVC 2015 has adopted the standards conforming behavior.
9657 bool DeletesOnlyMatchingCopy =
9658 getLangOpts().MSVCCompat &&
9660
9662 (!DeletesOnlyMatchingCopy ||
9664 if (!Diagnose) return true;
9665
9666 // Find any user-declared move constructor.
9667 for (auto *I : RD->ctors()) {
9668 if (I->isMoveConstructor()) {
9669 UserDeclaredMove = I;
9670 break;
9671 }
9672 }
9673 assert(UserDeclaredMove);
9674 } else if (RD->hasUserDeclaredMoveAssignment() &&
9675 (!DeletesOnlyMatchingCopy ||
9677 if (!Diagnose) return true;
9678
9679 // Find any user-declared move assignment operator.
9680 for (auto *I : RD->methods()) {
9681 if (I->isMoveAssignmentOperator()) {
9682 UserDeclaredMove = I;
9683 break;
9684 }
9685 }
9686 assert(UserDeclaredMove);
9687 }
9688
9689 if (UserDeclaredMove) {
9690 Diag(UserDeclaredMove->getLocation(),
9691 diag::note_deleted_copy_user_declared_move)
9692 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9693 << UserDeclaredMove->isMoveAssignmentOperator();
9694 return true;
9695 }
9696 }
9697
9698 // Do access control from the special member function
9699 ContextRAII MethodContext(*this, MD);
9700
9701 // C++11 [class.dtor]p5:
9702 // -- for a virtual destructor, lookup of the non-array deallocation function
9703 // results in an ambiguity or in a function that is deleted or inaccessible
9704 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9705 FunctionDecl *OperatorDelete = nullptr;
9706 DeclarationName Name =
9708 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9709 OperatorDelete, /*Diagnose*/false)) {
9710 if (Diagnose)
9711 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9712 return true;
9713 }
9714 }
9715
9716 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9717
9718 // Per DR1611, do not consider virtual bases of constructors of abstract
9719 // classes, since we are not going to construct them.
9720 // Per DR1658, do not consider virtual bases of destructors of abstract
9721 // classes either.
9722 // Per DR2180, for assignment operators we only assign (and thus only
9723 // consider) direct bases.
9724 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9725 : SMI.VisitPotentiallyConstructedBases))
9726 return true;
9727
9728 if (SMI.shouldDeleteForAllConstMembers())
9729 return true;
9730
9731 if (getLangOpts().CUDA) {
9732 // We should delete the special member in CUDA mode if target inference
9733 // failed.
9734 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9735 // is treated as certain special member, which may not reflect what special
9736 // member MD really is. However inferTargetForImplicitSpecialMember
9737 // expects CSM to match MD, therefore recalculate CSM.
9738 assert(ICI || CSM == getSpecialMember(MD));
9739 auto RealCSM = CSM;
9740 if (ICI)
9741 RealCSM = getSpecialMember(MD);
9742
9743 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9744 SMI.ConstArg, Diagnose);
9745 }
9746
9747 return false;
9748}
9749
9752 assert(DFK && "not a defaultable function");
9753 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9754
9755 if (DFK.isSpecialMember()) {
9756 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9757 nullptr, /*Diagnose=*/true);
9758 } else {
9759 DefaultedComparisonAnalyzer(
9760 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9761 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9762 .visit();
9763 }
9764}
9765
9766/// Perform lookup for a special member of the specified kind, and determine
9767/// whether it is trivial. If the triviality can be determined without the
9768/// lookup, skip it. This is intended for use when determining whether a
9769/// special member of a containing object is trivial, and thus does not ever
9770/// perform overload resolution for default constructors.
9771///
9772/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9773/// member that was most likely to be intended to be trivial, if any.
9774///
9775/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9776/// determine whether the special member is trivial.
9778 CXXSpecialMemberKind CSM, unsigned Quals,
9779 bool ConstRHS,
9781 CXXMethodDecl **Selected) {
9782 if (Selected)
9783 *Selected = nullptr;
9784
9785 switch (CSM) {
9787 llvm_unreachable("not a special member");
9788
9790 // C++11 [class.ctor]p5:
9791 // A default constructor is trivial if:
9792 // - all the [direct subobjects] have trivial default constructors
9793 //
9794 // Note, no overload resolution is performed in this case.
9796 return true;
9797
9798 if (Selected) {
9799 // If there's a default constructor which could have been trivial, dig it
9800 // out. Otherwise, if there's any user-provided default constructor, point
9801 // to that as an example of why there's not a trivial one.
9802 CXXConstructorDecl *DefCtor = nullptr;
9805 for (auto *CI : RD->ctors()) {
9806 if (!CI->isDefaultConstructor())
9807 continue;
9808 DefCtor = CI;
9809 if (!DefCtor->isUserProvided())
9810 break;
9811 }
9812
9813 *Selected = DefCtor;
9814 }
9815
9816 return false;
9817
9819 // C++11 [class.dtor]p5:
9820 // A destructor is trivial if:
9821 // - all the direct [subobjects] have trivial destructors
9822 if (RD->hasTrivialDestructor() ||
9825 return true;
9826
9827 if (Selected) {
9828 if (RD->needsImplicitDestructor())
9830 *Selected = RD->getDestructor();
9831 }
9832
9833 return false;
9834
9836 // C++11 [class.copy]p12:
9837 // A copy constructor is trivial if:
9838 // - the constructor selected to copy each direct [subobject] is trivial
9839 if (RD->hasTrivialCopyConstructor() ||
9842 if (Quals == Qualifiers::Const)
9843 // We must either select the trivial copy constructor or reach an
9844 // ambiguity; no need to actually perform overload resolution.
9845 return true;
9846 } else if (!Selected) {
9847 return false;
9848 }
9849 // In C++98, we are not supposed to perform overload resolution here, but we
9850 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9851 // cases like B as having a non-trivial copy constructor:
9852 // struct A { template<typename T> A(T&); };
9853 // struct B { mutable A a; };
9854 goto NeedOverloadResolution;
9855
9857 // C++11 [class.copy]p25:
9858 // A copy assignment operator is trivial if:
9859 // - the assignment operator selected to copy each direct [subobject] is
9860 // trivial
9861 if (RD->hasTrivialCopyAssignment()) {
9862 if (Quals == Qualifiers::Const)
9863 return true;
9864 } else if (!Selected) {
9865 return false;
9866 }
9867 // In C++98, we are not supposed to perform overload resolution here, but we
9868 // treat that as a language defect.
9869 goto NeedOverloadResolution;
9870
9873 NeedOverloadResolution:
9875 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9876
9877 // The standard doesn't describe how to behave if the lookup is ambiguous.
9878 // We treat it as not making the member non-trivial, just like the standard
9879 // mandates for the default constructor. This should rarely matter, because
9880 // the member will also be deleted.
9882 return true;
9883
9884 if (!SMOR.getMethod()) {
9885 assert(SMOR.getKind() ==
9887 return false;
9888 }
9889
9890 // We deliberately don't check if we found a deleted special member. We're
9891 // not supposed to!
9892 if (Selected)
9893 *Selected = SMOR.getMethod();
9894
9895 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9898 return SMOR.getMethod()->isTrivialForCall();
9899 return SMOR.getMethod()->isTrivial();
9900 }
9901
9902 llvm_unreachable("unknown special method kind");
9903}
9904
9906 for (auto *CI : RD->ctors())
9907 if (!CI->isImplicit())
9908 return CI;
9909
9910 // Look for constructor templates.
9912 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9913 if (CXXConstructorDecl *CD =
9914 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9915 return CD;
9916 }
9917
9918 return nullptr;
9919}
9920
9921/// The kind of subobject we are checking for triviality. The values of this
9922/// enumeration are used in diagnostics.
9924 /// The subobject is a base class.
9926 /// The subobject is a non-static data member.
9928 /// The object is actually the complete object.
9931
9932/// Check whether the special member selected for a given type would be trivial.
9934 QualType SubType, bool ConstRHS,
9938 bool Diagnose) {
9939 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9940 if (!SubRD)
9941 return true;
9942
9943 CXXMethodDecl *Selected;
9944 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9945 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9946 return true;
9947
9948 if (Diagnose) {
9949 if (ConstRHS)
9950 SubType.addConst();
9951
9952 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
9953 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9954 << Kind << SubType.getUnqualifiedType();
9956 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9957 } else if (!Selected)
9958 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9959 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
9960 << SubType;
9961 else if (Selected->isUserProvided()) {
9962 if (Kind == TSK_CompleteObject)
9963 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9964 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9965 else {
9966 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9967 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9968 S.Diag(Selected->getLocation(), diag::note_declared_at);
9969 }
9970 } else {
9971 if (Kind != TSK_CompleteObject)
9972 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9973 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9974
9975 // Explain why the defaulted or deleted special member isn't trivial.
9977 Diagnose);
9978 }
9979 }
9980
9981 return false;
9982}
9983
9984/// Check whether the members of a class type allow a special member to be
9985/// trivial.
9987 CXXSpecialMemberKind CSM, bool ConstArg,
9989 bool Diagnose) {
9990 for (const auto *FI : RD->fields()) {
9991 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
9992 continue;
9993
9994 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9995
9996 // Pretend anonymous struct or union members are members of this class.
9997 if (FI->isAnonymousStructOrUnion()) {
9998 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9999 CSM, ConstArg, TAH, Diagnose))
10000 return false;
10001 continue;
10002 }
10003
10004 // C++11 [class.ctor]p5:
10005 // A default constructor is trivial if [...]
10006 // -- no non-static data member of its class has a
10007 // brace-or-equal-initializer
10009 FI->hasInClassInitializer()) {
10010 if (Diagnose)
10011 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10012 << FI;
10013 return false;
10014 }
10015
10016 // Objective C ARC 4.3.5:
10017 // [...] nontrivally ownership-qualified types are [...] not trivially
10018 // default constructible, copy constructible, move constructible, copy
10019 // assignable, move assignable, or destructible [...]
10020 if (FieldType.hasNonTrivialObjCLifetime()) {
10021 if (Diagnose)
10022 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10023 << RD << FieldType.getObjCLifetime();
10024 return false;
10025 }
10026
10027 bool ConstRHS = ConstArg && !FI->isMutable();
10028 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10029 CSM, TSK_Field, TAH, Diagnose))
10030 return false;
10031 }
10032
10033 return true;
10034}
10035
10039
10040 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10042 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10044 /*Diagnose*/true);
10045}
10046
10048 TrivialABIHandling TAH, bool Diagnose) {
10049 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10050 "not special enough");
10051
10052 CXXRecordDecl *RD = MD->getParent();
10053
10054 bool ConstArg = false;
10055
10056 // C++11 [class.copy]p12, p25: [DR1593]
10057 // A [special member] is trivial if [...] its parameter-type-list is
10058 // equivalent to the parameter-type-list of an implicit declaration [...]
10059 switch (CSM) {
10062 // Trivial default constructors and destructors cannot have parameters.
10063 break;
10064
10067 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10068 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10069
10070 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10071 // if they are not user-provided and their parameter-type-list is equivalent
10072 // to the parameter-type-list of an implicit declaration. This maintains the
10073 // behavior before dr2171 was implemented.
10074 //
10075 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10076 // trivial, if they are not user-provided, regardless of the qualifiers on
10077 // the reference type.
10078 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10080 if (!RT ||
10082 ClangABICompat14)) {
10083 if (Diagnose)
10084 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10085 << Param0->getSourceRange() << Param0->getType()
10088 return false;
10089 }
10090
10091 ConstArg = RT->getPointeeType().isConstQualified();
10092 break;
10093 }
10094
10097 // Trivial move operations always have non-cv-qualified parameters.
10098 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10099 const RValueReferenceType *RT =
10100 Param0->getType()->getAs<RValueReferenceType>();
10101 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10102 if (Diagnose)
10103 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10104 << Param0->getSourceRange() << Param0->getType()
10106 return false;
10107 }
10108 break;
10109 }
10110
10112 llvm_unreachable("not a special member");
10113 }
10114
10115 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10116 if (Diagnose)
10118 diag::note_nontrivial_default_arg)
10120 return false;
10121 }
10122 if (MD->isVariadic()) {
10123 if (Diagnose)
10124 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10125 return false;
10126 }
10127
10128 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10129 // A copy/move [constructor or assignment operator] is trivial if
10130 // -- the [member] selected to copy/move each direct base class subobject
10131 // is trivial
10132 //
10133 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10134 // A [default constructor or destructor] is trivial if
10135 // -- all the direct base classes have trivial [default constructors or
10136 // destructors]
10137 for (const auto &BI : RD->bases())
10138 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10139 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10140 return false;
10141
10142 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10143 // A copy/move [constructor or assignment operator] for a class X is
10144 // trivial if
10145 // -- for each non-static data member of X that is of class type (or array
10146 // thereof), the constructor selected to copy/move that member is
10147 // trivial
10148 //
10149 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10150 // A [default constructor or destructor] is trivial if
10151 // -- for all of the non-static data members of its class that are of class
10152 // type (or array thereof), each such class has a trivial [default
10153 // constructor or destructor]
10154 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10155 return false;
10156
10157 // C++11 [class.dtor]p5:
10158 // A destructor is trivial if [...]
10159 // -- the destructor is not virtual
10160 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10161 if (Diagnose)
10162 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10163 return false;
10164 }
10165
10166 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10167 // A [special member] for class X is trivial if [...]
10168 // -- class X has no virtual functions and no virtual base classes
10170 MD->getParent()->isDynamicClass()) {
10171 if (!Diagnose)
10172 return false;
10173
10174 if (RD->getNumVBases()) {
10175 // Check for virtual bases. We already know that the corresponding
10176 // member in all bases is trivial, so vbases must all be direct.
10177 CXXBaseSpecifier &BS = *RD->vbases_begin();
10178 assert(BS.isVirtual());
10179 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10180 return false;
10181 }
10182
10183 // Must have a virtual method.
10184 for (const auto *MI : RD->methods()) {
10185 if (MI->isVirtual()) {
10186 SourceLocation MLoc = MI->getBeginLoc();
10187 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10188 return false;
10189 }
10190 }
10191
10192 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10193 }
10194
10195 // Looks like it's trivial!
10196 return true;
10197}
10198
10199namespace {
10200struct FindHiddenVirtualMethod {
10201 Sema *S;
10202 CXXMethodDecl *Method;
10203 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10204 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10205
10206private:
10207 /// Check whether any most overridden method from MD in Methods
10208 static bool CheckMostOverridenMethods(
10209 const CXXMethodDecl *MD,
10210 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10211 if (MD->size_overridden_methods() == 0)
10212 return Methods.count(MD->getCanonicalDecl());
10213 for (const CXXMethodDecl *O : MD->overridden_methods())
10214 if (CheckMostOverridenMethods(O, Methods))
10215 return true;
10216 return false;
10217 }
10218
10219public:
10220 /// Member lookup function that determines whether a given C++
10221 /// method overloads virtual methods in a base class without overriding any,
10222 /// to be used with CXXRecordDecl::lookupInBases().
10223 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10224 RecordDecl *BaseRecord =
10225 Specifier->getType()->castAs<RecordType>()->getDecl();
10226
10227 DeclarationName Name = Method->getDeclName();
10228 assert(Name.getNameKind() == DeclarationName::Identifier);
10229
10230 bool foundSameNameMethod = false;
10231 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10232 for (Path.Decls = BaseRecord->lookup(Name).begin();
10233 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10234 NamedDecl *D = *Path.Decls;
10235 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10236 MD = MD->getCanonicalDecl();
10237 foundSameNameMethod = true;
10238 // Interested only in hidden virtual methods.
10239 if (!MD->isVirtual())
10240 continue;
10241 // If the method we are checking overrides a method from its base
10242 // don't warn about the other overloaded methods. Clang deviates from
10243 // GCC by only diagnosing overloads of inherited virtual functions that
10244 // do not override any other virtual functions in the base. GCC's
10245 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10246 // function from a base class. These cases may be better served by a
10247 // warning (not specific to virtual functions) on call sites when the
10248 // call would select a different function from the base class, were it
10249 // visible.
10250 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10251 if (!S->IsOverload(Method, MD, false))
10252 return true;
10253 // Collect the overload only if its hidden.
10254 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10255 overloadedMethods.push_back(MD);
10256 }
10257 }
10258
10259 if (foundSameNameMethod)
10260 OverloadedMethods.append(overloadedMethods.begin(),
10261 overloadedMethods.end());
10262 return foundSameNameMethod;
10263 }
10264};
10265} // end anonymous namespace
10266
10267/// Add the most overridden methods from MD to Methods
10269 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10270 if (MD->size_overridden_methods() == 0)
10271 Methods.insert(MD->getCanonicalDecl());
10272 else
10273 for (const CXXMethodDecl *O : MD->overridden_methods())
10274 AddMostOverridenMethods(O, Methods);
10275}
10276
10278 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10279 if (!MD->getDeclName().isIdentifier())
10280 return;
10281
10282 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10283 /*bool RecordPaths=*/false,
10284 /*bool DetectVirtual=*/false);
10285 FindHiddenVirtualMethod FHVM;
10286 FHVM.Method = MD;
10287 FHVM.S = this;
10288
10289 // Keep the base methods that were overridden or introduced in the subclass
10290 // by 'using' in a set. A base method not in this set is hidden.
10291 CXXRecordDecl *DC = MD->getParent();
10293 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10294 NamedDecl *ND = *I;
10295 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10296 ND = shad->getTargetDecl();
10297 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10298 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10299 }
10300
10301 if (DC->lookupInBases(FHVM, Paths))
10302 OverloadedMethods = FHVM.OverloadedMethods;
10303}
10304
10306 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10307 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10308 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10310 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10311 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10312 Diag(overloadedMD->getLocation(), PD);
10313 }
10314}
10315
10317 if (MD->isInvalidDecl())
10318 return;
10319
10320 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10321 return;
10322
10323 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10324 FindHiddenVirtualMethods(MD, OverloadedMethods);
10325 if (!OverloadedMethods.empty()) {
10326 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10327 << MD << (OverloadedMethods.size() > 1);
10328
10329 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10330 }
10331}
10332
10334 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10335 // No diagnostics if this is a template instantiation.
10337 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10338 diag::ext_cannot_use_trivial_abi) << &RD;
10339 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10340 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10341 }
10342 RD.dropAttr<TrivialABIAttr>();
10343 };
10344
10345 // Ill-formed if the copy and move constructors are deleted.
10346 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10347 // If the type is dependent, then assume it might have
10348 // implicit copy or move ctor because we won't know yet at this point.
10349 if (RD.isDependentType())
10350 return true;
10353 return true;
10356 return true;
10357 for (const CXXConstructorDecl *CD : RD.ctors())
10358 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10359 return true;
10360 return false;
10361 };
10362
10363 if (!HasNonDeletedCopyOrMoveConstructor()) {
10364 PrintDiagAndRemoveAttr(0);
10365 return;
10366 }
10367
10368 // Ill-formed if the struct has virtual functions.
10369 if (RD.isPolymorphic()) {
10370 PrintDiagAndRemoveAttr(1);
10371 return;
10372 }
10373
10374 for (const auto &B : RD.bases()) {
10375 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10376 // virtual base.
10377 if (!B.getType()->isDependentType() &&
10378 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10379 PrintDiagAndRemoveAttr(2);
10380 return;
10381 }
10382
10383 if (B.isVirtual()) {
10384 PrintDiagAndRemoveAttr(3);
10385 return;
10386 }
10387 }
10388
10389 for (const auto *FD : RD.fields()) {
10390 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10391 // non-trivial for the purpose of calls.
10392 QualType FT = FD->getType();
10394 PrintDiagAndRemoveAttr(4);
10395 return;
10396 }
10397
10398 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10399 if (!RT->isDependentType() &&
10400 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10401 PrintDiagAndRemoveAttr(5);
10402 return;
10403 }
10404 }
10405}
10406
10408 CXXRecordDecl &RD) {
10410 diag::err_incomplete_type_vtable_pointer_auth))
10411 return;
10412
10413 const CXXRecordDecl *PrimaryBase = &RD;
10414 if (PrimaryBase->hasAnyDependentBases())
10415 return;
10416
10417 while (1) {
10418 assert(PrimaryBase);
10419 const CXXRecordDecl *Base = nullptr;
10420 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10421 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10422 continue;
10423 Base = BasePtr.getType()->getAsCXXRecordDecl();
10424 break;
10425 }
10426 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10427 break;
10428 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10429 diag::err_non_top_level_vtable_pointer_auth)
10430 << &RD << Base;
10431 PrimaryBase = Base;
10432 }
10433
10434 if (!RD.isPolymorphic())
10435 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10436 diag::err_non_polymorphic_vtable_pointer_auth)
10437 << &RD;
10438}
10439
10442 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10443 if (!TagDecl)
10444 return;
10445
10447
10448 for (const ParsedAttr &AL : AttrList) {
10449 if (AL.getKind() != ParsedAttr::AT_Visibility)
10450 continue;
10451 AL.setInvalid();
10452 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10453 }
10454
10455 ActOnFields(S, RLoc, TagDecl,
10457 // strict aliasing violation!
10458 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10459 FieldCollector->getCurNumFields()),
10460 LBrac, RBrac, AttrList);
10461
10462 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10463}
10464
10465/// Find the equality comparison functions that should be implicitly declared
10466/// in a given class definition, per C++2a [class.compare.default]p3.
10468 ASTContext &Ctx, CXXRecordDecl *RD,
10470 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10471 if (!RD->lookup(EqEq).empty())
10472 // Member operator== explicitly declared: no implicit operator==s.
10473 return;
10474
10475 // Traverse friends looking for an '==' or a '<=>'.
10476 for (FriendDecl *Friend : RD->friends()) {
10477 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10478 if (!FD) continue;
10479
10480 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10481 // Friend operator== explicitly declared: no implicit operator==s.
10482 Spaceships.clear();
10483 return;
10484 }
10485
10486 if (FD->getOverloadedOperator() == OO_Spaceship &&
10488 Spaceships.push_back(FD);
10489 }
10490
10491 // Look for members named 'operator<=>'.
10492 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10493 for (NamedDecl *ND : RD->lookup(Cmp)) {
10494 // Note that we could find a non-function here (either a function template
10495 // or a using-declaration). Neither case results in an implicit
10496 // 'operator=='.
10497 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10498 if (FD->isExplicitlyDefaulted())
10499 Spaceships.push_back(FD);
10500 }
10501}
10502
10504 // Don't add implicit special members to templated classes.
10505 // FIXME: This means unqualified lookups for 'operator=' within a class
10506 // template don't work properly.
10507 if (!ClassDecl->isDependentType()) {
10508 if (ClassDecl->needsImplicitDefaultConstructor()) {
10510
10511 if (ClassDecl->hasInheritedConstructor())
10513 }
10514
10515 if (ClassDecl->needsImplicitCopyConstructor()) {
10517
10518 // If the properties or semantics of the copy constructor couldn't be
10519 // determined while the class was being declared, force a declaration
10520 // of it now.
10522 ClassDecl->hasInheritedConstructor())
10524 // For the MS ABI we need to know whether the copy ctor is deleted. A
10525 // prerequisite for deleting the implicit copy ctor is that the class has
10526 // a move ctor or move assignment that is either user-declared or whose
10527 // semantics are inherited from a subobject. FIXME: We should provide a
10528 // more direct way for CodeGen to ask whether the constructor was deleted.
10529 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10530 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10532 ClassDecl->hasUserDeclaredMoveAssignment() ||
10535 }
10536
10537 if (getLangOpts().CPlusPlus11 &&
10538 ClassDecl->needsImplicitMoveConstructor()) {
10540
10542 ClassDecl->hasInheritedConstructor())
10544 }
10545
10546 if (ClassDecl->needsImplicitCopyAssignment()) {
10548
10549 // If we have a dynamic class, then the copy assignment operator may be
10550 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10551 // it shows up in the right place in the vtable and that we diagnose
10552 // problems with the implicit exception specification.
10553 if (ClassDecl->isDynamicClass() ||
10555 ClassDecl->hasInheritedAssignment())
10557 }
10558
10559 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10561
10562 // Likewise for the move assignment operator.
10563 if (ClassDecl->isDynamicClass() ||
10565 ClassDecl->hasInheritedAssignment())
10567 }
10568
10569 if (ClassDecl->needsImplicitDestructor()) {
10571
10572 // If we have a dynamic class, then the destructor may be virtual, so we
10573 // have to declare the destructor immediately. This ensures that, e.g., it
10574 // shows up in the right place in the vtable and that we diagnose problems
10575 // with the implicit exception specification.
10576 if (ClassDecl->isDynamicClass() ||
10578 DeclareImplicitDestructor(ClassDecl);
10579 }
10580 }
10581
10582 // C++2a [class.compare.default]p3:
10583 // If the member-specification does not explicitly declare any member or
10584 // friend named operator==, an == operator function is declared implicitly
10585 // for each defaulted three-way comparison operator function defined in
10586 // the member-specification
10587 // FIXME: Consider doing this lazily.
10588 // We do this during the initial parse for a class template, not during
10589 // instantiation, so that we can handle unqualified lookups for 'operator=='
10590 // when parsing the template.
10592 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10594 DefaultedSpaceships);
10595 for (auto *FD : DefaultedSpaceships)
10596 DeclareImplicitEqualityComparison(ClassDecl, FD);
10597 }
10598}
10599
10600unsigned
10602 llvm::function_ref<Scope *()> EnterScope) {
10603 if (!D)
10604 return 0;
10606
10607 // In order to get name lookup right, reenter template scopes in order from
10608 // outermost to innermost.
10610 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10611
10612 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10613 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10614 ParameterLists.push_back(DD->getTemplateParameterList(i));
10615
10616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10617 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10618 ParameterLists.push_back(FTD->getTemplateParameters());
10619 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10620 LookupDC = VD->getDeclContext();
10621
10623 ParameterLists.push_back(VTD->getTemplateParameters());
10624 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10625 ParameterLists.push_back(PSD->getTemplateParameters());
10626 }
10627 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10628 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10629 ParameterLists.push_back(TD->getTemplateParameterList(i));
10630
10631 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10633 ParameterLists.push_back(CTD->getTemplateParameters());
10634 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10635 ParameterLists.push_back(PSD->getTemplateParameters());
10636 }
10637 }
10638 // FIXME: Alias declarations and concepts.
10639
10640 unsigned Count = 0;
10641 Scope *InnermostTemplateScope = nullptr;
10642 for (TemplateParameterList *Params : ParameterLists) {
10643 // Ignore explicit specializations; they don't contribute to the template
10644 // depth.
10645 if (Params->size() == 0)
10646 continue;
10647
10648 InnermostTemplateScope = EnterScope();
10649 for (NamedDecl *Param : *Params) {
10650 if (Param->getDeclName()) {
10651 InnermostTemplateScope->AddDecl(Param);
10652 IdResolver.AddDecl(Param);
10653 }
10654 }
10655 ++Count;
10656 }
10657
10658 // Associate the new template scopes with the corresponding entities.
10659 if (InnermostTemplateScope) {
10660 assert(LookupDC && "no enclosing DeclContext for template lookup");
10661 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10662 }
10663
10664 return Count;
10665}
10666
10668 if (!RecordD) return;
10669 AdjustDeclIfTemplate(RecordD);
10670 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10672}
10673
10675 if (!RecordD) return;
10677}
10678
10680 if (!Param)
10681 return;
10682
10683 S->AddDecl(Param);
10684 if (Param->getDeclName())
10685 IdResolver.AddDecl(Param);
10686}
10687
10689}
10690
10691/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10692/// C++ method declaration. We're (re-)introducing the given
10693/// function parameter into scope for use in parsing later parts of
10694/// the method declaration. For example, we could see an
10695/// ActOnParamDefaultArgument event for this parameter.
10697 if (!ParamD)
10698 return;
10699
10700 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10701
10702 S->AddDecl(Param);
10703 if (Param->getDeclName())
10704 IdResolver.AddDecl(Param);
10705}
10706
10708 if (!MethodD)
10709 return;
10710
10711 AdjustDeclIfTemplate(MethodD);
10712
10713 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10714
10715 // Now that we have our default arguments, check the constructor
10716 // again. It could produce additional diagnostics or affect whether
10717 // the class has implicitly-declared destructors, among other
10718 // things.
10719 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10720 CheckConstructor(Constructor);
10721
10722 // Check the default arguments, which we may have added.
10723 if (!Method->isInvalidDecl())
10725}
10726
10727// Emit the given diagnostic for each non-address-space qualifier.
10728// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10729static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10730 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10731 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10732 bool DiagOccured = false;
10734 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10735 SourceLocation SL) {
10736 // This diagnostic should be emitted on any qualifier except an addr
10737 // space qualifier. However, forEachQualifier currently doesn't visit
10738 // addr space qualifiers, so there's no way to write this condition
10739 // right now; we just diagnose on everything.
10740 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10741 DiagOccured = true;
10742 });
10743 if (DiagOccured)
10744 D.setInvalidType();
10745 }
10746}
10747
10749 StorageClass &SC) {
10750 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10751
10752 // C++ [class.ctor]p3:
10753 // A constructor shall not be virtual (10.3) or static (9.4). A
10754 // constructor can be invoked for a const, volatile or const
10755 // volatile object. A constructor shall not be declared const,
10756 // volatile, or const volatile (9.3.2).
10757 if (isVirtual) {
10758 if (!D.isInvalidType())
10759 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10760 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10761 << SourceRange(D.getIdentifierLoc());
10762 D.setInvalidType();
10763 }
10764 if (SC == SC_Static) {
10765 if (!D.isInvalidType())
10766 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10767 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10768 << SourceRange(D.getIdentifierLoc());
10769 D.setInvalidType();
10770 SC = SC_None;
10771 }
10772
10773 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10775 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10776 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10777 D.getDeclSpec().getRestrictSpecLoc(),
10778 D.getDeclSpec().getAtomicSpecLoc());
10779 D.setInvalidType();
10780 }
10781
10782 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10783
10784 // C++0x [class.ctor]p4:
10785 // A constructor shall not be declared with a ref-qualifier.
10786 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10787 if (FTI.hasRefQualifier()) {
10788 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10791 D.setInvalidType();
10792 }
10793
10794 // Rebuild the function type "R" without any type qualifiers (in
10795 // case any of the errors above fired) and with "void" as the
10796 // return type, since constructors don't have return types.
10797 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10798 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10799 return R;
10800
10802 EPI.TypeQuals = Qualifiers();
10803 EPI.RefQualifier = RQ_None;
10804
10805 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10806}
10807
10809 CXXRecordDecl *ClassDecl
10810 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10811 if (!ClassDecl)
10812 return Constructor->setInvalidDecl();
10813
10814 // C++ [class.copy]p3:
10815 // A declaration of a constructor for a class X is ill-formed if
10816 // its first parameter is of type (optionally cv-qualified) X and
10817 // either there are no other parameters or else all other
10818 // parameters have default arguments.
10819 if (!Constructor->isInvalidDecl() &&
10820 Constructor->hasOneParamOrDefaultArgs() &&
10821 Constructor->getTemplateSpecializationKind() !=
10823 QualType ParamType = Constructor->getParamDecl(0)->getType();
10824 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10825 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10826 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10827 const char *ConstRef
10828 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10829 : " const &";
10830 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10831 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10832
10833 // FIXME: Rather that making the constructor invalid, we should endeavor
10834 // to fix the type.
10835 Constructor->setInvalidDecl();
10836 }
10837 }
10838}
10839
10841 CXXRecordDecl *RD = Destructor->getParent();
10842
10843 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10845
10846 if (!Destructor->isImplicit())
10847 Loc = Destructor->getLocation();
10848 else
10849 Loc = RD->getLocation();
10850
10851 // If we have a virtual destructor, look up the deallocation function
10852 if (FunctionDecl *OperatorDelete =
10854 Expr *ThisArg = nullptr;
10855
10856 // If the notional 'delete this' expression requires a non-trivial
10857 // conversion from 'this' to the type of a destroying operator delete's
10858 // first parameter, perform that conversion now.
10859 if (OperatorDelete->isDestroyingOperatorDelete()) {
10860 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10861 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10862 // C++ [class.dtor]p13:
10863 // ... as if for the expression 'delete this' appearing in a
10864 // non-virtual destructor of the destructor's class.
10865 ContextRAII SwitchContext(*this, Destructor);
10866 ExprResult This =
10867 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10868 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10869 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10870 if (This.isInvalid()) {
10871 // FIXME: Register this as a context note so that it comes out
10872 // in the right order.
10873 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10874 return true;
10875 }
10876 ThisArg = This.get();
10877 }
10878 }
10879
10880 DiagnoseUseOfDecl(OperatorDelete, Loc);
10881 MarkFunctionReferenced(Loc, OperatorDelete);
10882 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10883 }
10884 }
10885
10886 return false;
10887}
10888
10890 StorageClass& SC) {
10891 // C++ [class.dtor]p1:
10892 // [...] A typedef-name that names a class is a class-name
10893 // (7.1.3); however, a typedef-name that names a class shall not
10894 // be used as the identifier in the declarator for a destructor
10895 // declaration.
10896 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10897 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10898 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10899 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10900 else if (const TemplateSpecializationType *TST =
10901 DeclaratorType->getAs<TemplateSpecializationType>())
10902 if (TST->isTypeAlias())
10903 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10904 << DeclaratorType << 1;
10905
10906 // C++ [class.dtor]p2:
10907 // A destructor is used to destroy objects of its class type. A
10908 // destructor takes no parameters, and no return type can be
10909 // specified for it (not even void). The address of a destructor
10910 // shall not be taken. A destructor shall not be static. A
10911 // destructor can be invoked for a const, volatile or const
10912 // volatile object. A destructor shall not be declared const,
10913 // volatile or const volatile (9.3.2).
10914 if (SC == SC_Static) {
10915 if (!D.isInvalidType())
10916 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10917 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10918 << SourceRange(D.getIdentifierLoc())
10919 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10920
10921 SC = SC_None;
10922 }
10923 if (!D.isInvalidType()) {
10924 // Destructors don't have return types, but the parser will
10925 // happily parse something like:
10926 //
10927 // class X {
10928 // float ~X();
10929 // };
10930 //
10931 // The return type will be eliminated later.
10932 if (D.getDeclSpec().hasTypeSpecifier())
10933 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10934 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10935 << SourceRange(D.getIdentifierLoc());
10936 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10937 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10939 D.getDeclSpec().getConstSpecLoc(),
10940 D.getDeclSpec().getVolatileSpecLoc(),
10941 D.getDeclSpec().getRestrictSpecLoc(),
10942 D.getDeclSpec().getAtomicSpecLoc());
10943 D.setInvalidType();
10944 }
10945 }
10946
10947 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10948
10949 // C++0x [class.dtor]p2:
10950 // A destructor shall not be declared with a ref-qualifier.
10951 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10952 if (FTI.hasRefQualifier()) {
10953 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10956 D.setInvalidType();
10957 }
10958
10959 // Make sure we don't have any parameters.
10960 if (FTIHasNonVoidParameters(FTI)) {
10961 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10962
10963 // Delete the parameters.
10964 FTI.freeParams();
10965 D.setInvalidType();
10966 }
10967
10968 // Make sure the destructor isn't variadic.
10969 if (FTI.isVariadic) {
10970 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10971 D.setInvalidType();
10972 }
10973
10974 // Rebuild the function type "R" without any type qualifiers or
10975 // parameters (in case any of the errors above fired) and with
10976 // "void" as the return type, since destructors don't have return
10977 // types.
10978 if (!D.isInvalidType())
10979 return R;
10980
10981 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10983 EPI.Variadic = false;
10984 EPI.TypeQuals = Qualifiers();
10985 EPI.RefQualifier = RQ_None;
10986 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10987}
10988
10989static void extendLeft(SourceRange &R, SourceRange Before) {
10990 if (Before.isInvalid())
10991 return;
10992 R.setBegin(Before.getBegin());
10993 if (R.getEnd().isInvalid())
10994 R.setEnd(Before.getEnd());
10995}
10996
10997static void extendRight(SourceRange &R, SourceRange After) {
10998 if (After.isInvalid())
10999 return;
11000 if (R.getBegin().isInvalid())
11001 R.setBegin(After.getBegin());
11002 R.setEnd(After.getEnd());
11003}
11004
11006 StorageClass& SC) {
11007 // C++ [class.conv.fct]p1:
11008 // Neither parameter types nor return type can be specified. The
11009 // type of a conversion function (8.3.5) is "function taking no
11010 // parameter returning conversion-type-id."
11011 if (SC == SC_Static) {
11012 if (!D.isInvalidType())
11013 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11014 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11015 << D.getName().getSourceRange();
11016 D.setInvalidType();
11017 SC = SC_None;
11018 }
11019
11020 TypeSourceInfo *ConvTSI = nullptr;
11021 QualType ConvType =
11022 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11023
11024 const DeclSpec &DS = D.getDeclSpec();
11025 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11026 // Conversion functions don't have return types, but the parser will
11027 // happily parse something like:
11028 //
11029 // class X {
11030 // float operator bool();
11031 // };
11032 //
11033 // The return type will be changed later anyway.
11034 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11036 << SourceRange(D.getIdentifierLoc());
11037 D.setInvalidType();
11038 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11039 // It's also plausible that the user writes type qualifiers in the wrong
11040 // place, such as:
11041 // struct S { const operator int(); };
11042 // FIXME: we could provide a fixit to move the qualifiers onto the
11043 // conversion type.
11044 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11045 << SourceRange(D.getIdentifierLoc()) << 0;
11046 D.setInvalidType();
11047 }
11048 const auto *Proto = R->castAs<FunctionProtoType>();
11049 // Make sure we don't have any parameters.
11050 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11051 unsigned NumParam = Proto->getNumParams();
11052
11053 // [C++2b]
11054 // A conversion function shall have no non-object parameters.
11055 if (NumParam == 1) {
11056 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11057 if (const auto *First =
11058 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11059 First && First->isExplicitObjectParameter())
11060 NumParam--;
11061 }
11062
11063 if (NumParam != 0) {
11064 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11065 // Delete the parameters.
11066 FTI.freeParams();
11067 D.setInvalidType();
11068 } else if (Proto->isVariadic()) {
11069 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11070 D.setInvalidType();
11071 }
11072
11073 // Diagnose "&operator bool()" and other such nonsense. This
11074 // is actually a gcc extension which we don't support.
11075 if (Proto->getReturnType() != ConvType) {
11076 bool NeedsTypedef = false;
11077 SourceRange Before, After;
11078
11079 // Walk the chunks and extract information on them for our diagnostic.
11080 bool PastFunctionChunk = false;
11081 for (auto &Chunk : D.type_objects()) {
11082 switch (Chunk.Kind) {
11084 if (!PastFunctionChunk) {
11085 if (Chunk.Fun.HasTrailingReturnType) {
11086 TypeSourceInfo *TRT = nullptr;
11087 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11088 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11089 }
11090 PastFunctionChunk = true;
11091 break;
11092 }
11093 [[fallthrough]];
11095 NeedsTypedef = true;
11096 extendRight(After, Chunk.getSourceRange());
11097 break;
11098
11104 extendLeft(Before, Chunk.getSourceRange());
11105 break;
11106
11108 extendLeft(Before, Chunk.Loc);
11109 extendRight(After, Chunk.EndLoc);
11110 break;
11111 }
11112 }
11113
11114 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11115 After.isValid() ? After.getBegin() :
11116 D.getIdentifierLoc();
11117 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11118 DB << Before << After;
11119
11120 if (!NeedsTypedef) {
11121 DB << /*don't need a typedef*/0;
11122
11123 // If we can provide a correct fix-it hint, do so.
11124 if (After.isInvalid() && ConvTSI) {
11125 SourceLocation InsertLoc =
11127 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11129 InsertLoc, CharSourceRange::getTokenRange(Before))
11130 << FixItHint::CreateRemoval(Before);
11131 }
11132 } else if (!Proto->getReturnType()->isDependentType()) {
11133 DB << /*typedef*/1 << Proto->getReturnType();
11134 } else if (getLangOpts().CPlusPlus11) {
11135 DB << /*alias template*/2 << Proto->getReturnType();
11136 } else {
11137 DB << /*might not be fixable*/3;
11138 }
11139
11140 // Recover by incorporating the other type chunks into the result type.
11141 // Note, this does *not* change the name of the function. This is compatible
11142 // with the GCC extension:
11143 // struct S { &operator int(); } s;
11144 // int &r = s.operator int(); // ok in GCC
11145 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11146 ConvType = Proto->getReturnType();
11147 }
11148
11149 // C++ [class.conv.fct]p4:
11150 // The conversion-type-id shall not represent a function type nor
11151 // an array type.
11152 if (ConvType->isArrayType()) {
11153 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11154 ConvType = Context.getPointerType(ConvType);
11155 D.setInvalidType();
11156 } else if (ConvType->isFunctionType()) {
11157 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11158 ConvType = Context.getPointerType(ConvType);
11159 D.setInvalidType();
11160 }
11161
11162 // Rebuild the function type "R" without any parameters (in case any
11163 // of the errors above fired) and with the conversion type as the
11164 // return type.
11165 if (D.isInvalidType())
11166 R = Context.getFunctionType(ConvType, std::nullopt,
11167 Proto->getExtProtoInfo());
11168
11169 // C++0x explicit conversion operators.
11173 ? diag::warn_cxx98_compat_explicit_conversion_functions
11174 : diag::ext_explicit_conversion_functions)
11176}
11177
11179 assert(Conversion && "Expected to receive a conversion function declaration");
11180
11181 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11182
11183 // Make sure we aren't redeclaring the conversion function.
11184 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11185 // C++ [class.conv.fct]p1:
11186 // [...] A conversion function is never used to convert a
11187 // (possibly cv-qualified) object to the (possibly cv-qualified)
11188 // same object type (or a reference to it), to a (possibly
11189 // cv-qualified) base class of that type (or a reference to it),
11190 // or to (possibly cv-qualified) void.
11191 QualType ClassType
11193 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11194 ConvType = ConvTypeRef->getPointeeType();
11195 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11197 /* Suppress diagnostics for instantiations. */;
11198 else if (Conversion->size_overridden_methods() != 0)
11199 /* Suppress diagnostics for overriding virtual function in a base class. */;
11200 else if (ConvType->isRecordType()) {
11201 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11202 if (ConvType == ClassType)
11203 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11204 << ClassType;
11205 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11206 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11207 << ClassType << ConvType;
11208 } else if (ConvType->isVoidType()) {
11209 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11210 << ClassType << ConvType;
11211 }
11212
11213 if (FunctionTemplateDecl *ConversionTemplate =
11214 Conversion->getDescribedFunctionTemplate()) {
11215 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11216 ConvType = ConvTypePtr->getPointeeType();
11217 }
11218 if (ConvType->isUndeducedAutoType()) {
11219 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11220 << getReturnTypeLoc(Conversion).getSourceRange()
11221 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11222 << /* in declaration of conversion function template= */ 24;
11223 }
11224
11225 return ConversionTemplate;
11226 }
11227
11228 return Conversion;
11229}
11230
11232 DeclarationName Name, QualType R) {
11233 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11234}
11235
11237 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11238}
11239
11241 DeclarationName Name, QualType R,
11242 bool IsLambda, DeclContext *DC) {
11243 if (!D.isFunctionDeclarator())
11244 return;
11245
11246 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11247 if (FTI.NumParams == 0)
11248 return;
11249 ParmVarDecl *ExplicitObjectParam = nullptr;
11250 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11251 const auto &ParamInfo = FTI.Params[Idx];
11252 if (!ParamInfo.Param)
11253 continue;
11254 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11255 if (!Param->isExplicitObjectParameter())
11256 continue;
11257 if (Idx == 0) {
11258 ExplicitObjectParam = Param;
11259 continue;
11260 } else {
11261 Diag(Param->getLocation(),
11262 diag::err_explicit_object_parameter_must_be_first)
11263 << IsLambda << Param->getSourceRange();
11264 }
11265 }
11266 if (!ExplicitObjectParam)
11267 return;
11268
11269 if (ExplicitObjectParam->hasDefaultArg()) {
11270 Diag(ExplicitObjectParam->getLocation(),
11271 diag::err_explicit_object_default_arg)
11272 << ExplicitObjectParam->getSourceRange();
11273 }
11274
11275 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11276 (D.getContext() == clang::DeclaratorContext::Member &&
11277 D.isStaticMember())) {
11278 Diag(ExplicitObjectParam->getBeginLoc(),
11279 diag::err_explicit_object_parameter_nonmember)
11280 << D.getSourceRange() << /*static=*/0 << IsLambda;
11281 D.setInvalidType();
11282 }
11283
11284 if (D.getDeclSpec().isVirtualSpecified()) {
11285 Diag(ExplicitObjectParam->getBeginLoc(),
11286 diag::err_explicit_object_parameter_nonmember)
11287 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11288 D.setInvalidType();
11289 }
11290
11291 // Friend declarations require some care. Consider:
11292 //
11293 // namespace N {
11294 // struct A{};
11295 // int f(A);
11296 // }
11297 //
11298 // struct S {
11299 // struct T {
11300 // int f(this T);
11301 // };
11302 //
11303 // friend int T::f(this T); // Allow this.
11304 // friend int f(this S); // But disallow this.
11305 // friend int N::f(this A); // And disallow this.
11306 // };
11307 //
11308 // Here, it seems to suffice to check whether the scope
11309 // specifier designates a class type.
11310 if (D.getDeclSpec().isFriendSpecified() &&
11311 !isa_and_present<CXXRecordDecl>(
11312 computeDeclContext(D.getCXXScopeSpec()))) {
11313 Diag(ExplicitObjectParam->getBeginLoc(),
11314 diag::err_explicit_object_parameter_nonmember)
11315 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11316 D.setInvalidType();
11317 }
11318
11319 if (IsLambda && FTI.hasMutableQualifier()) {
11320 Diag(ExplicitObjectParam->getBeginLoc(),
11321 diag::err_explicit_object_parameter_mutable)
11322 << D.getSourceRange();
11323 }
11324
11325 if (IsLambda)
11326 return;
11327
11328 if (!DC || !DC->isRecord()) {
11329 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11330 "should have been diagnosed already");
11331 return;
11332 }
11333
11334 // CWG2674: constructors and destructors cannot have explicit parameters.
11335 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11336 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11337 Diag(ExplicitObjectParam->getBeginLoc(),
11338 diag::err_explicit_object_parameter_constructor)
11339 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11340 << D.getSourceRange();
11341 D.setInvalidType();
11342 }
11343}
11344
11345namespace {
11346/// Utility class to accumulate and print a diagnostic listing the invalid
11347/// specifier(s) on a declaration.
11348struct BadSpecifierDiagnoser {
11349 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11350 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11351 ~BadSpecifierDiagnoser() {
11352 Diagnostic << Specifiers;
11353 }
11354
11355 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11356 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11357 }
11358 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11359 return check(SpecLoc,
11361 }
11362 void check(SourceLocation SpecLoc, const char *Spec) {
11363 if (SpecLoc.isInvalid()) return;
11364 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11365 if (!Specifiers.empty()) Specifiers += " ";
11366 Specifiers += Spec;
11367 }
11368
11369 Sema &S;
11371 std::string Specifiers;
11372};
11373}
11374
11376 StorageClass &SC) {
11377 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11378 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11379 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11380
11381 // C++ [temp.deduct.guide]p3:
11382 // A deduction-gide shall be declared in the same scope as the
11383 // corresponding class template.
11385 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11386 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11387 << GuidedTemplateDecl;
11388 NoteTemplateLocation(*GuidedTemplateDecl);
11389 }
11390
11391 auto &DS = D.getMutableDeclSpec();
11392 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11393 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11394 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11395 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11396 BadSpecifierDiagnoser Diagnoser(
11397 *this, D.getIdentifierLoc(),
11398 diag::err_deduction_guide_invalid_specifier);
11399
11400 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11401 DS.ClearStorageClassSpecs();
11402 SC = SC_None;
11403
11404 // 'explicit' is permitted.
11405 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11406 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11407 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11408 DS.ClearConstexprSpec();
11409
11410 Diagnoser.check(DS.getConstSpecLoc(), "const");
11411 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11412 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11413 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11414 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11415 DS.ClearTypeQualifiers();
11416
11417 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11418 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11419 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11420 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11421 DS.ClearTypeSpecType();
11422 }
11423
11424 if (D.isInvalidType())
11425 return true;
11426
11427 // Check the declarator is simple enough.
11428 bool FoundFunction = false;
11429 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11430 if (Chunk.Kind == DeclaratorChunk::Paren)
11431 continue;
11432 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11433 Diag(D.getDeclSpec().getBeginLoc(),
11434 diag::err_deduction_guide_with_complex_decl)
11435 << D.getSourceRange();
11436 break;
11437 }
11438 if (!Chunk.Fun.hasTrailingReturnType())
11439 return Diag(D.getName().getBeginLoc(),
11440 diag::err_deduction_guide_no_trailing_return_type);
11441
11442 // Check that the return type is written as a specialization of
11443 // the template specified as the deduction-guide's name.
11444 // The template name may not be qualified. [temp.deduct.guide]
11445 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11446 TypeSourceInfo *TSI = nullptr;
11447 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11448 assert(TSI && "deduction guide has valid type but invalid return type?");
11449 bool AcceptableReturnType = false;
11450 bool MightInstantiateToSpecialization = false;
11451 if (auto RetTST =
11453 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11454 bool TemplateMatches =
11455 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11456
11458 SpecifiedName.getAsQualifiedTemplateName();
11459 assert(Qualifiers && "expected QualifiedTemplate");
11460 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11461 Qualifiers->getQualifier() == nullptr;
11462 if (SimplyWritten && TemplateMatches)
11463 AcceptableReturnType = true;
11464 else {
11465 // This could still instantiate to the right type, unless we know it
11466 // names the wrong class template.
11467 auto *TD = SpecifiedName.getAsTemplateDecl();
11468 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11469 !TemplateMatches);
11470 }
11471 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11472 MightInstantiateToSpecialization = true;
11473 }
11474
11475 if (!AcceptableReturnType)
11476 return Diag(TSI->getTypeLoc().getBeginLoc(),
11477 diag::err_deduction_guide_bad_trailing_return_type)
11478 << GuidedTemplate << TSI->getType()
11479 << MightInstantiateToSpecialization
11480 << TSI->getTypeLoc().getSourceRange();
11481
11482 // Keep going to check that we don't have any inner declarator pieces (we
11483 // could still have a function returning a pointer to a function).
11484 FoundFunction = true;
11485 }
11486
11487 if (D.isFunctionDefinition())
11488 // we can still create a valid deduction guide here.
11489 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11490 return false;
11491}
11492
11493//===----------------------------------------------------------------------===//
11494// Namespace Handling
11495//===----------------------------------------------------------------------===//
11496
11497/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11498/// reopened.
11501 IdentifierInfo *II, bool *IsInline,
11502 NamespaceDecl *PrevNS) {
11503 assert(*IsInline != PrevNS->isInline());
11504
11505 // 'inline' must appear on the original definition, but not necessarily
11506 // on all extension definitions, so the note should point to the first
11507 // definition to avoid confusion.
11508 PrevNS = PrevNS->getFirstDecl();
11509
11510 if (PrevNS->isInline())
11511 // The user probably just forgot the 'inline', so suggest that it
11512 // be added back.
11513 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11514 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11515 else
11516 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11517
11518 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11519 *IsInline = PrevNS->isInline();
11520}
11521
11522/// ActOnStartNamespaceDef - This is called at the start of a namespace
11523/// definition.
11525 SourceLocation InlineLoc,
11526 SourceLocation NamespaceLoc,
11527 SourceLocation IdentLoc, IdentifierInfo *II,
11528 SourceLocation LBrace,
11529 const ParsedAttributesView &AttrList,
11530 UsingDirectiveDecl *&UD, bool IsNested) {
11531 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11532 // For anonymous namespace, take the location of the left brace.
11533 SourceLocation Loc = II ? IdentLoc : LBrace;
11534 bool IsInline = InlineLoc.isValid();
11535 bool IsInvalid = false;
11536 bool IsStd = false;
11537 bool AddToKnown = false;
11538 Scope *DeclRegionScope = NamespcScope->getParent();
11539
11540 NamespaceDecl *PrevNS = nullptr;
11541 if (II) {
11542 // C++ [namespace.std]p7:
11543 // A translation unit shall not declare namespace std to be an inline
11544 // namespace (9.8.2).
11545 //
11546 // Precondition: the std namespace is in the file scope and is declared to
11547 // be inline
11548 auto DiagnoseInlineStdNS = [&]() {
11549 assert(IsInline && II->isStr("std") &&
11551 "Precondition of DiagnoseInlineStdNS not met");
11552 Diag(InlineLoc, diag::err_inline_namespace_std)
11553 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11554 IsInline = false;
11555 };
11556 // C++ [namespace.def]p2:
11557 // The identifier in an original-namespace-definition shall not
11558 // have been previously defined in the declarative region in
11559 // which the original-namespace-definition appears. The
11560 // identifier in an original-namespace-definition is the name of
11561 // the namespace. Subsequently in that declarative region, it is
11562 // treated as an original-namespace-name.
11563 //
11564 // Since namespace names are unique in their scope, and we don't
11565 // look through using directives, just look for any ordinary names
11566 // as if by qualified name lookup.
11567 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11568 RedeclarationKind::ForExternalRedeclaration);
11570 NamedDecl *PrevDecl =
11571 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11572 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11573
11574 if (PrevNS) {
11575 // This is an extended namespace definition.
11576 if (IsInline && II->isStr("std") &&
11578 DiagnoseInlineStdNS();
11579 else if (IsInline != PrevNS->isInline())
11580 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11581 &IsInline, PrevNS);
11582 } else if (PrevDecl) {
11583 // This is an invalid name redefinition.
11584 Diag(Loc, diag::err_redefinition_different_kind)
11585 << II;
11586 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11587 IsInvalid = true;
11588 // Continue on to push Namespc as current DeclContext and return it.
11589 } else if (II->isStr("std") &&
11591 if (IsInline)
11592 DiagnoseInlineStdNS();
11593 // This is the first "real" definition of the namespace "std", so update
11594 // our cache of the "std" namespace to point at this definition.
11595 PrevNS = getStdNamespace();
11596 IsStd = true;
11597 AddToKnown = !IsInline;
11598 } else {
11599 // We've seen this namespace for the first time.
11600 AddToKnown = !IsInline;
11601 }
11602 } else {
11603 // Anonymous namespaces.
11604
11605 // Determine whether the parent already has an anonymous namespace.
11607 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11608 PrevNS = TU->getAnonymousNamespace();
11609 } else {
11610 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11611 PrevNS = ND->getAnonymousNamespace();
11612 }
11613
11614 if (PrevNS && IsInline != PrevNS->isInline())
11615 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11616 &IsInline, PrevNS);
11617 }
11618
11620 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11621 if (IsInvalid)
11622 Namespc->setInvalidDecl();
11623
11624 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11625 AddPragmaAttributes(DeclRegionScope, Namespc);
11626 ProcessAPINotes(Namespc);
11627
11628 // FIXME: Should we be merging attributes?
11629 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11631
11632 if (IsStd)
11633 StdNamespace = Namespc;
11634 if (AddToKnown)
11635 KnownNamespaces[Namespc] = false;
11636
11637 if (II) {
11638 PushOnScopeChains(Namespc, DeclRegionScope);
11639 } else {
11640 // Link the anonymous namespace into its parent.
11642 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11643 TU->setAnonymousNamespace(Namespc);
11644 } else {
11645 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11646 }
11647
11648 CurContext->addDecl(Namespc);
11649
11650 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11651 // behaves as if it were replaced by
11652 // namespace unique { /* empty body */ }
11653 // using namespace unique;
11654 // namespace unique { namespace-body }
11655 // where all occurrences of 'unique' in a translation unit are
11656 // replaced by the same identifier and this identifier differs
11657 // from all other identifiers in the entire program.
11658
11659 // We just create the namespace with an empty name and then add an
11660 // implicit using declaration, just like the standard suggests.
11661 //
11662 // CodeGen enforces the "universally unique" aspect by giving all
11663 // declarations semantically contained within an anonymous
11664 // namespace internal linkage.
11665
11666 if (!PrevNS) {
11668 /* 'using' */ LBrace,
11669 /* 'namespace' */ SourceLocation(),
11670 /* qualifier */ NestedNameSpecifierLoc(),
11671 /* identifier */ SourceLocation(),
11672 Namespc,
11673 /* Ancestor */ Parent);
11674 UD->setImplicit();
11675 Parent->addDecl(UD);
11676 }
11677 }
11678
11679 ActOnDocumentableDecl(Namespc);
11680
11681 // Although we could have an invalid decl (i.e. the namespace name is a
11682 // redefinition), push it as current DeclContext and try to continue parsing.
11683 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11684 // for the namespace has the declarations that showed up in that particular
11685 // namespace definition.
11686 PushDeclContext(NamespcScope, Namespc);
11687 return Namespc;
11688}
11689
11690/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11691/// is a namespace alias, returns the namespace it points to.
11693 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11694 return AD->getNamespace();
11695 return dyn_cast_or_null<NamespaceDecl>(D);
11696}
11697
11699 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11700 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11701 Namespc->setRBraceLoc(RBrace);
11703 if (Namespc->hasAttr<VisibilityAttr>())
11704 PopPragmaVisibility(true, RBrace);
11705 // If this namespace contains an export-declaration, export it now.
11706 if (DeferredExportedNamespaces.erase(Namespc))
11708}
11709
11711 return cast_or_null<CXXRecordDecl>(
11713}
11714
11716 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11717}
11718
11720 return cast_or_null<NamespaceDecl>(
11722}
11723namespace {
11724
11725enum UnsupportedSTLSelect {
11726 USS_InvalidMember,
11727 USS_MissingMember,
11728 USS_NonTrivial,
11729 USS_Other
11730};
11731
11732struct InvalidSTLDiagnoser {
11733 Sema &S;
11735 QualType TyForDiags;
11736
11737 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11738 const VarDecl *VD = nullptr) {
11739 {
11740 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11741 << TyForDiags << ((int)Sel);
11742 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11743 assert(!Name.empty());
11744 D << Name;
11745 }
11746 }
11747 if (Sel == USS_InvalidMember) {
11748 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11749 << VD << VD->getSourceRange();
11750 }
11751 return QualType();
11752 }
11753};
11754} // namespace
11755
11759 assert(getLangOpts().CPlusPlus &&
11760 "Looking for comparison category type outside of C++.");
11761
11762 // Use an elaborated type for diagnostics which has a name containing the
11763 // prepended 'std' namespace but not any inline namespace names.
11764 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11765 auto *NNS =
11768 Info->getType());
11769 };
11770
11771 // Check if we've already successfully checked the comparison category type
11772 // before. If so, skip checking it again.
11774 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11775 // The only thing we need to check is that the type has a reachable
11776 // definition in the current context.
11777 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11778 return QualType();
11779
11780 return Info->getType();
11781 }
11782
11783 // If lookup failed
11784 if (!Info) {
11785 std::string NameForDiags = "std::";
11786 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11787 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11788 << NameForDiags << (int)Usage;
11789 return QualType();
11790 }
11791
11792 assert(Info->Kind == Kind);
11793 assert(Info->Record);
11794
11795 // Update the Record decl in case we encountered a forward declaration on our
11796 // first pass. FIXME: This is a bit of a hack.
11797 if (Info->Record->hasDefinition())
11798 Info->Record = Info->Record->getDefinition();
11799
11800 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11801 return QualType();
11802
11803 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11804
11805 if (!Info->Record->isTriviallyCopyable())
11806 return UnsupportedSTLError(USS_NonTrivial);
11807
11808 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11809 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11810 // Tolerate empty base classes.
11811 if (Base->isEmpty())
11812 continue;
11813 // Reject STL implementations which have at least one non-empty base.
11814 return UnsupportedSTLError();
11815 }
11816
11817 // Check that the STL has implemented the types using a single integer field.
11818 // This expectation allows better codegen for builtin operators. We require:
11819 // (1) The class has exactly one field.
11820 // (2) The field is an integral or enumeration type.
11821 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11822 if (std::distance(FIt, FEnd) != 1 ||
11823 !FIt->getType()->isIntegralOrEnumerationType()) {
11824 return UnsupportedSTLError();
11825 }
11826
11827 // Build each of the require values and store them in Info.
11828 for (ComparisonCategoryResult CCR :
11830 StringRef MemName = ComparisonCategories::getResultString(CCR);
11831 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11832
11833 if (!ValInfo)
11834 return UnsupportedSTLError(USS_MissingMember, MemName);
11835
11836 VarDecl *VD = ValInfo->VD;
11837 assert(VD && "should not be null!");
11838
11839 // Attempt to diagnose reasons why the STL definition of this type
11840 // might be foobar, including it failing to be a constant expression.
11841 // TODO Handle more ways the lookup or result can be invalid.
11842 if (!VD->isStaticDataMember() ||
11844 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11845
11846 // Attempt to evaluate the var decl as a constant expression and extract
11847 // the value of its first field as a ICE. If this fails, the STL
11848 // implementation is not supported.
11849 if (!ValInfo->hasValidIntValue())
11850 return UnsupportedSTLError();
11851
11853 }
11854
11855 // We've successfully built the required types and expressions. Update
11856 // the cache and return the newly cached value.
11857 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11858 return Info->getType();
11859}
11860
11862 if (!StdNamespace) {
11863 // The "std" namespace has not yet been defined, so build one implicitly.
11866 /*Inline=*/false, SourceLocation(), SourceLocation(),
11867 &PP.getIdentifierTable().get("std"),
11868 /*PrevDecl=*/nullptr, /*Nested=*/false);
11870 // We want the created NamespaceDecl to be available for redeclaration
11871 // lookups, but not for regular name lookups.
11874 }
11875
11876 return getStdNamespace();
11877}
11878
11880 assert(getLangOpts().CPlusPlus &&
11881 "Looking for std::initializer_list outside of C++.");
11882
11883 // We're looking for implicit instantiations of
11884 // template <typename E> class std::initializer_list.
11885
11886 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11887 return false;
11888
11889 ClassTemplateDecl *Template = nullptr;
11890 const TemplateArgument *Arguments = nullptr;
11891
11892 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11893
11895 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11896 if (!Specialization)
11897 return false;
11898
11899 Template = Specialization->getSpecializedTemplate();
11900 Arguments = Specialization->getTemplateArgs().data();
11901 } else {
11902 const TemplateSpecializationType *TST = nullptr;
11903 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
11904 TST = ICN->getInjectedTST();
11905 else
11906 TST = Ty->getAs<TemplateSpecializationType>();
11907 if (TST) {
11908 Template = dyn_cast_or_null<ClassTemplateDecl>(
11910 Arguments = TST->template_arguments().begin();
11911 }
11912 }
11913 if (!Template)
11914 return false;
11915
11916 if (!StdInitializerList) {
11917 // Haven't recognized std::initializer_list yet, maybe this is it.
11918 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11919 if (TemplateClass->getIdentifier() !=
11920 &PP.getIdentifierTable().get("initializer_list") ||
11921 !getStdNamespace()->InEnclosingNamespaceSetOf(
11922 TemplateClass->getDeclContext()))
11923 return false;
11924 // This is a template called std::initializer_list, but is it the right
11925 // template?
11926 TemplateParameterList *Params = Template->getTemplateParameters();
11927 if (Params->getMinRequiredArguments() != 1)
11928 return false;
11929 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11930 return false;
11931
11932 // It's the right template.
11933 StdInitializerList = Template;
11934 }
11935
11937 return false;
11938
11939 // This is an instance of std::initializer_list. Find the argument type.
11940 if (Element)
11941 *Element = Arguments[0].getAsType();
11942 return true;
11943}
11944
11947 if (!Std) {
11948 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11949 return nullptr;
11950 }
11951
11952 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11954 if (!S.LookupQualifiedName(Result, Std)) {
11955 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11956 return nullptr;
11957 }
11958 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11959 if (!Template) {
11960 Result.suppressDiagnostics();
11961 // We found something weird. Complain about the first thing we found.
11962 NamedDecl *Found = *Result.begin();
11963 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11964 return nullptr;
11965 }
11966
11967 // We found some template called std::initializer_list. Now verify that it's
11968 // correct.
11969 TemplateParameterList *Params = Template->getTemplateParameters();
11970 if (Params->getMinRequiredArguments() != 1 ||
11971 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11972 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11973 return nullptr;
11974 }
11975
11976 return Template;
11977}
11978
11980 if (!StdInitializerList) {
11982 if (!StdInitializerList)
11983 return QualType();
11984 }
11985
11989 Loc)));
11994}
11995
11997 // C++ [dcl.init.list]p2:
11998 // A constructor is an initializer-list constructor if its first parameter
11999 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12000 // std::initializer_list<E> for some type E, and either there are no other
12001 // parameters or else all other parameters have default arguments.
12002 if (!Ctor->hasOneParamOrDefaultArgs())
12003 return false;
12004
12005 QualType ArgType = Ctor->getParamDecl(0)->getType();
12006 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12007 ArgType = RT->getPointeeType().getUnqualifiedType();
12008
12009 return isStdInitializerList(ArgType, nullptr);
12010}
12011
12012/// Determine whether a using statement is in a context where it will be
12013/// apply in all contexts.
12015 switch (CurContext->getDeclKind()) {
12016 case Decl::TranslationUnit:
12017 return true;
12018 case Decl::LinkageSpec:
12020 default:
12021 return false;
12022 }
12023}
12024
12025namespace {
12026
12027// Callback to only accept typo corrections that are namespaces.
12028class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12029public:
12030 bool ValidateCandidate(const TypoCorrection &candidate) override {
12031 if (NamedDecl *ND = candidate.getCorrectionDecl())
12032 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12033 return false;
12034 }
12035
12036 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12037 return std::make_unique<NamespaceValidatorCCC>(*this);
12038 }
12039};
12040
12041}
12042
12043static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12044 Sema &S) {
12045 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12046 Module *M = ND->getOwningModule();
12047 assert(M && "hidden namespace definition not in a module?");
12048
12049 if (M->isExplicitGlobalModule())
12050 S.Diag(Corrected.getCorrectionRange().getBegin(),
12051 diag::err_module_unimported_use_header)
12053 << /*Header Name*/ false;
12054 else
12055 S.Diag(Corrected.getCorrectionRange().getBegin(),
12056 diag::err_module_unimported_use)
12058 << M->getTopLevelModuleName();
12059}
12060
12062 CXXScopeSpec &SS,
12063 SourceLocation IdentLoc,
12064 IdentifierInfo *Ident) {
12065 R.clear();
12066 NamespaceValidatorCCC CCC{};
12067 if (TypoCorrection Corrected =
12068 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12070 // Generally we find it is confusing more than helpful to diagnose the
12071 // invisible namespace.
12072 // See https://github.com/llvm/llvm-project/issues/73893.
12073 //
12074 // However, we should diagnose when the users are trying to using an
12075 // invisible namespace. So we handle the case specially here.
12076 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12077 Corrected.requiresImport()) {
12078 DiagnoseInvisibleNamespace(Corrected, S);
12079 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12080 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12081 bool DroppedSpecifier =
12082 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12083 S.diagnoseTypo(Corrected,
12084 S.PDiag(diag::err_using_directive_member_suggest)
12085 << Ident << DC << DroppedSpecifier << SS.getRange(),
12086 S.PDiag(diag::note_namespace_defined_here));
12087 } else {
12088 S.diagnoseTypo(Corrected,
12089 S.PDiag(diag::err_using_directive_suggest) << Ident,
12090 S.PDiag(diag::note_namespace_defined_here));
12091 }
12092 R.addDecl(Corrected.getFoundDecl());
12093 return true;
12094 }
12095 return false;
12096}
12097
12099 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12100 SourceLocation IdentLoc,
12101 IdentifierInfo *NamespcName,
12102 const ParsedAttributesView &AttrList) {
12103 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12104 assert(NamespcName && "Invalid NamespcName.");
12105 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12106
12107 // Get the innermost enclosing declaration scope.
12108 S = S->getDeclParent();
12109
12110 UsingDirectiveDecl *UDir = nullptr;
12111 NestedNameSpecifier *Qualifier = nullptr;
12112 if (SS.isSet())
12113 Qualifier = SS.getScopeRep();
12114
12115 // Lookup namespace name.
12116 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12117 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12118 if (R.isAmbiguous())
12119 return nullptr;
12120
12121 if (R.empty()) {
12122 R.clear();
12123 // Allow "using namespace std;" or "using namespace ::std;" even if
12124 // "std" hasn't been defined yet, for GCC compatibility.
12125 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12126 NamespcName->isStr("std")) {
12127 Diag(IdentLoc, diag::ext_using_undefined_std);
12129 R.resolveKind();
12130 }
12131 // Otherwise, attempt typo correction.
12132 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12133 }
12134
12135 if (!R.empty()) {
12136 NamedDecl *Named = R.getRepresentativeDecl();
12138 assert(NS && "expected namespace decl");
12139
12140 // The use of a nested name specifier may trigger deprecation warnings.
12141 DiagnoseUseOfDecl(Named, IdentLoc);
12142
12143 // C++ [namespace.udir]p1:
12144 // A using-directive specifies that the names in the nominated
12145 // namespace can be used in the scope in which the
12146 // using-directive appears after the using-directive. During
12147 // unqualified name lookup (3.4.1), the names appear as if they
12148 // were declared in the nearest enclosing namespace which
12149 // contains both the using-directive and the nominated
12150 // namespace. [Note: in this context, "contains" means "contains
12151 // directly or indirectly". ]
12152
12153 // Find enclosing context containing both using-directive and
12154 // nominated namespace.
12155 DeclContext *CommonAncestor = NS;
12156 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12157 CommonAncestor = CommonAncestor->getParent();
12158
12159 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12161 IdentLoc, Named, CommonAncestor);
12162
12165 Diag(IdentLoc, diag::warn_using_directive_in_header);
12166 }
12167
12168 PushUsingDirective(S, UDir);
12169 } else {
12170 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12171 }
12172
12173 if (UDir) {
12174 ProcessDeclAttributeList(S, UDir, AttrList);
12175 ProcessAPINotes(UDir);
12176 }
12177
12178 return UDir;
12179}
12180
12182 // If the scope has an associated entity and the using directive is at
12183 // namespace or translation unit scope, add the UsingDirectiveDecl into
12184 // its lookup structure so qualified name lookup can find it.
12185 DeclContext *Ctx = S->getEntity();
12186 if (Ctx && !Ctx->isFunctionOrMethod())
12187 Ctx->addDecl(UDir);
12188 else
12189 // Otherwise, it is at block scope. The using-directives will affect lookup
12190 // only to the end of the scope.
12191 S->PushUsingDirective(UDir);
12192}
12193
12195 SourceLocation UsingLoc,
12196 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12197 UnqualifiedId &Name,
12198 SourceLocation EllipsisLoc,
12199 const ParsedAttributesView &AttrList) {
12200 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12201
12202 if (SS.isEmpty()) {
12203 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12204 return nullptr;
12205 }
12206
12207 switch (Name.getKind()) {
12213 break;
12214
12217 // C++11 inheriting constructors.
12218 Diag(Name.getBeginLoc(),
12220 ? diag::warn_cxx98_compat_using_decl_constructor
12221 : diag::err_using_decl_constructor)
12222 << SS.getRange();
12223
12224 if (getLangOpts().CPlusPlus11) break;
12225
12226 return nullptr;
12227
12229 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12230 return nullptr;
12231
12233 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12234 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12235 return nullptr;
12236
12238 llvm_unreachable("cannot parse qualified deduction guide name");
12239 }
12240
12241 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12242 DeclarationName TargetName = TargetNameInfo.getName();
12243 if (!TargetName)
12244 return nullptr;
12245
12246 // Warn about access declarations.
12247 if (UsingLoc.isInvalid()) {
12248 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12249 ? diag::err_access_decl
12250 : diag::warn_access_decl_deprecated)
12251 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12252 }
12253
12254 if (EllipsisLoc.isInvalid()) {
12257 return nullptr;
12258 } else {
12260 !TargetNameInfo.containsUnexpandedParameterPack()) {
12261 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12262 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12263 EllipsisLoc = SourceLocation();
12264 }
12265 }
12266
12267 NamedDecl *UD =
12268 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12269 SS, TargetNameInfo, EllipsisLoc, AttrList,
12270 /*IsInstantiation*/ false,
12271 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12272 if (UD)
12273 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12274
12275 return UD;
12276}
12277
12279 SourceLocation UsingLoc,
12280 SourceLocation EnumLoc, SourceRange TyLoc,
12281 const IdentifierInfo &II, ParsedType Ty,
12282 CXXScopeSpec *SS) {
12283 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12284 TypeSourceInfo *TSI = nullptr;
12285 SourceLocation IdentLoc = TyLoc.getBegin();
12286 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12287 if (EnumTy.isNull()) {
12288 Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12289 ? diag::err_using_enum_is_dependent
12290 : diag::err_unknown_typename)
12291 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12292 return nullptr;
12293 }
12294
12295 if (EnumTy->isDependentType()) {
12296 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12297 return nullptr;
12298 }
12299
12300 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12301 if (!Enum) {
12302 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12303 return nullptr;
12304 }
12305
12306 if (auto *Def = Enum->getDefinition())
12307 Enum = Def;
12308
12309 if (TSI == nullptr)
12310 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12311
12312 auto *UD =
12313 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12314
12315 if (UD)
12316 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12317
12318 return UD;
12319}
12320
12321/// Determine whether a using declaration considers the given
12322/// declarations as "equivalent", e.g., if they are redeclarations of
12323/// the same entity or are both typedefs of the same type.
12324static bool
12326 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12327 return true;
12328
12329 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12330 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12331 return Context.hasSameType(TD1->getUnderlyingType(),
12332 TD2->getUnderlyingType());
12333
12334 // Two using_if_exists using-declarations are equivalent if both are
12335 // unresolved.
12336 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12337 isa<UnresolvedUsingIfExistsDecl>(D2))
12338 return true;
12339
12340 return false;
12341}
12342
12344 const LookupResult &Previous,
12345 UsingShadowDecl *&PrevShadow) {
12346 // Diagnose finding a decl which is not from a base class of the
12347 // current class. We do this now because there are cases where this
12348 // function will silently decide not to build a shadow decl, which
12349 // will pre-empt further diagnostics.
12350 //
12351 // We don't need to do this in C++11 because we do the check once on
12352 // the qualifier.
12353 //
12354 // FIXME: diagnose the following if we care enough:
12355 // struct A { int foo; };
12356 // struct B : A { using A::foo; };
12357 // template <class T> struct C : A {};
12358 // template <class T> struct D : C<T> { using B::foo; } // <---
12359 // This is invalid (during instantiation) in C++03 because B::foo
12360 // resolves to the using decl in B, which is not a base class of D<T>.
12361 // We can't diagnose it immediately because C<T> is an unknown
12362 // specialization. The UsingShadowDecl in D<T> then points directly
12363 // to A::foo, which will look well-formed when we instantiate.
12364 // The right solution is to not collapse the shadow-decl chain.
12366 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12367 DeclContext *OrigDC = Orig->getDeclContext();
12368
12369 // Handle enums and anonymous structs.
12370 if (isa<EnumDecl>(OrigDC))
12371 OrigDC = OrigDC->getParent();
12372 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12373 while (OrigRec->isAnonymousStructOrUnion())
12374 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12375
12376 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12377 if (OrigDC == CurContext) {
12378 Diag(Using->getLocation(),
12379 diag::err_using_decl_nested_name_specifier_is_current_class)
12380 << Using->getQualifierLoc().getSourceRange();
12381 Diag(Orig->getLocation(), diag::note_using_decl_target);
12382 Using->setInvalidDecl();
12383 return true;
12384 }
12385
12386 Diag(Using->getQualifierLoc().getBeginLoc(),
12387 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12388 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12389 << Using->getQualifierLoc().getSourceRange();
12390 Diag(Orig->getLocation(), diag::note_using_decl_target);
12391 Using->setInvalidDecl();
12392 return true;
12393 }
12394 }
12395
12396 if (Previous.empty()) return false;
12397
12398 NamedDecl *Target = Orig;
12399 if (isa<UsingShadowDecl>(Target))
12400 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12401
12402 // If the target happens to be one of the previous declarations, we
12403 // don't have a conflict.
12404 //
12405 // FIXME: but we might be increasing its access, in which case we
12406 // should redeclare it.
12407 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12408 bool FoundEquivalentDecl = false;
12409 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12410 I != E; ++I) {
12411 NamedDecl *D = (*I)->getUnderlyingDecl();
12412 // We can have UsingDecls in our Previous results because we use the same
12413 // LookupResult for checking whether the UsingDecl itself is a valid
12414 // redeclaration.
12415 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12416 continue;
12417
12418 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12419 // C++ [class.mem]p19:
12420 // If T is the name of a class, then [every named member other than
12421 // a non-static data member] shall have a name different from T
12422 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12423 !isa<IndirectFieldDecl>(Target) &&
12424 !isa<UnresolvedUsingValueDecl>(Target) &&
12426 CurContext,
12428 return true;
12429 }
12430
12432 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12433 PrevShadow = Shadow;
12434 FoundEquivalentDecl = true;
12436 // We don't conflict with an existing using shadow decl of an equivalent
12437 // declaration, but we're not a redeclaration of it.
12438 FoundEquivalentDecl = true;
12439 }
12440
12441 if (isVisible(D))
12442 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12443 }
12444
12445 if (FoundEquivalentDecl)
12446 return false;
12447
12448 // Always emit a diagnostic for a mismatch between an unresolved
12449 // using_if_exists and a resolved using declaration in either direction.
12450 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12451 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12452 if (!NonTag && !Tag)
12453 return false;
12454 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12455 Diag(Target->getLocation(), diag::note_using_decl_target);
12456 Diag((NonTag ? NonTag : Tag)->getLocation(),
12457 diag::note_using_decl_conflict);
12458 BUD->setInvalidDecl();
12459 return true;
12460 }
12461
12462 if (FunctionDecl *FD = Target->getAsFunction()) {
12463 NamedDecl *OldDecl = nullptr;
12464 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12465 /*IsForUsingDecl*/ true)) {
12466 case Ovl_Overload:
12467 return false;
12468
12469 case Ovl_NonFunction:
12470 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12471 break;
12472
12473 // We found a decl with the exact signature.
12474 case Ovl_Match:
12475 // If we're in a record, we want to hide the target, so we
12476 // return true (without a diagnostic) to tell the caller not to
12477 // build a shadow decl.
12478 if (CurContext->isRecord())
12479 return true;
12480
12481 // If we're not in a record, this is an error.
12482 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12483 break;
12484 }
12485
12486 Diag(Target->getLocation(), diag::note_using_decl_target);
12487 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12488 BUD->setInvalidDecl();
12489 return true;
12490 }
12491
12492 // Target is not a function.
12493
12494 if (isa<TagDecl>(Target)) {
12495 // No conflict between a tag and a non-tag.
12496 if (!Tag) return false;
12497
12498 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12499 Diag(Target->getLocation(), diag::note_using_decl_target);
12500 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12501 BUD->setInvalidDecl();
12502 return true;
12503 }
12504
12505 // No conflict between a tag and a non-tag.
12506 if (!NonTag) return false;
12507
12508 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12509 Diag(Target->getLocation(), diag::note_using_decl_target);
12510 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12511 BUD->setInvalidDecl();
12512 return true;
12513}
12514
12515/// Determine whether a direct base class is a virtual base class.
12517 if (!Derived->getNumVBases())
12518 return false;
12519 for (auto &B : Derived->bases())
12520 if (B.getType()->getAsCXXRecordDecl() == Base)
12521 return B.isVirtual();
12522 llvm_unreachable("not a direct base class");
12523}
12524
12526 NamedDecl *Orig,
12527 UsingShadowDecl *PrevDecl) {
12528 // If we resolved to another shadow declaration, just coalesce them.
12529 NamedDecl *Target = Orig;
12530 if (isa<UsingShadowDecl>(Target)) {
12531 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12532 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12533 }
12534
12535 NamedDecl *NonTemplateTarget = Target;
12536 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12537 NonTemplateTarget = TargetTD->getTemplatedDecl();
12538
12539 UsingShadowDecl *Shadow;
12540 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12541 UsingDecl *Using = cast<UsingDecl>(BUD);
12542 bool IsVirtualBase =
12543 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12544 Using->getQualifier()->getAsRecordDecl());
12546 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12547 } else {
12549 Target->getDeclName(), BUD, Target);
12550 }
12551 BUD->addShadowDecl(Shadow);
12552
12553 Shadow->setAccess(BUD->getAccess());
12554 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12555 Shadow->setInvalidDecl();
12556
12557 Shadow->setPreviousDecl(PrevDecl);
12558
12559 if (S)
12560 PushOnScopeChains(Shadow, S);
12561 else
12562 CurContext->addDecl(Shadow);
12563
12564
12565 return Shadow;
12566}
12567
12569 if (Shadow->getDeclName().getNameKind() ==
12571 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12572
12573 // Remove it from the DeclContext...
12574 Shadow->getDeclContext()->removeDecl(Shadow);
12575
12576 // ...and the scope, if applicable...
12577 if (S) {
12578 S->RemoveDecl(Shadow);
12579 IdResolver.RemoveDecl(Shadow);
12580 }
12581
12582 // ...and the using decl.
12583 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12584
12585 // TODO: complain somehow if Shadow was used. It shouldn't
12586 // be possible for this to happen, because...?
12587}
12588
12589/// Find the base specifier for a base class with the given type.
12591 QualType DesiredBase,
12592 bool &AnyDependentBases) {
12593 // Check whether the named type is a direct base class.
12594 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12596 for (auto &Base : Derived->bases()) {
12597 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12598 if (CanonicalDesiredBase == BaseType)
12599 return &Base;
12600 if (BaseType->isDependentType())
12601 AnyDependentBases = true;
12602 }
12603 return nullptr;
12604}
12605
12606namespace {
12607class UsingValidatorCCC final : public CorrectionCandidateCallback {
12608public:
12609 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12610 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12611 : HasTypenameKeyword(HasTypenameKeyword),
12612 IsInstantiation(IsInstantiation), OldNNS(NNS),
12613 RequireMemberOf(RequireMemberOf) {}
12614
12615 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12616 NamedDecl *ND = Candidate.getCorrectionDecl();
12617
12618 // Keywords are not valid here.
12619 if (!ND || isa<NamespaceDecl>(ND))
12620 return false;
12621
12622 // Completely unqualified names are invalid for a 'using' declaration.
12623 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12624 return false;
12625
12626 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12627 // reject.
12628
12629 if (RequireMemberOf) {
12630 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12631 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12632 // No-one ever wants a using-declaration to name an injected-class-name
12633 // of a base class, unless they're declaring an inheriting constructor.
12634 ASTContext &Ctx = ND->getASTContext();
12635 if (!Ctx.getLangOpts().CPlusPlus11)
12636 return false;
12637 QualType FoundType = Ctx.getRecordType(FoundRecord);
12638
12639 // Check that the injected-class-name is named as a member of its own
12640 // type; we don't want to suggest 'using Derived::Base;', since that
12641 // means something else.
12643 Candidate.WillReplaceSpecifier()
12644 ? Candidate.getCorrectionSpecifier()
12645 : OldNNS;
12646 if (!Specifier->getAsType() ||
12647 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12648 return false;
12649
12650 // Check that this inheriting constructor declaration actually names a
12651 // direct base class of the current class.
12652 bool AnyDependentBases = false;
12653 if (!findDirectBaseWithType(RequireMemberOf,
12654 Ctx.getRecordType(FoundRecord),
12655 AnyDependentBases) &&
12656 !AnyDependentBases)
12657 return false;
12658 } else {
12659 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12660 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12661 return false;
12662
12663 // FIXME: Check that the base class member is accessible?
12664 }
12665 } else {
12666 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12667 if (FoundRecord && FoundRecord->isInjectedClassName())
12668 return false;
12669 }
12670
12671 if (isa<TypeDecl>(ND))
12672 return HasTypenameKeyword || !IsInstantiation;
12673
12674 return !HasTypenameKeyword;
12675 }
12676
12677 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12678 return std::make_unique<UsingValidatorCCC>(*this);
12679 }
12680
12681private:
12682 bool HasTypenameKeyword;
12683 bool IsInstantiation;
12684 NestedNameSpecifier *OldNNS;
12685 CXXRecordDecl *RequireMemberOf;
12686};
12687} // end anonymous namespace
12688
12690 // It is really dumb that we have to do this.
12691 LookupResult::Filter F = Previous.makeFilter();
12692 while (F.hasNext()) {
12693 NamedDecl *D = F.next();
12694 if (!isDeclInScope(D, CurContext, S))
12695 F.erase();
12696 // If we found a local extern declaration that's not ordinarily visible,
12697 // and this declaration is being added to a non-block scope, ignore it.
12698 // We're only checking for scope conflicts here, not also for violations
12699 // of the linkage rules.
12700 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12702 F.erase();
12703 }
12704 F.done();
12705}
12706
12708 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12709 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12710 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12711 const ParsedAttributesView &AttrList, bool IsInstantiation,
12712 bool IsUsingIfExists) {
12713 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12714 SourceLocation IdentLoc = NameInfo.getLoc();
12715 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12716
12717 // FIXME: We ignore attributes for now.
12718
12719 // For an inheriting constructor declaration, the name of the using
12720 // declaration is the name of a constructor in this class, not in the
12721 // base class.
12722 DeclarationNameInfo UsingName = NameInfo;
12724 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12727
12728 // Do the redeclaration lookup in the current scope.
12729 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12730 RedeclarationKind::ForVisibleRedeclaration);
12731 Previous.setHideTags(false);
12732 if (S) {
12733 LookupName(Previous, S);
12734
12736 } else {
12737 assert(IsInstantiation && "no scope in non-instantiation");
12738 if (CurContext->isRecord())
12740 else {
12741 // No redeclaration check is needed here; in non-member contexts we
12742 // diagnosed all possible conflicts with other using-declarations when
12743 // building the template:
12744 //
12745 // For a dependent non-type using declaration, the only valid case is
12746 // if we instantiate to a single enumerator. We check for conflicts
12747 // between shadow declarations we introduce, and we check in the template
12748 // definition for conflicts between a non-type using declaration and any
12749 // other declaration, which together covers all cases.
12750 //
12751 // A dependent typename using declaration will never successfully
12752 // instantiate, since it will always name a class member, so we reject
12753 // that in the template definition.
12754 }
12755 }
12756
12757 // Check for invalid redeclarations.
12758 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12759 SS, IdentLoc, Previous))
12760 return nullptr;
12761
12762 // 'using_if_exists' doesn't make sense on an inherited constructor.
12763 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12765 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12766 return nullptr;
12767 }
12768
12769 DeclContext *LookupContext = computeDeclContext(SS);
12771 if (!LookupContext || EllipsisLoc.isValid()) {
12772 NamedDecl *D;
12773 // Dependent scope, or an unexpanded pack
12774 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12775 SS, NameInfo, IdentLoc))
12776 return nullptr;
12777
12778 if (HasTypenameKeyword) {
12779 // FIXME: not all declaration name kinds are legal here
12781 UsingLoc, TypenameLoc,
12782 QualifierLoc,
12783 IdentLoc, NameInfo.getName(),
12784 EllipsisLoc);
12785 } else {
12787 QualifierLoc, NameInfo, EllipsisLoc);
12788 }
12789 D->setAccess(AS);
12791 ProcessDeclAttributeList(S, D, AttrList);
12792 return D;
12793 }
12794
12795 auto Build = [&](bool Invalid) {
12796 UsingDecl *UD =
12797 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12798 UsingName, HasTypenameKeyword);
12799 UD->setAccess(AS);
12800 CurContext->addDecl(UD);
12801 ProcessDeclAttributeList(S, UD, AttrList);
12803 return UD;
12804 };
12805 auto BuildInvalid = [&]{ return Build(true); };
12806 auto BuildValid = [&]{ return Build(false); };
12807
12808 if (RequireCompleteDeclContext(SS, LookupContext))
12809 return BuildInvalid();
12810
12811 // Look up the target name.
12812 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12813
12814 // Unlike most lookups, we don't always want to hide tag
12815 // declarations: tag names are visible through the using declaration
12816 // even if hidden by ordinary names, *except* in a dependent context
12817 // where they may be used by two-phase lookup.
12818 if (!IsInstantiation)
12819 R.setHideTags(false);
12820
12821 // For the purposes of this lookup, we have a base object type
12822 // equal to that of the current context.
12823 if (CurContext->isRecord()) {
12825 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12826 }
12827
12828 LookupQualifiedName(R, LookupContext);
12829
12830 // Validate the context, now we have a lookup
12831 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12832 IdentLoc, &R))
12833 return nullptr;
12834
12835 if (R.empty() && IsUsingIfExists)
12837 UsingName.getName()),
12838 AS_public);
12839
12840 // Try to correct typos if possible. If constructor name lookup finds no
12841 // results, that means the named class has no explicit constructors, and we
12842 // suppressed declaring implicit ones (probably because it's dependent or
12843 // invalid).
12844 if (R.empty() &&
12846 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12847 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12848 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12849 auto *II = NameInfo.getName().getAsIdentifierInfo();
12850 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12852 isa<TranslationUnitDecl>(LookupContext) &&
12853 getSourceManager().isInSystemHeader(UsingLoc))
12854 return nullptr;
12855 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12856 dyn_cast<CXXRecordDecl>(CurContext));
12857 if (TypoCorrection Corrected =
12858 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12860 // We reject candidates where DroppedSpecifier == true, hence the
12861 // literal '0' below.
12862 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12863 << NameInfo.getName() << LookupContext << 0
12864 << SS.getRange());
12865
12866 // If we picked a correction with no attached Decl we can't do anything
12867 // useful with it, bail out.
12868 NamedDecl *ND = Corrected.getCorrectionDecl();
12869 if (!ND)
12870 return BuildInvalid();
12871
12872 // If we corrected to an inheriting constructor, handle it as one.
12873 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12874 if (RD && RD->isInjectedClassName()) {
12875 // The parent of the injected class name is the class itself.
12876 RD = cast<CXXRecordDecl>(RD->getParent());
12877
12878 // Fix up the information we'll use to build the using declaration.
12879 if (Corrected.WillReplaceSpecifier()) {
12881 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12882 QualifierLoc.getSourceRange());
12883 QualifierLoc = Builder.getWithLocInContext(Context);
12884 }
12885
12886 // In this case, the name we introduce is the name of a derived class
12887 // constructor.
12888 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12891 UsingName.setNamedTypeInfo(nullptr);
12892 for (auto *Ctor : LookupConstructors(RD))
12893 R.addDecl(Ctor);
12894 R.resolveKind();
12895 } else {
12896 // FIXME: Pick up all the declarations if we found an overloaded
12897 // function.
12898 UsingName.setName(ND->getDeclName());
12899 R.addDecl(ND);
12900 }
12901 } else {
12902 Diag(IdentLoc, diag::err_no_member)
12903 << NameInfo.getName() << LookupContext << SS.getRange();
12904 return BuildInvalid();
12905 }
12906 }
12907
12908 if (R.isAmbiguous())
12909 return BuildInvalid();
12910
12911 if (HasTypenameKeyword) {
12912 // If we asked for a typename and got a non-type decl, error out.
12913 if (!R.getAsSingle<TypeDecl>() &&
12915 Diag(IdentLoc, diag::err_using_typename_non_type);
12916 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12917 Diag((*I)->getUnderlyingDecl()->getLocation(),
12918 diag::note_using_decl_target);
12919 return BuildInvalid();
12920 }
12921 } else {
12922 // If we asked for a non-typename and we got a type, error out,
12923 // but only if this is an instantiation of an unresolved using
12924 // decl. Otherwise just silently find the type name.
12925 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12926 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12927 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12928 return BuildInvalid();
12929 }
12930 }
12931
12932 // C++14 [namespace.udecl]p6:
12933 // A using-declaration shall not name a namespace.
12934 if (R.getAsSingle<NamespaceDecl>()) {
12935 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12936 << SS.getRange();
12937 // Suggest using 'using namespace ...' instead.
12938 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
12939 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
12940 return BuildInvalid();
12941 }
12942
12943 UsingDecl *UD = BuildValid();
12944
12945 // Some additional rules apply to inheriting constructors.
12946 if (UsingName.getName().getNameKind() ==
12948 // Suppress access diagnostics; the access check is instead performed at the
12949 // point of use for an inheriting constructor.
12952 return UD;
12953 }
12954
12955 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12956 UsingShadowDecl *PrevDecl = nullptr;
12957 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12958 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12959 }
12960
12961 return UD;
12962}
12963
12965 SourceLocation UsingLoc,
12966 SourceLocation EnumLoc,
12967 SourceLocation NameLoc,
12969 EnumDecl *ED) {
12970 bool Invalid = false;
12971
12973 /// In class scope, check if this is a duplicate, for better a diagnostic.
12974 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12975 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12976 RedeclarationKind::ForVisibleRedeclaration);
12977
12978 LookupName(Previous, S);
12979
12980 for (NamedDecl *D : Previous)
12981 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12982 if (UED->getEnumDecl() == ED) {
12983 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12984 << SourceRange(EnumLoc, NameLoc);
12985 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12986 Invalid = true;
12987 break;
12988 }
12989 }
12990
12991 if (RequireCompleteEnumDecl(ED, NameLoc))
12992 Invalid = true;
12993
12995 EnumLoc, NameLoc, EnumType);
12996 UD->setAccess(AS);
12997 CurContext->addDecl(UD);
12998
12999 if (Invalid) {
13000 UD->setInvalidDecl();
13001 return UD;
13002 }
13003
13004 // Create the shadow decls for each enumerator
13005 for (EnumConstantDecl *EC : ED->enumerators()) {
13006 UsingShadowDecl *PrevDecl = nullptr;
13007 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13009 RedeclarationKind::ForVisibleRedeclaration);
13010 LookupName(Previous, S);
13012
13013 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13014 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13015 }
13016
13017 return UD;
13018}
13019
13021 ArrayRef<NamedDecl *> Expansions) {
13022 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13023 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13024 isa<UsingPackDecl>(InstantiatedFrom));
13025
13026 auto *UPD =
13027 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13028 UPD->setAccess(InstantiatedFrom->getAccess());
13029 CurContext->addDecl(UPD);
13030 return UPD;
13031}
13032
13034 assert(!UD->hasTypename() && "expecting a constructor name");
13035
13036 const Type *SourceType = UD->getQualifier()->getAsType();
13037 assert(SourceType &&
13038 "Using decl naming constructor doesn't have type in scope spec.");
13039 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13040
13041 // Check whether the named type is a direct base class.
13042 bool AnyDependentBases = false;
13043 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13044 AnyDependentBases);
13045 if (!Base && !AnyDependentBases) {
13046 Diag(UD->getUsingLoc(),
13047 diag::err_using_decl_constructor_not_in_direct_base)
13048 << UD->getNameInfo().getSourceRange()
13049 << QualType(SourceType, 0) << TargetClass;
13050 UD->setInvalidDecl();
13051 return true;
13052 }
13053
13054 if (Base)
13055 Base->setInheritConstructors();
13056
13057 return false;
13058}
13059
13061 bool HasTypenameKeyword,
13062 const CXXScopeSpec &SS,
13063 SourceLocation NameLoc,
13064 const LookupResult &Prev) {
13065 NestedNameSpecifier *Qual = SS.getScopeRep();
13066
13067 // C++03 [namespace.udecl]p8:
13068 // C++0x [namespace.udecl]p10:
13069 // A using-declaration is a declaration and can therefore be used
13070 // repeatedly where (and only where) multiple declarations are
13071 // allowed.
13072 //
13073 // That's in non-member contexts.
13075 // A dependent qualifier outside a class can only ever resolve to an
13076 // enumeration type. Therefore it conflicts with any other non-type
13077 // declaration in the same scope.
13078 // FIXME: How should we check for dependent type-type conflicts at block
13079 // scope?
13080 if (Qual->isDependent() && !HasTypenameKeyword) {
13081 for (auto *D : Prev) {
13082 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13083 bool OldCouldBeEnumerator =
13084 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13085 Diag(NameLoc,
13086 OldCouldBeEnumerator ? diag::err_redefinition
13087 : diag::err_redefinition_different_kind)
13088 << Prev.getLookupName();
13089 Diag(D->getLocation(), diag::note_previous_definition);
13090 return true;
13091 }
13092 }
13093 }
13094 return false;
13095 }
13096
13097 const NestedNameSpecifier *CNNS =
13099 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13100 NamedDecl *D = *I;
13101
13102 bool DTypename;
13103 NestedNameSpecifier *DQual;
13104 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13105 DTypename = UD->hasTypename();
13106 DQual = UD->getQualifier();
13107 } else if (UnresolvedUsingValueDecl *UD
13108 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13109 DTypename = false;
13110 DQual = UD->getQualifier();
13111 } else if (UnresolvedUsingTypenameDecl *UD
13112 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13113 DTypename = true;
13114 DQual = UD->getQualifier();
13115 } else continue;
13116
13117 // using decls differ if one says 'typename' and the other doesn't.
13118 // FIXME: non-dependent using decls?
13119 if (HasTypenameKeyword != DTypename) continue;
13120
13121 // using decls differ if they name different scopes (but note that
13122 // template instantiation can cause this check to trigger when it
13123 // didn't before instantiation).
13124 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13125 continue;
13126
13127 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13128 Diag(D->getLocation(), diag::note_using_decl) << 1;
13129 return true;
13130 }
13131
13132 return false;
13133}
13134
13135bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13136 const CXXScopeSpec &SS,
13137 const DeclarationNameInfo &NameInfo,
13138 SourceLocation NameLoc,
13139 const LookupResult *R, const UsingDecl *UD) {
13140 DeclContext *NamedContext = computeDeclContext(SS);
13141 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13142 "resolvable context must have exactly one set of decls");
13143
13144 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13145 // relationship.
13146 bool Cxx20Enumerator = false;
13147 if (NamedContext) {
13148 EnumConstantDecl *EC = nullptr;
13149 if (R)
13150 EC = R->getAsSingle<EnumConstantDecl>();
13151 else if (UD && UD->shadow_size() == 1)
13152 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13153 if (EC)
13154 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13155
13156 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13157 // C++14 [namespace.udecl]p7:
13158 // A using-declaration shall not name a scoped enumerator.
13159 // C++20 p1099 permits enumerators.
13160 if (EC && R && ED->isScoped())
13161 Diag(SS.getBeginLoc(),
13163 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13164 : diag::ext_using_decl_scoped_enumerator)
13165 << SS.getRange();
13166
13167 // We want to consider the scope of the enumerator
13168 NamedContext = ED->getDeclContext();
13169 }
13170 }
13171
13172 if (!CurContext->isRecord()) {
13173 // C++03 [namespace.udecl]p3:
13174 // C++0x [namespace.udecl]p8:
13175 // A using-declaration for a class member shall be a member-declaration.
13176 // C++20 [namespace.udecl]p7
13177 // ... other than an enumerator ...
13178
13179 // If we weren't able to compute a valid scope, it might validly be a
13180 // dependent class or enumeration scope. If we have a 'typename' keyword,
13181 // the scope must resolve to a class type.
13182 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13183 : !HasTypename)
13184 return false; // OK
13185
13186 Diag(NameLoc,
13187 Cxx20Enumerator
13188 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13189 : diag::err_using_decl_can_not_refer_to_class_member)
13190 << SS.getRange();
13191
13192 if (Cxx20Enumerator)
13193 return false; // OK
13194
13195 auto *RD = NamedContext
13196 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13197 : nullptr;
13198 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13199 // See if there's a helpful fixit
13200
13201 if (!R) {
13202 // We will have already diagnosed the problem on the template
13203 // definition, Maybe we should do so again?
13204 } else if (R->getAsSingle<TypeDecl>()) {
13205 if (getLangOpts().CPlusPlus11) {
13206 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13207 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13208 << 0 // alias declaration
13210 NameInfo.getName().getAsString() +
13211 " = ");
13212 } else {
13213 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13214 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13215 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13216 << 1 // typedef declaration
13217 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13219 InsertLoc, " " + NameInfo.getName().getAsString());
13220 }
13221 } else if (R->getAsSingle<VarDecl>()) {
13222 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13223 // repeating the type of the static data member here.
13224 FixItHint FixIt;
13225 if (getLangOpts().CPlusPlus11) {
13226 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13228 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13229 }
13230
13231 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13232 << 2 // reference declaration
13233 << FixIt;
13234 } else if (R->getAsSingle<EnumConstantDecl>()) {
13235 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13236 // repeating the type of the enumeration here, and we can't do so if
13237 // the type is anonymous.
13238 FixItHint FixIt;
13239 if (getLangOpts().CPlusPlus11) {
13240 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13242 UsingLoc,
13243 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13244 }
13245
13246 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13247 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13248 << FixIt;
13249 }
13250 }
13251
13252 return true; // Fail
13253 }
13254
13255 // If the named context is dependent, we can't decide much.
13256 if (!NamedContext) {
13257 // FIXME: in C++0x, we can diagnose if we can prove that the
13258 // nested-name-specifier does not refer to a base class, which is
13259 // still possible in some cases.
13260
13261 // Otherwise we have to conservatively report that things might be
13262 // okay.
13263 return false;
13264 }
13265
13266 // The current scope is a record.
13267 if (!NamedContext->isRecord()) {
13268 // Ideally this would point at the last name in the specifier,
13269 // but we don't have that level of source info.
13270 Diag(SS.getBeginLoc(),
13271 Cxx20Enumerator
13272 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13273 : diag::err_using_decl_nested_name_specifier_is_not_class)
13274 << SS.getScopeRep() << SS.getRange();
13275
13276 if (Cxx20Enumerator)
13277 return false; // OK
13278
13279 return true;
13280 }
13281
13282 if (!NamedContext->isDependentContext() &&
13283 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13284 return true;
13285
13286 if (getLangOpts().CPlusPlus11) {
13287 // C++11 [namespace.udecl]p3:
13288 // In a using-declaration used as a member-declaration, the
13289 // nested-name-specifier shall name a base class of the class
13290 // being defined.
13291
13292 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13293 cast<CXXRecordDecl>(NamedContext))) {
13294
13295 if (Cxx20Enumerator) {
13296 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13297 << SS.getRange();
13298 return false;
13299 }
13300
13301 if (CurContext == NamedContext) {
13302 Diag(SS.getBeginLoc(),
13303 diag::err_using_decl_nested_name_specifier_is_current_class)
13304 << SS.getRange();
13305 return !getLangOpts().CPlusPlus20;
13306 }
13307
13308 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13309 Diag(SS.getBeginLoc(),
13310 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13311 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13312 << SS.getRange();
13313 }
13314 return true;
13315 }
13316
13317 return false;
13318 }
13319
13320 // C++03 [namespace.udecl]p4:
13321 // A using-declaration used as a member-declaration shall refer
13322 // to a member of a base class of the class being defined [etc.].
13323
13324 // Salient point: SS doesn't have to name a base class as long as
13325 // lookup only finds members from base classes. Therefore we can
13326 // diagnose here only if we can prove that can't happen,
13327 // i.e. if the class hierarchies provably don't intersect.
13328
13329 // TODO: it would be nice if "definitely valid" results were cached
13330 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13331 // need to be repeated.
13332
13334 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13335 Bases.insert(Base);
13336 return true;
13337 };
13338
13339 // Collect all bases. Return false if we find a dependent base.
13340 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13341 return false;
13342
13343 // Returns true if the base is dependent or is one of the accumulated base
13344 // classes.
13345 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13346 return !Bases.count(Base);
13347 };
13348
13349 // Return false if the class has a dependent base or if it or one
13350 // of its bases is present in the base set of the current context.
13351 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13352 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13353 return false;
13354
13355 Diag(SS.getRange().getBegin(),
13356 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13357 << SS.getScopeRep()
13358 << cast<CXXRecordDecl>(CurContext)
13359 << SS.getRange();
13360
13361 return true;
13362}
13363
13365 MultiTemplateParamsArg TemplateParamLists,
13366 SourceLocation UsingLoc, UnqualifiedId &Name,
13367 const ParsedAttributesView &AttrList,
13368 TypeResult Type, Decl *DeclFromDeclSpec) {
13369 // Get the innermost enclosing declaration scope.
13370 S = S->getDeclParent();
13371
13372 if (Type.isInvalid())
13373 return nullptr;
13374
13375 bool Invalid = false;
13377 TypeSourceInfo *TInfo = nullptr;
13378 GetTypeFromParser(Type.get(), &TInfo);
13379
13380 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13381 return nullptr;
13382
13383 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13385 Invalid = true;
13387 TInfo->getTypeLoc().getBeginLoc());
13388 }
13389
13390 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13391 TemplateParamLists.size()
13393 : RedeclarationKind::ForVisibleRedeclaration);
13394 LookupName(Previous, S);
13395
13396 // Warn about shadowing the name of a template parameter.
13397 if (Previous.isSingleResult() &&
13398 Previous.getFoundDecl()->isTemplateParameter()) {
13399 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13400 Previous.clear();
13401 }
13402
13403 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13404 "name in alias declaration must be an identifier");
13406 Name.StartLocation,
13407 Name.Identifier, TInfo);
13408
13409 NewTD->setAccess(AS);
13410
13411 if (Invalid)
13412 NewTD->setInvalidDecl();
13413
13414 ProcessDeclAttributeList(S, NewTD, AttrList);
13415 AddPragmaAttributes(S, NewTD);
13416 ProcessAPINotes(NewTD);
13417
13419 Invalid |= NewTD->isInvalidDecl();
13420
13421 bool Redeclaration = false;
13422
13423 NamedDecl *NewND;
13424 if (TemplateParamLists.size()) {
13425 TypeAliasTemplateDecl *OldDecl = nullptr;
13426 TemplateParameterList *OldTemplateParams = nullptr;
13427
13428 if (TemplateParamLists.size() != 1) {
13429 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13430 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13431 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13432 Invalid = true;
13433 }
13434 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13435
13436 // Check that we can declare a template here.
13437 if (CheckTemplateDeclScope(S, TemplateParams))
13438 return nullptr;
13439
13440 // Only consider previous declarations in the same scope.
13441 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13442 /*ExplicitInstantiationOrSpecialization*/false);
13443 if (!Previous.empty()) {
13444 Redeclaration = true;
13445
13446 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13447 if (!OldDecl && !Invalid) {
13448 Diag(UsingLoc, diag::err_redefinition_different_kind)
13449 << Name.Identifier;
13450
13451 NamedDecl *OldD = Previous.getRepresentativeDecl();
13452 if (OldD->getLocation().isValid())
13453 Diag(OldD->getLocation(), diag::note_previous_definition);
13454
13455 Invalid = true;
13456 }
13457
13458 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13459 if (TemplateParameterListsAreEqual(TemplateParams,
13460 OldDecl->getTemplateParameters(),
13461 /*Complain=*/true,
13463 OldTemplateParams =
13465 else
13466 Invalid = true;
13467
13468 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13469 if (!Invalid &&
13471 NewTD->getUnderlyingType())) {
13472 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13473 // but we can't reasonably accept it.
13474 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13475 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13476 if (OldTD->getLocation().isValid())
13477 Diag(OldTD->getLocation(), diag::note_previous_definition);
13478 Invalid = true;
13479 }
13480 }
13481 }
13482
13483 // Merge any previous default template arguments into our parameters,
13484 // and check the parameter list.
13485 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13487 return nullptr;
13488
13489 TypeAliasTemplateDecl *NewDecl =
13491 Name.Identifier, TemplateParams,
13492 NewTD);
13493 NewTD->setDescribedAliasTemplate(NewDecl);
13494
13495 NewDecl->setAccess(AS);
13496
13497 if (Invalid)
13498 NewDecl->setInvalidDecl();
13499 else if (OldDecl) {
13500 NewDecl->setPreviousDecl(OldDecl);
13501 CheckRedeclarationInModule(NewDecl, OldDecl);
13502 }
13503
13504 NewND = NewDecl;
13505 } else {
13506 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13508 handleTagNumbering(TD, S);
13509 }
13510 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13511 NewND = NewTD;
13512 }
13513
13514 PushOnScopeChains(NewND, S);
13515 ActOnDocumentableDecl(NewND);
13516 return NewND;
13517}
13518
13520 SourceLocation AliasLoc,
13521 IdentifierInfo *Alias, CXXScopeSpec &SS,
13522 SourceLocation IdentLoc,
13523 IdentifierInfo *Ident) {
13524
13525 // Lookup the namespace name.
13526 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13527 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13528
13529 if (R.isAmbiguous())
13530 return nullptr;
13531
13532 if (R.empty()) {
13533 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13534 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13535 return nullptr;
13536 }
13537 }
13538 assert(!R.isAmbiguous() && !R.empty());
13540
13541 // Check if we have a previous declaration with the same name.
13542 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13543 RedeclarationKind::ForVisibleRedeclaration);
13544 LookupName(PrevR, S);
13545
13546 // Check we're not shadowing a template parameter.
13547 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13549 PrevR.clear();
13550 }
13551
13552 // Filter out any other lookup result from an enclosing scope.
13553 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13554 /*AllowInlineNamespace*/false);
13555
13556 // Find the previous declaration and check that we can redeclare it.
13557 NamespaceAliasDecl *Prev = nullptr;
13558 if (PrevR.isSingleResult()) {
13559 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13560 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13561 // We already have an alias with the same name that points to the same
13562 // namespace; check that it matches.
13563 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13564 Prev = AD;
13565 } else if (isVisible(PrevDecl)) {
13566 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13567 << Alias;
13568 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13569 << AD->getNamespace();
13570 return nullptr;
13571 }
13572 } else if (isVisible(PrevDecl)) {
13573 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13574 ? diag::err_redefinition
13575 : diag::err_redefinition_different_kind;
13576 Diag(AliasLoc, DiagID) << Alias;
13577 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13578 return nullptr;
13579 }
13580 }
13581
13582 // The use of a nested name specifier may trigger deprecation warnings.
13583 DiagnoseUseOfDecl(ND, IdentLoc);
13584
13586 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13587 Alias, SS.getWithLocInContext(Context),
13588 IdentLoc, ND);
13589 if (Prev)
13590 AliasDecl->setPreviousDecl(Prev);
13591
13593 return AliasDecl;
13594}
13595
13596namespace {
13597struct SpecialMemberExceptionSpecInfo
13598 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13601
13602 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13606 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13607
13608 bool visitBase(CXXBaseSpecifier *Base);
13609 bool visitField(FieldDecl *FD);
13610
13611 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13612 unsigned Quals);
13613
13614 void visitSubobjectCall(Subobject Subobj,
13616};
13617}
13618
13619bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13620 auto *RT = Base->getType()->getAs<RecordType>();
13621 if (!RT)
13622 return false;
13623
13624 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13625 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13626 if (auto *BaseCtor = SMOR.getMethod()) {
13627 visitSubobjectCall(Base, BaseCtor);
13628 return false;
13629 }
13630
13631 visitClassSubobject(BaseClass, Base, 0);
13632 return false;
13633}
13634
13635bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13637 FD->hasInClassInitializer()) {
13638 Expr *E = FD->getInClassInitializer();
13639 if (!E)
13640 // FIXME: It's a little wasteful to build and throw away a
13641 // CXXDefaultInitExpr here.
13642 // FIXME: We should have a single context note pointing at Loc, and
13643 // this location should be MD->getLocation() instead, since that's
13644 // the location where we actually use the default init expression.
13645 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13646 if (E)
13647 ExceptSpec.CalledExpr(E);
13648 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13649 ->getAs<RecordType>()) {
13650 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13651 FD->getType().getCVRQualifiers());
13652 }
13653 return false;
13654}
13655
13656void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13657 Subobject Subobj,
13658 unsigned Quals) {
13659 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13660 bool IsMutable = Field && Field->isMutable();
13661 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13662}
13663
13664void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13665 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13666 // Note, if lookup fails, it doesn't matter what exception specification we
13667 // choose because the special member will be deleted.
13668 if (CXXMethodDecl *MD = SMOR.getMethod())
13669 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13670}
13671
13673 llvm::APSInt Result;
13675 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13676 ExplicitSpec.setExpr(Converted.get());
13677 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13678 ExplicitSpec.setKind(Result.getBoolValue()
13681 return true;
13682 }
13684 return false;
13685}
13686
13689 if (!ExplicitExpr->isTypeDependent())
13691 return ES;
13692}
13693
13698 ComputingExceptionSpec CES(S, MD, Loc);
13699
13700 CXXRecordDecl *ClassDecl = MD->getParent();
13701
13702 // C++ [except.spec]p14:
13703 // An implicitly declared special member function (Clause 12) shall have an
13704 // exception-specification. [...]
13705 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13706 if (ClassDecl->isInvalidDecl())
13707 return Info.ExceptSpec;
13708
13709 // FIXME: If this diagnostic fires, we're probably missing a check for
13710 // attempting to resolve an exception specification before it's known
13711 // at a higher level.
13712 if (S.RequireCompleteType(MD->getLocation(),
13713 S.Context.getRecordType(ClassDecl),
13714 diag::err_exception_spec_incomplete_type))
13715 return Info.ExceptSpec;
13716
13717 // C++1z [except.spec]p7:
13718 // [Look for exceptions thrown by] a constructor selected [...] to
13719 // initialize a potentially constructed subobject,
13720 // C++1z [except.spec]p8:
13721 // The exception specification for an implicitly-declared destructor, or a
13722 // destructor without a noexcept-specifier, is potentially-throwing if and
13723 // only if any of the destructors for any of its potentially constructed
13724 // subojects is potentially throwing.
13725 // FIXME: We respect the first rule but ignore the "potentially constructed"
13726 // in the second rule to resolve a core issue (no number yet) that would have
13727 // us reject:
13728 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13729 // struct B : A {};
13730 // struct C : B { void f(); };
13731 // ... due to giving B::~B() a non-throwing exception specification.
13732 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13733 : Info.VisitAllBases);
13734
13735 return Info.ExceptSpec;
13736}
13737
13738namespace {
13739/// RAII object to register a special member as being currently declared.
13740struct DeclaringSpecialMember {
13741 Sema &S;
13743 Sema::ContextRAII SavedContext;
13744 bool WasAlreadyBeingDeclared;
13745
13746 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13747 : S(S), D(RD, CSM), SavedContext(S, RD) {
13748 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13749 if (WasAlreadyBeingDeclared)
13750 // This almost never happens, but if it does, ensure that our cache
13751 // doesn't contain a stale result.
13752 S.SpecialMemberCache.clear();
13753 else {
13754 // Register a note to be produced if we encounter an error while
13755 // declaring the special member.
13758 // FIXME: We don't have a location to use here. Using the class's
13759 // location maintains the fiction that we declare all special members
13760 // with the class, but (1) it's not clear that lying about that helps our
13761 // users understand what's going on, and (2) there may be outer contexts
13762 // on the stack (some of which are relevant) and printing them exposes
13763 // our lies.
13765 Ctx.Entity = RD;
13766 Ctx.SpecialMember = CSM;
13768 }
13769 }
13770 ~DeclaringSpecialMember() {
13771 if (!WasAlreadyBeingDeclared) {
13774 }
13775 }
13776
13777 /// Are we already trying to declare this special member?
13778 bool isAlreadyBeingDeclared() const {
13779 return WasAlreadyBeingDeclared;
13780 }
13781};
13782}
13783
13785 // Look up any existing declarations, but don't trigger declaration of all
13786 // implicit special members with this name.
13787 DeclarationName Name = FD->getDeclName();
13789 RedeclarationKind::ForExternalRedeclaration);
13790 for (auto *D : FD->getParent()->lookup(Name))
13791 if (auto *Acceptable = R.getAcceptableDecl(D))
13792 R.addDecl(Acceptable);
13793 R.resolveKind();
13795
13796 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13798}
13799
13800void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13801 QualType ResultTy,
13802 ArrayRef<QualType> Args) {
13803 // Build an exception specification pointing back at this constructor.
13805
13807 if (AS != LangAS::Default) {
13808 EPI.TypeQuals.addAddressSpace(AS);
13809 }
13810
13811 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13812 SpecialMem->setType(QT);
13813
13814 // During template instantiation of implicit special member functions we need
13815 // a reliable TypeSourceInfo for the function prototype in order to allow
13816 // functions to be substituted.
13818 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13819 TypeSourceInfo *TSI =
13821 SpecialMem->setTypeSourceInfo(TSI);
13822 }
13823}
13824
13826 CXXRecordDecl *ClassDecl) {
13827 // C++ [class.ctor]p5:
13828 // A default constructor for a class X is a constructor of class X
13829 // that can be called without an argument. If there is no
13830 // user-declared constructor for class X, a default constructor is
13831 // implicitly declared. An implicitly-declared default constructor
13832 // is an inline public member of its class.
13833 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13834 "Should not build implicit default constructor!");
13835
13836 DeclaringSpecialMember DSM(*this, ClassDecl,
13838 if (DSM.isAlreadyBeingDeclared())
13839 return nullptr;
13840
13842 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13843
13844 // Create the actual constructor declaration.
13845 CanQualType ClassType
13847 SourceLocation ClassLoc = ClassDecl->getLocation();
13848 DeclarationName Name
13850 DeclarationNameInfo NameInfo(Name, ClassLoc);
13852 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13853 /*TInfo=*/nullptr, ExplicitSpecifier(),
13854 getCurFPFeatures().isFPConstrained(),
13855 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13858 DefaultCon->setAccess(AS_public);
13859 DefaultCon->setDefaulted();
13860
13861 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13862
13863 if (getLangOpts().CUDA)
13865 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13866 /* ConstRHS */ false,
13867 /* Diagnose */ false);
13868
13869 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13870 // constructors is easy to compute.
13871 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13872
13873 // Note that we have declared this constructor.
13875
13876 Scope *S = getScopeForContext(ClassDecl);
13878
13879 if (ShouldDeleteSpecialMember(DefaultCon,
13881 SetDeclDeleted(DefaultCon, ClassLoc);
13882
13883 if (S)
13884 PushOnScopeChains(DefaultCon, S, false);
13885 ClassDecl->addDecl(DefaultCon);
13886
13887 return DefaultCon;
13888}
13889
13891 CXXConstructorDecl *Constructor) {
13892 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13893 !Constructor->doesThisDeclarationHaveABody() &&
13894 !Constructor->isDeleted()) &&
13895 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13896 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13897 return;
13898
13899 CXXRecordDecl *ClassDecl = Constructor->getParent();
13900 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13901 if (ClassDecl->isInvalidDecl()) {
13902 return;
13903 }
13904
13905 SynthesizedFunctionScope Scope(*this, Constructor);
13906
13907 // The exception specification is needed because we are defining the
13908 // function.
13909 ResolveExceptionSpec(CurrentLocation,
13910 Constructor->getType()->castAs<FunctionProtoType>());
13911 MarkVTableUsed(CurrentLocation, ClassDecl);
13912
13913 // Add a context note for diagnostics produced after this point.
13914 Scope.addContextNote(CurrentLocation);
13915
13916 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13917 Constructor->setInvalidDecl();
13918 return;
13919 }
13920
13921 SourceLocation Loc = Constructor->getEndLoc().isValid()
13922 ? Constructor->getEndLoc()
13923 : Constructor->getLocation();
13924 Constructor->setBody(new (Context) CompoundStmt(Loc));
13925 Constructor->markUsed(Context);
13926
13928 L->CompletedImplicitDefinition(Constructor);
13929 }
13930
13931 DiagnoseUninitializedFields(*this, Constructor);
13932}
13933
13935 // Perform any delayed checks on exception specifications.
13937}
13938
13939/// Find or create the fake constructor we synthesize to model constructing an
13940/// object of a derived class via a constructor of a base class.
13943 CXXConstructorDecl *BaseCtor,
13945 CXXRecordDecl *Derived = Shadow->getParent();
13946 SourceLocation UsingLoc = Shadow->getLocation();
13947
13948 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13949 // For now we use the name of the base class constructor as a member of the
13950 // derived class to indicate a (fake) inherited constructor name.
13951 DeclarationName Name = BaseCtor->getDeclName();
13952
13953 // Check to see if we already have a fake constructor for this inherited
13954 // constructor call.
13955 for (NamedDecl *Ctor : Derived->lookup(Name))
13956 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13957 ->getInheritedConstructor()
13958 .getConstructor(),
13959 BaseCtor))
13960 return cast<CXXConstructorDecl>(Ctor);
13961
13962 DeclarationNameInfo NameInfo(Name, UsingLoc);
13963 TypeSourceInfo *TInfo =
13964 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13965 FunctionProtoTypeLoc ProtoLoc =
13967
13968 // Check the inherited constructor is valid and find the list of base classes
13969 // from which it was inherited.
13970 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13971
13972 bool Constexpr = BaseCtor->isConstexpr() &&
13975 false, BaseCtor, &ICI);
13976
13978 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13979 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13980 /*isInline=*/true,
13981 /*isImplicitlyDeclared=*/true,
13983 InheritedConstructor(Shadow, BaseCtor),
13984 BaseCtor->getTrailingRequiresClause());
13985 if (Shadow->isInvalidDecl())
13986 DerivedCtor->setInvalidDecl();
13987
13988 // Build an unevaluated exception specification for this fake constructor.
13989 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13992 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13993 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13994 FPT->getParamTypes(), EPI));
13995
13996 // Build the parameter declarations.
13998 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13999 TypeSourceInfo *TInfo =
14002 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14003 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14004 PD->setScopeInfo(0, I);
14005 PD->setImplicit();
14006 // Ensure attributes are propagated onto parameters (this matters for
14007 // format, pass_object_size, ...).
14008 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14009 ParamDecls.push_back(PD);
14010 ProtoLoc.setParam(I, PD);
14011 }
14012
14013 // Set up the new constructor.
14014 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14015 DerivedCtor->setAccess(BaseCtor->getAccess());
14016 DerivedCtor->setParams(ParamDecls);
14017 Derived->addDecl(DerivedCtor);
14018
14019 if (ShouldDeleteSpecialMember(DerivedCtor,
14021 SetDeclDeleted(DerivedCtor, UsingLoc);
14022
14023 return DerivedCtor;
14024}
14025
14027 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14030 &ICI,
14031 /*Diagnose*/ true);
14032}
14033
14035 CXXConstructorDecl *Constructor) {
14036 CXXRecordDecl *ClassDecl = Constructor->getParent();
14037 assert(Constructor->getInheritedConstructor() &&
14038 !Constructor->doesThisDeclarationHaveABody() &&
14039 !Constructor->isDeleted());
14040 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14041 return;
14042
14043 // Initializations are performed "as if by a defaulted default constructor",
14044 // so enter the appropriate scope.
14045 SynthesizedFunctionScope Scope(*this, Constructor);
14046
14047 // The exception specification is needed because we are defining the
14048 // function.
14049 ResolveExceptionSpec(CurrentLocation,
14050 Constructor->getType()->castAs<FunctionProtoType>());
14051 MarkVTableUsed(CurrentLocation, ClassDecl);
14052
14053 // Add a context note for diagnostics produced after this point.
14054 Scope.addContextNote(CurrentLocation);
14055
14057 Constructor->getInheritedConstructor().getShadowDecl();
14058 CXXConstructorDecl *InheritedCtor =
14059 Constructor->getInheritedConstructor().getConstructor();
14060
14061 // [class.inhctor.init]p1:
14062 // initialization proceeds as if a defaulted default constructor is used to
14063 // initialize the D object and each base class subobject from which the
14064 // constructor was inherited
14065
14066 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14067 CXXRecordDecl *RD = Shadow->getParent();
14068 SourceLocation InitLoc = Shadow->getLocation();
14069
14070 // Build explicit initializers for all base classes from which the
14071 // constructor was inherited.
14073 for (bool VBase : {false, true}) {
14074 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14075 if (B.isVirtual() != VBase)
14076 continue;
14077
14078 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14079 if (!BaseRD)
14080 continue;
14081
14082 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14083 if (!BaseCtor.first)
14084 continue;
14085
14086 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14088 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14089
14090 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14091 Inits.push_back(new (Context) CXXCtorInitializer(
14092 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14093 SourceLocation()));
14094 }
14095 }
14096
14097 // We now proceed as if for a defaulted default constructor, with the relevant
14098 // initializers replaced.
14099
14100 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14101 Constructor->setInvalidDecl();
14102 return;
14103 }
14104
14105 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14106 Constructor->markUsed(Context);
14107
14109 L->CompletedImplicitDefinition(Constructor);
14110 }
14111
14112 DiagnoseUninitializedFields(*this, Constructor);
14113}
14114
14116 // C++ [class.dtor]p2:
14117 // If a class has no user-declared destructor, a destructor is
14118 // declared implicitly. An implicitly-declared destructor is an
14119 // inline public member of its class.
14120 assert(ClassDecl->needsImplicitDestructor());
14121
14122 DeclaringSpecialMember DSM(*this, ClassDecl,
14124 if (DSM.isAlreadyBeingDeclared())
14125 return nullptr;
14126
14128 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14129
14130 // Create the actual destructor declaration.
14131 CanQualType ClassType
14133 SourceLocation ClassLoc = ClassDecl->getLocation();
14134 DeclarationName Name
14136 DeclarationNameInfo NameInfo(Name, ClassLoc);
14138 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14139 getCurFPFeatures().isFPConstrained(),
14140 /*isInline=*/true,
14141 /*isImplicitlyDeclared=*/true,
14144 Destructor->setAccess(AS_public);
14145 Destructor->setDefaulted();
14146
14147 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14148
14149 if (getLangOpts().CUDA)
14152 /* ConstRHS */ false,
14153 /* Diagnose */ false);
14154
14155 // We don't need to use SpecialMemberIsTrivial here; triviality for
14156 // destructors is easy to compute.
14157 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14158 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14159 ClassDecl->hasTrivialDestructorForCall());
14160
14161 // Note that we have declared this destructor.
14163
14164 Scope *S = getScopeForContext(ClassDecl);
14166
14167 // We can't check whether an implicit destructor is deleted before we complete
14168 // the definition of the class, because its validity depends on the alignment
14169 // of the class. We'll check this from ActOnFields once the class is complete.
14170 if (ClassDecl->isCompleteDefinition() &&
14172 SetDeclDeleted(Destructor, ClassLoc);
14173
14174 // Introduce this destructor into its scope.
14175 if (S)
14176 PushOnScopeChains(Destructor, S, false);
14177 ClassDecl->addDecl(Destructor);
14178
14179 return Destructor;
14180}
14181
14184 assert((Destructor->isDefaulted() &&
14185 !Destructor->doesThisDeclarationHaveABody() &&
14186 !Destructor->isDeleted()) &&
14187 "DefineImplicitDestructor - call it for implicit default dtor");
14188 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14189 return;
14190
14191 CXXRecordDecl *ClassDecl = Destructor->getParent();
14192 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14193
14195
14196 // The exception specification is needed because we are defining the
14197 // function.
14198 ResolveExceptionSpec(CurrentLocation,
14199 Destructor->getType()->castAs<FunctionProtoType>());
14200 MarkVTableUsed(CurrentLocation, ClassDecl);
14201
14202 // Add a context note for diagnostics produced after this point.
14203 Scope.addContextNote(CurrentLocation);
14204
14206 Destructor->getParent());
14207
14209 Destructor->setInvalidDecl();
14210 return;
14211 }
14212
14213 SourceLocation Loc = Destructor->getEndLoc().isValid()
14214 ? Destructor->getEndLoc()
14215 : Destructor->getLocation();
14216 Destructor->setBody(new (Context) CompoundStmt(Loc));
14217 Destructor->markUsed(Context);
14218
14220 L->CompletedImplicitDefinition(Destructor);
14221 }
14222}
14223
14226 if (Destructor->isInvalidDecl())
14227 return;
14228
14229 CXXRecordDecl *ClassDecl = Destructor->getParent();
14231 "implicit complete dtors unneeded outside MS ABI");
14232 assert(ClassDecl->getNumVBases() > 0 &&
14233 "complete dtor only exists for classes with vbases");
14234
14236
14237 // Add a context note for diagnostics produced after this point.
14238 Scope.addContextNote(CurrentLocation);
14239
14240 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14241}
14242
14244 // If the context is an invalid C++ class, just suppress these checks.
14245 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14246 if (Record->isInvalidDecl()) {
14249 return;
14250 }
14252 }
14253}
14254
14257
14258 if (!DelayedDllExportMemberFunctions.empty()) {
14260 std::swap(DelayedDllExportMemberFunctions, WorkList);
14261 for (CXXMethodDecl *M : WorkList) {
14262 DefineDefaultedFunction(*this, M, M->getLocation());
14263
14264 // Pass the method to the consumer to get emitted. This is not necessary
14265 // for explicit instantiation definitions, as they will get emitted
14266 // anyway.
14267 if (M->getParent()->getTemplateSpecializationKind() !=
14270 }
14271 }
14272}
14273
14275 if (!DelayedDllExportClasses.empty()) {
14276 // Calling ReferenceDllExportedMembers might cause the current function to
14277 // be called again, so use a local copy of DelayedDllExportClasses.
14279 std::swap(DelayedDllExportClasses, WorkList);
14280 for (CXXRecordDecl *Class : WorkList)
14282 }
14283}
14284
14286 assert(getLangOpts().CPlusPlus11 &&
14287 "adjusting dtor exception specs was introduced in c++11");
14288
14289 if (Destructor->isDependentContext())
14290 return;
14291
14292 // C++11 [class.dtor]p3:
14293 // A declaration of a destructor that does not have an exception-
14294 // specification is implicitly considered to have the same exception-
14295 // specification as an implicit declaration.
14296 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14297 if (DtorType->hasExceptionSpec())
14298 return;
14299
14300 // Replace the destructor's type, building off the existing one. Fortunately,
14301 // the only thing of interest in the destructor type is its extended info.
14302 // The return and arguments are fixed.
14303 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14306 Destructor->setType(
14307 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14308
14309 // FIXME: If the destructor has a body that could throw, and the newly created
14310 // spec doesn't allow exceptions, we should emit a warning, because this
14311 // change in behavior can break conforming C++03 programs at runtime.
14312 // However, we don't have a body or an exception specification yet, so it
14313 // needs to be done somewhere else.
14314}
14315
14316namespace {
14317/// An abstract base class for all helper classes used in building the
14318// copy/move operators. These classes serve as factory functions and help us
14319// avoid using the same Expr* in the AST twice.
14320class ExprBuilder {
14321 ExprBuilder(const ExprBuilder&) = delete;
14322 ExprBuilder &operator=(const ExprBuilder&) = delete;
14323
14324protected:
14325 static Expr *assertNotNull(Expr *E) {
14326 assert(E && "Expression construction must not fail.");
14327 return E;
14328 }
14329
14330public:
14331 ExprBuilder() {}
14332 virtual ~ExprBuilder() {}
14333
14334 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14335};
14336
14337class RefBuilder: public ExprBuilder {
14338 VarDecl *Var;
14339 QualType VarType;
14340
14341public:
14342 Expr *build(Sema &S, SourceLocation Loc) const override {
14343 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14344 }
14345
14346 RefBuilder(VarDecl *Var, QualType VarType)
14347 : Var(Var), VarType(VarType) {}
14348};
14349
14350class ThisBuilder: public ExprBuilder {
14351public:
14352 Expr *build(Sema &S, SourceLocation Loc) const override {
14353 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14354 }
14355};
14356
14357class CastBuilder: public ExprBuilder {
14358 const ExprBuilder &Builder;
14359 QualType Type;
14361 const CXXCastPath &Path;
14362
14363public:
14364 Expr *build(Sema &S, SourceLocation Loc) const override {
14365 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14366 CK_UncheckedDerivedToBase, Kind,
14367 &Path).get());
14368 }
14369
14370 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14371 const CXXCastPath &Path)
14372 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14373};
14374
14375class DerefBuilder: public ExprBuilder {
14376 const ExprBuilder &Builder;
14377
14378public:
14379 Expr *build(Sema &S, SourceLocation Loc) const override {
14380 return assertNotNull(
14381 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14382 }
14383
14384 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14385};
14386
14387class MemberBuilder: public ExprBuilder {
14388 const ExprBuilder &Builder;
14389 QualType Type;
14390 CXXScopeSpec SS;
14391 bool IsArrow;
14392 LookupResult &MemberLookup;
14393
14394public:
14395 Expr *build(Sema &S, SourceLocation Loc) const override {
14396 return assertNotNull(S.BuildMemberReferenceExpr(
14397 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14398 nullptr, MemberLookup, nullptr, nullptr).get());
14399 }
14400
14401 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14402 LookupResult &MemberLookup)
14403 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14404 MemberLookup(MemberLookup) {}
14405};
14406
14407class MoveCastBuilder: public ExprBuilder {
14408 const ExprBuilder &Builder;
14409
14410public:
14411 Expr *build(Sema &S, SourceLocation Loc) const override {
14412 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14413 }
14414
14415 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14416};
14417
14418class LvalueConvBuilder: public ExprBuilder {
14419 const ExprBuilder &Builder;
14420
14421public:
14422 Expr *build(Sema &S, SourceLocation Loc) const override {
14423 return assertNotNull(
14424 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14425 }
14426
14427 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14428};
14429
14430class SubscriptBuilder: public ExprBuilder {
14431 const ExprBuilder &Base;
14432 const ExprBuilder &Index;
14433
14434public:
14435 Expr *build(Sema &S, SourceLocation Loc) const override {
14436 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14437 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14438 }
14439
14440 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14441 : Base(Base), Index(Index) {}
14442};
14443
14444} // end anonymous namespace
14445
14446/// When generating a defaulted copy or move assignment operator, if a field
14447/// should be copied with __builtin_memcpy rather than via explicit assignments,
14448/// do so. This optimization only applies for arrays of scalars, and for arrays
14449/// of class type where the selected copy/move-assignment operator is trivial.
14450static StmtResult
14452 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14453 // Compute the size of the memory buffer to be copied.
14454 QualType SizeType = S.Context.getSizeType();
14455 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14457
14458 // Take the address of the field references for "from" and "to". We
14459 // directly construct UnaryOperators here because semantic analysis
14460 // does not permit us to take the address of an xvalue.
14461 Expr *From = FromB.build(S, Loc);
14462 From = UnaryOperator::Create(
14463 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14465 Expr *To = ToB.build(S, Loc);
14467 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14469
14470 const Type *E = T->getBaseElementTypeUnsafe();
14471 bool NeedsCollectableMemCpy =
14472 E->isRecordType() &&
14473 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14474
14475 // Create a reference to the __builtin_objc_memmove_collectable function
14476 StringRef MemCpyName = NeedsCollectableMemCpy ?
14477 "__builtin_objc_memmove_collectable" :
14478 "__builtin_memcpy";
14479 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14481 S.LookupName(R, S.TUScope, true);
14482
14483 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14484 if (!MemCpy)
14485 // Something went horribly wrong earlier, and we will have complained
14486 // about it.
14487 return StmtError();
14488
14489 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14490 VK_PRValue, Loc, nullptr);
14491 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14492
14493 Expr *CallArgs[] = {
14494 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14495 };
14496 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14497 Loc, CallArgs, Loc);
14498
14499 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14500 return Call.getAs<Stmt>();
14501}
14502
14503/// Builds a statement that copies/moves the given entity from \p From to
14504/// \c To.
14505///
14506/// This routine is used to copy/move the members of a class with an
14507/// implicitly-declared copy/move assignment operator. When the entities being
14508/// copied are arrays, this routine builds for loops to copy them.
14509///
14510/// \param S The Sema object used for type-checking.
14511///
14512/// \param Loc The location where the implicit copy/move is being generated.
14513///
14514/// \param T The type of the expressions being copied/moved. Both expressions
14515/// must have this type.
14516///
14517/// \param To The expression we are copying/moving to.
14518///
14519/// \param From The expression we are copying/moving from.
14520///
14521/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14522/// Otherwise, it's a non-static member subobject.
14523///
14524/// \param Copying Whether we're copying or moving.
14525///
14526/// \param Depth Internal parameter recording the depth of the recursion.
14527///
14528/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14529/// if a memcpy should be used instead.
14530static StmtResult
14532 const ExprBuilder &To, const ExprBuilder &From,
14533 bool CopyingBaseSubobject, bool Copying,
14534 unsigned Depth = 0) {
14535 // C++11 [class.copy]p28:
14536 // Each subobject is assigned in the manner appropriate to its type:
14537 //
14538 // - if the subobject is of class type, as if by a call to operator= with
14539 // the subobject as the object expression and the corresponding
14540 // subobject of x as a single function argument (as if by explicit
14541 // qualification; that is, ignoring any possible virtual overriding
14542 // functions in more derived classes);
14543 //
14544 // C++03 [class.copy]p13:
14545 // - if the subobject is of class type, the copy assignment operator for
14546 // the class is used (as if by explicit qualification; that is,
14547 // ignoring any possible virtual overriding functions in more derived
14548 // classes);
14549 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14550 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14551
14552 // Look for operator=.
14553 DeclarationName Name
14555 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14556 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14557
14558 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14559 // operator.
14560 if (!S.getLangOpts().CPlusPlus11) {
14561 LookupResult::Filter F = OpLookup.makeFilter();
14562 while (F.hasNext()) {
14563 NamedDecl *D = F.next();
14564 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14565 if (Method->isCopyAssignmentOperator() ||
14566 (!Copying && Method->isMoveAssignmentOperator()))
14567 continue;
14568
14569 F.erase();
14570 }
14571 F.done();
14572 }
14573
14574 // Suppress the protected check (C++ [class.protected]) for each of the
14575 // assignment operators we found. This strange dance is required when
14576 // we're assigning via a base classes's copy-assignment operator. To
14577 // ensure that we're getting the right base class subobject (without
14578 // ambiguities), we need to cast "this" to that subobject type; to
14579 // ensure that we don't go through the virtual call mechanism, we need
14580 // to qualify the operator= name with the base class (see below). However,
14581 // this means that if the base class has a protected copy assignment
14582 // operator, the protected member access check will fail. So, we
14583 // rewrite "protected" access to "public" access in this case, since we
14584 // know by construction that we're calling from a derived class.
14585 if (CopyingBaseSubobject) {
14586 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14587 L != LEnd; ++L) {
14588 if (L.getAccess() == AS_protected)
14589 L.setAccess(AS_public);
14590 }
14591 }
14592
14593 // Create the nested-name-specifier that will be used to qualify the
14594 // reference to operator=; this is required to suppress the virtual
14595 // call mechanism.
14596 CXXScopeSpec SS;
14597 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14598 SS.MakeTrivial(S.Context,
14599 NestedNameSpecifier::Create(S.Context, nullptr, false,
14600 CanonicalT),
14601 Loc);
14602
14603 // Create the reference to operator=.
14604 ExprResult OpEqualRef
14605 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14606 SS, /*TemplateKWLoc=*/SourceLocation(),
14607 /*FirstQualifierInScope=*/nullptr,
14608 OpLookup,
14609 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14610 /*SuppressQualifierCheck=*/true);
14611 if (OpEqualRef.isInvalid())
14612 return StmtError();
14613
14614 // Build the call to the assignment operator.
14615
14616 Expr *FromInst = From.build(S, Loc);
14617 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14618 OpEqualRef.getAs<Expr>(),
14619 Loc, FromInst, Loc);
14620 if (Call.isInvalid())
14621 return StmtError();
14622
14623 // If we built a call to a trivial 'operator=' while copying an array,
14624 // bail out. We'll replace the whole shebang with a memcpy.
14625 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14626 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14627 return StmtResult((Stmt*)nullptr);
14628
14629 // Convert to an expression-statement, and clean up any produced
14630 // temporaries.
14631 return S.ActOnExprStmt(Call);
14632 }
14633
14634 // - if the subobject is of scalar type, the built-in assignment
14635 // operator is used.
14637 if (!ArrayTy) {
14638 ExprResult Assignment = S.CreateBuiltinBinOp(
14639 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14640 if (Assignment.isInvalid())
14641 return StmtError();
14642 return S.ActOnExprStmt(Assignment);
14643 }
14644
14645 // - if the subobject is an array, each element is assigned, in the
14646 // manner appropriate to the element type;
14647
14648 // Construct a loop over the array bounds, e.g.,
14649 //
14650 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14651 //
14652 // that will copy each of the array elements.
14653 QualType SizeType = S.Context.getSizeType();
14654
14655 // Create the iteration variable.
14656 IdentifierInfo *IterationVarName = nullptr;
14657 {
14658 SmallString<8> Str;
14659 llvm::raw_svector_ostream OS(Str);
14660 OS << "__i" << Depth;
14661 IterationVarName = &S.Context.Idents.get(OS.str());
14662 }
14663 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14664 IterationVarName, SizeType,
14666 SC_None);
14667
14668 // Initialize the iteration variable to zero.
14669 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14670 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14671
14672 // Creates a reference to the iteration variable.
14673 RefBuilder IterationVarRef(IterationVar, SizeType);
14674 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14675
14676 // Create the DeclStmt that holds the iteration variable.
14677 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14678
14679 // Subscript the "from" and "to" expressions with the iteration variable.
14680 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14681 MoveCastBuilder FromIndexMove(FromIndexCopy);
14682 const ExprBuilder *FromIndex;
14683 if (Copying)
14684 FromIndex = &FromIndexCopy;
14685 else
14686 FromIndex = &FromIndexMove;
14687
14688 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14689
14690 // Build the copy/move for an individual element of the array.
14693 ToIndex, *FromIndex, CopyingBaseSubobject,
14694 Copying, Depth + 1);
14695 // Bail out if copying fails or if we determined that we should use memcpy.
14696 if (Copy.isInvalid() || !Copy.get())
14697 return Copy;
14698
14699 // Create the comparison against the array bound.
14700 llvm::APInt Upper
14701 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14702 Expr *Comparison = BinaryOperator::Create(
14703 S.Context, IterationVarRefRVal.build(S, Loc),
14704 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14707
14708 // Create the pre-increment of the iteration variable. We can determine
14709 // whether the increment will overflow based on the value of the array
14710 // bound.
14711 Expr *Increment = UnaryOperator::Create(
14712 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14713 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14714
14715 // Construct the loop that copies all elements of this array.
14716 return S.ActOnForStmt(
14717 Loc, Loc, InitStmt,
14718 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14719 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14720}
14721
14722static StmtResult
14724 const ExprBuilder &To, const ExprBuilder &From,
14725 bool CopyingBaseSubobject, bool Copying) {
14726 // Maybe we should use a memcpy?
14727 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14728 T.isTriviallyCopyableType(S.Context))
14729 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14730
14732 CopyingBaseSubobject,
14733 Copying, 0));
14734
14735 // If we ended up picking a trivial assignment operator for an array of a
14736 // non-trivially-copyable class type, just emit a memcpy.
14737 if (!Result.isInvalid() && !Result.get())
14738 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14739
14740 return Result;
14741}
14742
14744 // Note: The following rules are largely analoguous to the copy
14745 // constructor rules. Note that virtual bases are not taken into account
14746 // for determining the argument type of the operator. Note also that
14747 // operators taking an object instead of a reference are allowed.
14748 assert(ClassDecl->needsImplicitCopyAssignment());
14749
14750 DeclaringSpecialMember DSM(*this, ClassDecl,
14752 if (DSM.isAlreadyBeingDeclared())
14753 return nullptr;
14754
14755 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14757 ArgType, nullptr);
14759 if (AS != LangAS::Default)
14760 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14761 QualType RetType = Context.getLValueReferenceType(ArgType);
14762 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14763 if (Const)
14764 ArgType = ArgType.withConst();
14765
14766 ArgType = Context.getLValueReferenceType(ArgType);
14767
14769 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14770
14771 // An implicitly-declared copy assignment operator is an inline public
14772 // member of its class.
14774 SourceLocation ClassLoc = ClassDecl->getLocation();
14775 DeclarationNameInfo NameInfo(Name, ClassLoc);
14777 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14778 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14779 getCurFPFeatures().isFPConstrained(),
14780 /*isInline=*/true,
14782 SourceLocation());
14783 CopyAssignment->setAccess(AS_public);
14784 CopyAssignment->setDefaulted();
14785 CopyAssignment->setImplicit();
14786
14787 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14788
14789 if (getLangOpts().CUDA)
14792 /* ConstRHS */ Const,
14793 /* Diagnose */ false);
14794
14795 // Add the parameter to the operator.
14797 ClassLoc, ClassLoc,
14798 /*Id=*/nullptr, ArgType,
14799 /*TInfo=*/nullptr, SC_None,
14800 nullptr);
14801 CopyAssignment->setParams(FromParam);
14802
14803 CopyAssignment->setTrivial(
14807 : ClassDecl->hasTrivialCopyAssignment());
14808
14809 // Note that we have added this copy-assignment operator.
14811
14812 Scope *S = getScopeForContext(ClassDecl);
14814
14818 SetDeclDeleted(CopyAssignment, ClassLoc);
14819 }
14820
14821 if (S)
14823 ClassDecl->addDecl(CopyAssignment);
14824
14825 return CopyAssignment;
14826}
14827
14828/// Diagnose an implicit copy operation for a class which is odr-used, but
14829/// which is deprecated because the class has a user-declared copy constructor,
14830/// copy assignment operator, or destructor.
14832 assert(CopyOp->isImplicit());
14833
14834 CXXRecordDecl *RD = CopyOp->getParent();
14835 CXXMethodDecl *UserDeclaredOperation = nullptr;
14836
14837 if (RD->hasUserDeclaredDestructor()) {
14838 UserDeclaredOperation = RD->getDestructor();
14839 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14841 // Find any user-declared copy constructor.
14842 for (auto *I : RD->ctors()) {
14843 if (I->isCopyConstructor()) {
14844 UserDeclaredOperation = I;
14845 break;
14846 }
14847 }
14848 assert(UserDeclaredOperation);
14849 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14851 // Find any user-declared move assignment operator.
14852 for (auto *I : RD->methods()) {
14853 if (I->isCopyAssignmentOperator()) {
14854 UserDeclaredOperation = I;
14855 break;
14856 }
14857 }
14858 assert(UserDeclaredOperation);
14859 }
14860
14861 if (UserDeclaredOperation) {
14862 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14863 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14864 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14865 unsigned DiagID =
14866 (UDOIsUserProvided && UDOIsDestructor)
14867 ? diag::warn_deprecated_copy_with_user_provided_dtor
14868 : (UDOIsUserProvided && !UDOIsDestructor)
14869 ? diag::warn_deprecated_copy_with_user_provided_copy
14870 : (!UDOIsUserProvided && UDOIsDestructor)
14871 ? diag::warn_deprecated_copy_with_dtor
14872 : diag::warn_deprecated_copy;
14873 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14874 << RD << IsCopyAssignment;
14875 }
14876}
14877
14879 CXXMethodDecl *CopyAssignOperator) {
14880 assert((CopyAssignOperator->isDefaulted() &&
14881 CopyAssignOperator->isOverloadedOperator() &&
14882 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14883 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14884 !CopyAssignOperator->isDeleted()) &&
14885 "DefineImplicitCopyAssignment called for wrong function");
14886 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14887 return;
14888
14889 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14890 if (ClassDecl->isInvalidDecl()) {
14891 CopyAssignOperator->setInvalidDecl();
14892 return;
14893 }
14894
14895 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14896
14897 // The exception specification is needed because we are defining the
14898 // function.
14899 ResolveExceptionSpec(CurrentLocation,
14900 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14901
14902 // Add a context note for diagnostics produced after this point.
14903 Scope.addContextNote(CurrentLocation);
14904
14905 // C++11 [class.copy]p18:
14906 // The [definition of an implicitly declared copy assignment operator] is
14907 // deprecated if the class has a user-declared copy constructor or a
14908 // user-declared destructor.
14909 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14910 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14911
14912 // C++0x [class.copy]p30:
14913 // The implicitly-defined or explicitly-defaulted copy assignment operator
14914 // for a non-union class X performs memberwise copy assignment of its
14915 // subobjects. The direct base classes of X are assigned first, in the
14916 // order of their declaration in the base-specifier-list, and then the
14917 // immediate non-static data members of X are assigned, in the order in
14918 // which they were declared in the class definition.
14919
14920 // The statements that form the synthesized function body.
14921 SmallVector<Stmt*, 8> Statements;
14922
14923 // The parameter for the "other" object, which we are copying from.
14924 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
14925 Qualifiers OtherQuals = Other->getType().getQualifiers();
14926 QualType OtherRefType = Other->getType();
14927 if (OtherRefType->isLValueReferenceType()) {
14928 OtherRefType = OtherRefType->getPointeeType();
14929 OtherQuals = OtherRefType.getQualifiers();
14930 }
14931
14932 // Our location for everything implicitly-generated.
14933 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14934 ? CopyAssignOperator->getEndLoc()
14935 : CopyAssignOperator->getLocation();
14936
14937 // Builds a DeclRefExpr for the "other" object.
14938 RefBuilder OtherRef(Other, OtherRefType);
14939
14940 // Builds the function object parameter.
14941 std::optional<ThisBuilder> This;
14942 std::optional<DerefBuilder> DerefThis;
14943 std::optional<RefBuilder> ExplicitObject;
14944 bool IsArrow = false;
14945 QualType ObjectType;
14946 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
14947 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
14948 if (ObjectType->isReferenceType())
14949 ObjectType = ObjectType->getPointeeType();
14950 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
14951 } else {
14952 ObjectType = getCurrentThisType();
14953 This.emplace();
14954 DerefThis.emplace(*This);
14955 IsArrow = !LangOpts.HLSL;
14956 }
14957 ExprBuilder &ObjectParameter =
14958 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14959 : static_cast<ExprBuilder &>(*This);
14960
14961 // Assign base classes.
14962 bool Invalid = false;
14963 for (auto &Base : ClassDecl->bases()) {
14964 // Form the assignment:
14965 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14966 QualType BaseType = Base.getType().getUnqualifiedType();
14967 if (!BaseType->isRecordType()) {
14968 Invalid = true;
14969 continue;
14970 }
14971
14972 CXXCastPath BasePath;
14973 BasePath.push_back(&Base);
14974
14975 // Construct the "from" expression, which is an implicit cast to the
14976 // appropriately-qualified base type.
14977 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14978 VK_LValue, BasePath);
14979
14980 // Dereference "this".
14981 CastBuilder To(
14982 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14983 : static_cast<ExprBuilder &>(*DerefThis),
14984 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
14985 VK_LValue, BasePath);
14986
14987 // Build the copy.
14988 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14989 To, From,
14990 /*CopyingBaseSubobject=*/true,
14991 /*Copying=*/true);
14992 if (Copy.isInvalid()) {
14993 CopyAssignOperator->setInvalidDecl();
14994 return;
14995 }
14996
14997 // Success! Record the copy.
14998 Statements.push_back(Copy.getAs<Expr>());
14999 }
15000
15001 // Assign non-static members.
15002 for (auto *Field : ClassDecl->fields()) {
15003 // FIXME: We should form some kind of AST representation for the implied
15004 // memcpy in a union copy operation.
15005 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15006 continue;
15007
15008 if (Field->isInvalidDecl()) {
15009 Invalid = true;
15010 continue;
15011 }
15012
15013 // Check for members of reference type; we can't copy those.
15014 if (Field->getType()->isReferenceType()) {
15015 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15016 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15017 Diag(Field->getLocation(), diag::note_declared_at);
15018 Invalid = true;
15019 continue;
15020 }
15021
15022 // Check for members of const-qualified, non-class type.
15023 QualType BaseType = Context.getBaseElementType(Field->getType());
15024 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15025 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15026 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15027 Diag(Field->getLocation(), diag::note_declared_at);
15028 Invalid = true;
15029 continue;
15030 }
15031
15032 // Suppress assigning zero-width bitfields.
15033 if (Field->isZeroLengthBitField(Context))
15034 continue;
15035
15036 QualType FieldType = Field->getType().getNonReferenceType();
15037 if (FieldType->isIncompleteArrayType()) {
15038 assert(ClassDecl->hasFlexibleArrayMember() &&
15039 "Incomplete array type is not valid");
15040 continue;
15041 }
15042
15043 // Build references to the field in the object we're copying from and to.
15044 CXXScopeSpec SS; // Intentionally empty
15045 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15047 MemberLookup.addDecl(Field);
15048 MemberLookup.resolveKind();
15049
15050 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15051 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15052 // Build the copy of this field.
15053 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15054 To, From,
15055 /*CopyingBaseSubobject=*/false,
15056 /*Copying=*/true);
15057 if (Copy.isInvalid()) {
15058 CopyAssignOperator->setInvalidDecl();
15059 return;
15060 }
15061
15062 // Success! Record the copy.
15063 Statements.push_back(Copy.getAs<Stmt>());
15064 }
15065
15066 if (!Invalid) {
15067 // Add a "return *this;"
15068 Expr *ThisExpr =
15069 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15070 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15071 : static_cast<ExprBuilder &>(*DerefThis))
15072 .build(*this, Loc);
15073 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15074 if (Return.isInvalid())
15075 Invalid = true;
15076 else
15077 Statements.push_back(Return.getAs<Stmt>());
15078 }
15079
15080 if (Invalid) {
15081 CopyAssignOperator->setInvalidDecl();
15082 return;
15083 }
15084
15085 StmtResult Body;
15086 {
15087 CompoundScopeRAII CompoundScope(*this);
15088 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15089 /*isStmtExpr=*/false);
15090 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15091 }
15092 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15093 CopyAssignOperator->markUsed(Context);
15094
15096 L->CompletedImplicitDefinition(CopyAssignOperator);
15097 }
15098}
15099
15101 assert(ClassDecl->needsImplicitMoveAssignment());
15102
15103 DeclaringSpecialMember DSM(*this, ClassDecl,
15105 if (DSM.isAlreadyBeingDeclared())
15106 return nullptr;
15107
15108 // Note: The following rules are largely analoguous to the move
15109 // constructor rules.
15110
15111 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15113 ArgType, nullptr);
15115 if (AS != LangAS::Default)
15116 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15117 QualType RetType = Context.getLValueReferenceType(ArgType);
15118 ArgType = Context.getRValueReferenceType(ArgType);
15119
15121 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15122
15123 // An implicitly-declared move assignment operator is an inline public
15124 // member of its class.
15126 SourceLocation ClassLoc = ClassDecl->getLocation();
15127 DeclarationNameInfo NameInfo(Name, ClassLoc);
15129 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15130 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15131 getCurFPFeatures().isFPConstrained(),
15132 /*isInline=*/true,
15134 SourceLocation());
15135 MoveAssignment->setAccess(AS_public);
15136 MoveAssignment->setDefaulted();
15137 MoveAssignment->setImplicit();
15138
15139 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15140
15141 if (getLangOpts().CUDA)
15144 /* ConstRHS */ false,
15145 /* Diagnose */ false);
15146
15147 // Add the parameter to the operator.
15149 ClassLoc, ClassLoc,
15150 /*Id=*/nullptr, ArgType,
15151 /*TInfo=*/nullptr, SC_None,
15152 nullptr);
15153 MoveAssignment->setParams(FromParam);
15154
15155 MoveAssignment->setTrivial(
15159 : ClassDecl->hasTrivialMoveAssignment());
15160
15161 // Note that we have added this copy-assignment operator.
15163
15164 Scope *S = getScopeForContext(ClassDecl);
15166
15170 SetDeclDeleted(MoveAssignment, ClassLoc);
15171 }
15172
15173 if (S)
15175 ClassDecl->addDecl(MoveAssignment);
15176
15177 return MoveAssignment;
15178}
15179
15180/// Check if we're implicitly defining a move assignment operator for a class
15181/// with virtual bases. Such a move assignment might move-assign the virtual
15182/// base multiple times.
15184 SourceLocation CurrentLocation) {
15185 assert(!Class->isDependentContext() && "should not define dependent move");
15186
15187 // Only a virtual base could get implicitly move-assigned multiple times.
15188 // Only a non-trivial move assignment can observe this. We only want to
15189 // diagnose if we implicitly define an assignment operator that assigns
15190 // two base classes, both of which move-assign the same virtual base.
15191 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15192 Class->getNumBases() < 2)
15193 return;
15194
15196 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15197 VBaseMap VBases;
15198
15199 for (auto &BI : Class->bases()) {
15200 Worklist.push_back(&BI);
15201 while (!Worklist.empty()) {
15202 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15203 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15204
15205 // If the base has no non-trivial move assignment operators,
15206 // we don't care about moves from it.
15207 if (!Base->hasNonTrivialMoveAssignment())
15208 continue;
15209
15210 // If there's nothing virtual here, skip it.
15211 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15212 continue;
15213
15214 // If we're not actually going to call a move assignment for this base,
15215 // or the selected move assignment is trivial, skip it.
15218 /*ConstArg*/ false, /*VolatileArg*/ false,
15219 /*RValueThis*/ true, /*ConstThis*/ false,
15220 /*VolatileThis*/ false);
15221 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15223 continue;
15224
15225 if (BaseSpec->isVirtual()) {
15226 // We're going to move-assign this virtual base, and its move
15227 // assignment operator is not trivial. If this can happen for
15228 // multiple distinct direct bases of Class, diagnose it. (If it
15229 // only happens in one base, we'll diagnose it when synthesizing
15230 // that base class's move assignment operator.)
15231 CXXBaseSpecifier *&Existing =
15232 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15233 .first->second;
15234 if (Existing && Existing != &BI) {
15235 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15236 << Class << Base;
15237 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15238 << (Base->getCanonicalDecl() ==
15240 << Base << Existing->getType() << Existing->getSourceRange();
15241 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15242 << (Base->getCanonicalDecl() ==
15243 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15244 << Base << BI.getType() << BaseSpec->getSourceRange();
15245
15246 // Only diagnose each vbase once.
15247 Existing = nullptr;
15248 }
15249 } else {
15250 // Only walk over bases that have defaulted move assignment operators.
15251 // We assume that any user-provided move assignment operator handles
15252 // the multiple-moves-of-vbase case itself somehow.
15253 if (!SMOR.getMethod()->isDefaulted())
15254 continue;
15255
15256 // We're going to move the base classes of Base. Add them to the list.
15257 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15258 }
15259 }
15260 }
15261}
15262
15264 CXXMethodDecl *MoveAssignOperator) {
15265 assert((MoveAssignOperator->isDefaulted() &&
15266 MoveAssignOperator->isOverloadedOperator() &&
15267 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15268 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15269 !MoveAssignOperator->isDeleted()) &&
15270 "DefineImplicitMoveAssignment called for wrong function");
15271 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15272 return;
15273
15274 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15275 if (ClassDecl->isInvalidDecl()) {
15276 MoveAssignOperator->setInvalidDecl();
15277 return;
15278 }
15279
15280 // C++0x [class.copy]p28:
15281 // The implicitly-defined or move assignment operator for a non-union class
15282 // X performs memberwise move assignment of its subobjects. The direct base
15283 // classes of X are assigned first, in the order of their declaration in the
15284 // base-specifier-list, and then the immediate non-static data members of X
15285 // are assigned, in the order in which they were declared in the class
15286 // definition.
15287
15288 // Issue a warning if our implicit move assignment operator will move
15289 // from a virtual base more than once.
15290 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15291
15292 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15293
15294 // The exception specification is needed because we are defining the
15295 // function.
15296 ResolveExceptionSpec(CurrentLocation,
15297 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15298
15299 // Add a context note for diagnostics produced after this point.
15300 Scope.addContextNote(CurrentLocation);
15301
15302 // The statements that form the synthesized function body.
15303 SmallVector<Stmt*, 8> Statements;
15304
15305 // The parameter for the "other" object, which we are move from.
15306 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15307 QualType OtherRefType =
15308 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15309
15310 // Our location for everything implicitly-generated.
15311 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15312 ? MoveAssignOperator->getEndLoc()
15313 : MoveAssignOperator->getLocation();
15314
15315 // Builds a reference to the "other" object.
15316 RefBuilder OtherRef(Other, OtherRefType);
15317 // Cast to rvalue.
15318 MoveCastBuilder MoveOther(OtherRef);
15319
15320 // Builds the function object parameter.
15321 std::optional<ThisBuilder> This;
15322 std::optional<DerefBuilder> DerefThis;
15323 std::optional<RefBuilder> ExplicitObject;
15324 QualType ObjectType;
15325 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15326 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15327 if (ObjectType->isReferenceType())
15328 ObjectType = ObjectType->getPointeeType();
15329 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15330 } else {
15331 ObjectType = getCurrentThisType();
15332 This.emplace();
15333 DerefThis.emplace(*This);
15334 }
15335 ExprBuilder &ObjectParameter =
15336 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15337
15338 // Assign base classes.
15339 bool Invalid = false;
15340 for (auto &Base : ClassDecl->bases()) {
15341 // C++11 [class.copy]p28:
15342 // It is unspecified whether subobjects representing virtual base classes
15343 // are assigned more than once by the implicitly-defined copy assignment
15344 // operator.
15345 // FIXME: Do not assign to a vbase that will be assigned by some other base
15346 // class. For a move-assignment, this can result in the vbase being moved
15347 // multiple times.
15348
15349 // Form the assignment:
15350 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15351 QualType BaseType = Base.getType().getUnqualifiedType();
15352 if (!BaseType->isRecordType()) {
15353 Invalid = true;
15354 continue;
15355 }
15356
15357 CXXCastPath BasePath;
15358 BasePath.push_back(&Base);
15359
15360 // Construct the "from" expression, which is an implicit cast to the
15361 // appropriately-qualified base type.
15362 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15363
15364 // Implicitly cast "this" to the appropriately-qualified base type.
15365 // Dereference "this".
15366 CastBuilder To(
15367 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15368 : static_cast<ExprBuilder &>(*DerefThis),
15369 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15370 VK_LValue, BasePath);
15371
15372 // Build the move.
15373 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15374 To, From,
15375 /*CopyingBaseSubobject=*/true,
15376 /*Copying=*/false);
15377 if (Move.isInvalid()) {
15378 MoveAssignOperator->setInvalidDecl();
15379 return;
15380 }
15381
15382 // Success! Record the move.
15383 Statements.push_back(Move.getAs<Expr>());
15384 }
15385
15386 // Assign non-static members.
15387 for (auto *Field : ClassDecl->fields()) {
15388 // FIXME: We should form some kind of AST representation for the implied
15389 // memcpy in a union copy operation.
15390 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15391 continue;
15392
15393 if (Field->isInvalidDecl()) {
15394 Invalid = true;
15395 continue;
15396 }
15397
15398 // Check for members of reference type; we can't move those.
15399 if (Field->getType()->isReferenceType()) {
15400 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15401 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15402 Diag(Field->getLocation(), diag::note_declared_at);
15403 Invalid = true;
15404 continue;
15405 }
15406
15407 // Check for members of const-qualified, non-class type.
15408 QualType BaseType = Context.getBaseElementType(Field->getType());
15409 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15410 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15411 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15412 Diag(Field->getLocation(), diag::note_declared_at);
15413 Invalid = true;
15414 continue;
15415 }
15416
15417 // Suppress assigning zero-width bitfields.
15418 if (Field->isZeroLengthBitField(Context))
15419 continue;
15420
15421 QualType FieldType = Field->getType().getNonReferenceType();
15422 if (FieldType->isIncompleteArrayType()) {
15423 assert(ClassDecl->hasFlexibleArrayMember() &&
15424 "Incomplete array type is not valid");
15425 continue;
15426 }
15427
15428 // Build references to the field in the object we're copying from and to.
15429 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15431 MemberLookup.addDecl(Field);
15432 MemberLookup.resolveKind();
15433 MemberBuilder From(MoveOther, OtherRefType,
15434 /*IsArrow=*/false, MemberLookup);
15435 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15436 MemberLookup);
15437
15438 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15439 "Member reference with rvalue base must be rvalue except for reference "
15440 "members, which aren't allowed for move assignment.");
15441
15442 // Build the move of this field.
15443 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15444 To, From,
15445 /*CopyingBaseSubobject=*/false,
15446 /*Copying=*/false);
15447 if (Move.isInvalid()) {
15448 MoveAssignOperator->setInvalidDecl();
15449 return;
15450 }
15451
15452 // Success! Record the copy.
15453 Statements.push_back(Move.getAs<Stmt>());
15454 }
15455
15456 if (!Invalid) {
15457 // Add a "return *this;"
15458 Expr *ThisExpr =
15459 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15460 : static_cast<ExprBuilder &>(*DerefThis))
15461 .build(*this, Loc);
15462
15463 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15464 if (Return.isInvalid())
15465 Invalid = true;
15466 else
15467 Statements.push_back(Return.getAs<Stmt>());
15468 }
15469
15470 if (Invalid) {
15471 MoveAssignOperator->setInvalidDecl();
15472 return;
15473 }
15474
15475 StmtResult Body;
15476 {
15477 CompoundScopeRAII CompoundScope(*this);
15478 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15479 /*isStmtExpr=*/false);
15480 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15481 }
15482 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15483 MoveAssignOperator->markUsed(Context);
15484
15486 L->CompletedImplicitDefinition(MoveAssignOperator);
15487 }
15488}
15489
15491 CXXRecordDecl *ClassDecl) {
15492 // C++ [class.copy]p4:
15493 // If the class definition does not explicitly declare a copy
15494 // constructor, one is declared implicitly.
15495 assert(ClassDecl->needsImplicitCopyConstructor());
15496
15497 DeclaringSpecialMember DSM(*this, ClassDecl,
15499 if (DSM.isAlreadyBeingDeclared())
15500 return nullptr;
15501
15502 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15503 QualType ArgType = ClassType;
15505 ArgType, nullptr);
15506 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15507 if (Const)
15508 ArgType = ArgType.withConst();
15509
15511 if (AS != LangAS::Default)
15512 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15513
15514 ArgType = Context.getLValueReferenceType(ArgType);
15515
15517 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15518
15519 DeclarationName Name
15521 Context.getCanonicalType(ClassType));
15522 SourceLocation ClassLoc = ClassDecl->getLocation();
15523 DeclarationNameInfo NameInfo(Name, ClassLoc);
15524
15525 // An implicitly-declared copy constructor is an inline public
15526 // member of its class.
15528 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15529 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15530 /*isInline=*/true,
15531 /*isImplicitlyDeclared=*/true,
15534 CopyConstructor->setAccess(AS_public);
15535 CopyConstructor->setDefaulted();
15536
15537 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15538
15539 if (getLangOpts().CUDA)
15542 /* ConstRHS */ Const,
15543 /* Diagnose */ false);
15544
15545 // During template instantiation of special member functions we need a
15546 // reliable TypeSourceInfo for the parameter types in order to allow functions
15547 // to be substituted.
15548 TypeSourceInfo *TSI = nullptr;
15549 if (inTemplateInstantiation() && ClassDecl->isLambda())
15550 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15551
15552 // Add the parameter to the constructor.
15553 ParmVarDecl *FromParam =
15554 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15555 /*IdentifierInfo=*/nullptr, ArgType,
15556 /*TInfo=*/TSI, SC_None, nullptr);
15557 CopyConstructor->setParams(FromParam);
15558
15559 CopyConstructor->setTrivial(
15563 : ClassDecl->hasTrivialCopyConstructor());
15564
15565 CopyConstructor->setTrivialForCall(
15566 ClassDecl->hasAttr<TrivialABIAttr>() ||
15571 : ClassDecl->hasTrivialCopyConstructorForCall()));
15572
15573 // Note that we have declared this constructor.
15575
15576 Scope *S = getScopeForContext(ClassDecl);
15578
15583 }
15584
15585 if (S)
15587 ClassDecl->addDecl(CopyConstructor);
15588
15589 return CopyConstructor;
15590}
15591
15594 assert((CopyConstructor->isDefaulted() &&
15595 CopyConstructor->isCopyConstructor() &&
15596 !CopyConstructor->doesThisDeclarationHaveABody() &&
15597 !CopyConstructor->isDeleted()) &&
15598 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15599 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15600 return;
15601
15602 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15603 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15604
15606
15607 // The exception specification is needed because we are defining the
15608 // function.
15609 ResolveExceptionSpec(CurrentLocation,
15610 CopyConstructor->getType()->castAs<FunctionProtoType>());
15611 MarkVTableUsed(CurrentLocation, ClassDecl);
15612
15613 // Add a context note for diagnostics produced after this point.
15614 Scope.addContextNote(CurrentLocation);
15615
15616 // C++11 [class.copy]p7:
15617 // The [definition of an implicitly declared copy constructor] is
15618 // deprecated if the class has a user-declared copy assignment operator
15619 // or a user-declared destructor.
15620 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15622
15623 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15624 CopyConstructor->setInvalidDecl();
15625 } else {
15626 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15627 ? CopyConstructor->getEndLoc()
15628 : CopyConstructor->getLocation();
15629 Sema::CompoundScopeRAII CompoundScope(*this);
15630 CopyConstructor->setBody(
15631 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15632 .getAs<Stmt>());
15633 CopyConstructor->markUsed(Context);
15634 }
15635
15637 L->CompletedImplicitDefinition(CopyConstructor);
15638 }
15639}
15640
15642 CXXRecordDecl *ClassDecl) {
15643 assert(ClassDecl->needsImplicitMoveConstructor());
15644
15645 DeclaringSpecialMember DSM(*this, ClassDecl,
15647 if (DSM.isAlreadyBeingDeclared())
15648 return nullptr;
15649
15650 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15651
15652 QualType ArgType = ClassType;
15654 ArgType, nullptr);
15656 if (AS != LangAS::Default)
15657 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15658 ArgType = Context.getRValueReferenceType(ArgType);
15659
15661 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15662
15663 DeclarationName Name
15665 Context.getCanonicalType(ClassType));
15666 SourceLocation ClassLoc = ClassDecl->getLocation();
15667 DeclarationNameInfo NameInfo(Name, ClassLoc);
15668
15669 // C++11 [class.copy]p11:
15670 // An implicitly-declared copy/move constructor is an inline public
15671 // member of its class.
15673 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15674 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15675 /*isInline=*/true,
15676 /*isImplicitlyDeclared=*/true,
15679 MoveConstructor->setAccess(AS_public);
15680 MoveConstructor->setDefaulted();
15681
15682 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15683
15684 if (getLangOpts().CUDA)
15687 /* ConstRHS */ false,
15688 /* Diagnose */ false);
15689
15690 // Add the parameter to the constructor.
15692 ClassLoc, ClassLoc,
15693 /*IdentifierInfo=*/nullptr,
15694 ArgType, /*TInfo=*/nullptr,
15695 SC_None, nullptr);
15696 MoveConstructor->setParams(FromParam);
15697
15698 MoveConstructor->setTrivial(
15702 : ClassDecl->hasTrivialMoveConstructor());
15703
15704 MoveConstructor->setTrivialForCall(
15705 ClassDecl->hasAttr<TrivialABIAttr>() ||
15710 : ClassDecl->hasTrivialMoveConstructorForCall()));
15711
15712 // Note that we have declared this constructor.
15714
15715 Scope *S = getScopeForContext(ClassDecl);
15717
15722 }
15723
15724 if (S)
15726 ClassDecl->addDecl(MoveConstructor);
15727
15728 return MoveConstructor;
15729}
15730
15733 assert((MoveConstructor->isDefaulted() &&
15734 MoveConstructor->isMoveConstructor() &&
15735 !MoveConstructor->doesThisDeclarationHaveABody() &&
15736 !MoveConstructor->isDeleted()) &&
15737 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15738 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15739 return;
15740
15741 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15742 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15743
15745
15746 // The exception specification is needed because we are defining the
15747 // function.
15748 ResolveExceptionSpec(CurrentLocation,
15749 MoveConstructor->getType()->castAs<FunctionProtoType>());
15750 MarkVTableUsed(CurrentLocation, ClassDecl);
15751
15752 // Add a context note for diagnostics produced after this point.
15753 Scope.addContextNote(CurrentLocation);
15754
15755 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15756 MoveConstructor->setInvalidDecl();
15757 } else {
15758 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15759 ? MoveConstructor->getEndLoc()
15760 : MoveConstructor->getLocation();
15761 Sema::CompoundScopeRAII CompoundScope(*this);
15762 MoveConstructor->setBody(
15763 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15764 .getAs<Stmt>());
15765 MoveConstructor->markUsed(Context);
15766 }
15767
15769 L->CompletedImplicitDefinition(MoveConstructor);
15770 }
15771}
15772
15774 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15775}
15776
15778 SourceLocation CurrentLocation,
15779 CXXConversionDecl *Conv) {
15780 SynthesizedFunctionScope Scope(*this, Conv);
15781 assert(!Conv->getReturnType()->isUndeducedType());
15782
15783 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15784 CallingConv CC =
15785 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15786
15787 CXXRecordDecl *Lambda = Conv->getParent();
15788 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15789 FunctionDecl *Invoker =
15790 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15791 ? CallOp
15792 : Lambda->getLambdaStaticInvoker(CC);
15793
15794 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15796 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15797 if (!CallOp)
15798 return;
15799
15800 if (CallOp != Invoker) {
15802 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15803 CurrentLocation);
15804 if (!Invoker)
15805 return;
15806 }
15807 }
15808
15809 if (CallOp->isInvalidDecl())
15810 return;
15811
15812 // Mark the call operator referenced (and add to pending instantiations
15813 // if necessary).
15814 // For both the conversion and static-invoker template specializations
15815 // we construct their body's in this function, so no need to add them
15816 // to the PendingInstantiations.
15817 MarkFunctionReferenced(CurrentLocation, CallOp);
15818
15819 if (Invoker != CallOp) {
15820 // Fill in the __invoke function with a dummy implementation. IR generation
15821 // will fill in the actual details. Update its type in case it contained
15822 // an 'auto'.
15823 Invoker->markUsed(Context);
15824 Invoker->setReferenced();
15825 Invoker->setType(Conv->getReturnType()->getPointeeType());
15826 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15827 }
15828
15829 // Construct the body of the conversion function { return __invoke; }.
15830 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15831 Conv->getLocation());
15832 assert(FunctionRef && "Can't refer to __invoke function?");
15833 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15835 Conv->getLocation(), Conv->getLocation()));
15836 Conv->markUsed(Context);
15837 Conv->setReferenced();
15838
15840 L->CompletedImplicitDefinition(Conv);
15841 if (Invoker != CallOp)
15842 L->CompletedImplicitDefinition(Invoker);
15843 }
15844}
15845
15847 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15848 assert(!Conv->getParent()->isGenericLambda());
15849
15850 SynthesizedFunctionScope Scope(*this, Conv);
15851
15852 // Copy-initialize the lambda object as needed to capture it.
15853 Expr *This = ActOnCXXThis(CurrentLocation).get();
15854 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15855
15856 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15857 Conv->getLocation(),
15858 Conv, DerefThis);
15859
15860 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15861 // behavior. Note that only the general conversion function does this
15862 // (since it's unusable otherwise); in the case where we inline the
15863 // block literal, it has block literal lifetime semantics.
15864 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15865 BuildBlock = ImplicitCastExpr::Create(
15866 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15867 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15868
15869 if (BuildBlock.isInvalid()) {
15870 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15871 Conv->setInvalidDecl();
15872 return;
15873 }
15874
15875 // Create the return statement that returns the block from the conversion
15876 // function.
15877 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15878 if (Return.isInvalid()) {
15879 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15880 Conv->setInvalidDecl();
15881 return;
15882 }
15883
15884 // Set the body of the conversion function.
15885 Stmt *ReturnS = Return.get();
15887 Conv->getLocation(), Conv->getLocation()));
15888 Conv->markUsed(Context);
15889
15890 // We're done; notify the mutation listener, if any.
15892 L->CompletedImplicitDefinition(Conv);
15893 }
15894}
15895
15896/// Determine whether the given list arguments contains exactly one
15897/// "real" (non-default) argument.
15899 switch (Args.size()) {
15900 case 0:
15901 return false;
15902
15903 default:
15904 if (!Args[1]->isDefaultArgument())
15905 return false;
15906
15907 [[fallthrough]];
15908 case 1:
15909 return !Args[0]->isDefaultArgument();
15910 }
15911
15912 return false;
15913}
15914
15916 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15917 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
15918 bool HadMultipleCandidates, bool IsListInitialization,
15919 bool IsStdInitListInitialization, bool RequiresZeroInit,
15920 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15921 bool Elidable = false;
15922
15923 // C++0x [class.copy]p34:
15924 // When certain criteria are met, an implementation is allowed to
15925 // omit the copy/move construction of a class object, even if the
15926 // copy/move constructor and/or destructor for the object have
15927 // side effects. [...]
15928 // - when a temporary class object that has not been bound to a
15929 // reference (12.2) would be copied/moved to a class object
15930 // with the same cv-unqualified type, the copy/move operation
15931 // can be omitted by constructing the temporary object
15932 // directly into the target of the omitted copy/move
15933 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
15934 // FIXME: Converting constructors should also be accepted.
15935 // But to fix this, the logic that digs down into a CXXConstructExpr
15936 // to find the source object needs to handle it.
15937 // Right now it assumes the source object is passed directly as the
15938 // first argument.
15939 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15940 Expr *SubExpr = ExprArgs[0];
15941 // FIXME: Per above, this is also incorrect if we want to accept
15942 // converting constructors, as isTemporaryObject will
15943 // reject temporaries with different type from the
15944 // CXXRecord itself.
15945 Elidable = SubExpr->isTemporaryObject(
15946 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15947 }
15948
15949 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15950 FoundDecl, Constructor,
15951 Elidable, ExprArgs, HadMultipleCandidates,
15952 IsListInitialization,
15953 IsStdInitListInitialization, RequiresZeroInit,
15954 ConstructKind, ParenRange);
15955}
15956
15958 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15959 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15960 bool HadMultipleCandidates, bool IsListInitialization,
15961 bool IsStdInitListInitialization, bool RequiresZeroInit,
15962 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15963 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15964 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15965 // The only way to get here is if we did overload resolution to find the
15966 // shadow decl, so we don't need to worry about re-checking the trailing
15967 // requires clause.
15968 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15969 return ExprError();
15970 }
15971
15972 return BuildCXXConstructExpr(
15973 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15974 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15975 RequiresZeroInit, ConstructKind, ParenRange);
15976}
15977
15978/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15979/// including handling of its default argument expressions.
15981 SourceLocation ConstructLoc, QualType DeclInitType,
15982 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15983 bool HadMultipleCandidates, bool IsListInitialization,
15984 bool IsStdInitListInitialization, bool RequiresZeroInit,
15985 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15986 assert(declaresSameEntity(
15987 Constructor->getParent(),
15988 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15989 "given constructor for wrong type");
15990 MarkFunctionReferenced(ConstructLoc, Constructor);
15991 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
15992 return ExprError();
15993
15996 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15997 HadMultipleCandidates, IsListInitialization,
15998 IsStdInitListInitialization, RequiresZeroInit,
15999 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16000 Constructor);
16001}
16002
16004 if (VD->isInvalidDecl()) return;
16005 // If initializing the variable failed, don't also diagnose problems with
16006 // the destructor, they're likely related.
16007 if (VD->getInit() && VD->getInit()->containsErrors())
16008 return;
16009
16010 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16011 if (ClassDecl->isInvalidDecl()) return;
16012 if (ClassDecl->hasIrrelevantDestructor()) return;
16013 if (ClassDecl->isDependentContext()) return;
16014
16015 if (VD->isNoDestroy(getASTContext()))
16016 return;
16017
16019 // The result of `LookupDestructor` might be nullptr if the destructor is
16020 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16021 // will not be selected by `CXXRecordDecl::getDestructor()`.
16022 if (!Destructor)
16023 return;
16024 // If this is an array, we'll require the destructor during initialization, so
16025 // we can skip over this. We still want to emit exit-time destructor warnings
16026 // though.
16027 if (!VD->getType()->isArrayType()) {
16030 PDiag(diag::err_access_dtor_var)
16031 << VD->getDeclName() << VD->getType());
16033 }
16034
16035 if (Destructor->isTrivial()) return;
16036
16037 // If the destructor is constexpr, check whether the variable has constant
16038 // destruction now.
16039 if (Destructor->isConstexpr()) {
16040 bool HasConstantInit = false;
16041 if (VD->getInit() && !VD->getInit()->isValueDependent())
16042 HasConstantInit = VD->evaluateValue();
16044 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16045 HasConstantInit) {
16046 Diag(VD->getLocation(),
16047 diag::err_constexpr_var_requires_const_destruction) << VD;
16048 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16049 Diag(Notes[I].first, Notes[I].second);
16050 }
16051 }
16052
16053 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16054 return;
16055
16056 // Emit warning for non-trivial dtor in global scope (a real global,
16057 // class-static, function-static).
16058 if (!VD->hasAttr<AlwaysDestroyAttr>())
16059 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16060
16061 // TODO: this should be re-enabled for static locals by !CXAAtExit
16062 if (!VD->isStaticLocal())
16063 Diag(VD->getLocation(), diag::warn_global_destructor);
16064}
16065
16067 QualType DeclInitType, MultiExprArg ArgsPtr,
16069 SmallVectorImpl<Expr *> &ConvertedArgs,
16070 bool AllowExplicit,
16071 bool IsListInitialization) {
16072 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16073 unsigned NumArgs = ArgsPtr.size();
16074 Expr **Args = ArgsPtr.data();
16075
16076 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16077 unsigned NumParams = Proto->getNumParams();
16078
16079 // If too few arguments are available, we'll fill in the rest with defaults.
16080 if (NumArgs < NumParams)
16081 ConvertedArgs.reserve(NumParams);
16082 else
16083 ConvertedArgs.reserve(NumArgs);
16084
16085 VariadicCallType CallType =
16086 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16087 SmallVector<Expr *, 8> AllArgs;
16089 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16090 CallType, AllowExplicit, IsListInitialization);
16091 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16092
16093 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16094
16095 CheckConstructorCall(Constructor, DeclInitType,
16096 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16097 Loc);
16098
16099 return Invalid;
16100}
16101
16102static inline bool
16104 const FunctionDecl *FnDecl) {
16105 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16106 if (isa<NamespaceDecl>(DC)) {
16107 return SemaRef.Diag(FnDecl->getLocation(),
16108 diag::err_operator_new_delete_declared_in_namespace)
16109 << FnDecl->getDeclName();
16110 }
16111
16112 if (isa<TranslationUnitDecl>(DC) &&
16113 FnDecl->getStorageClass() == SC_Static) {
16114 return SemaRef.Diag(FnDecl->getLocation(),
16115 diag::err_operator_new_delete_declared_static)
16116 << FnDecl->getDeclName();
16117 }
16118
16119 return false;
16120}
16121
16123 const PointerType *PtrTy) {
16124 auto &Ctx = SemaRef.Context;
16125 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16126 PtrQuals.removeAddressSpace();
16127 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16128 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16129}
16130
16131static inline bool
16133 CanQualType ExpectedResultType,
16134 CanQualType ExpectedFirstParamType,
16135 unsigned DependentParamTypeDiag,
16136 unsigned InvalidParamTypeDiag) {
16137 QualType ResultType =
16138 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16139
16140 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16141 // The operator is valid on any address space for OpenCL.
16142 // Drop address space from actual and expected result types.
16143 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16144 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16145
16146 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16147 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16148 }
16149
16150 // Check that the result type is what we expect.
16151 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16152 // Reject even if the type is dependent; an operator delete function is
16153 // required to have a non-dependent result type.
16154 return SemaRef.Diag(
16155 FnDecl->getLocation(),
16156 ResultType->isDependentType()
16157 ? diag::err_operator_new_delete_dependent_result_type
16158 : diag::err_operator_new_delete_invalid_result_type)
16159 << FnDecl->getDeclName() << ExpectedResultType;
16160 }
16161
16162 // A function template must have at least 2 parameters.
16163 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16164 return SemaRef.Diag(FnDecl->getLocation(),
16165 diag::err_operator_new_delete_template_too_few_parameters)
16166 << FnDecl->getDeclName();
16167
16168 // The function decl must have at least 1 parameter.
16169 if (FnDecl->getNumParams() == 0)
16170 return SemaRef.Diag(FnDecl->getLocation(),
16171 diag::err_operator_new_delete_too_few_parameters)
16172 << FnDecl->getDeclName();
16173
16174 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16175 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16176 // The operator is valid on any address space for OpenCL.
16177 // Drop address space from actual and expected first parameter types.
16178 if (const auto *PtrTy =
16179 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16180 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16181
16182 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16183 ExpectedFirstParamType =
16184 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16185 }
16186
16187 // Check that the first parameter type is what we expect.
16188 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16189 ExpectedFirstParamType) {
16190 // The first parameter type is not allowed to be dependent. As a tentative
16191 // DR resolution, we allow a dependent parameter type if it is the right
16192 // type anyway, to allow destroying operator delete in class templates.
16193 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16194 ? DependentParamTypeDiag
16195 : InvalidParamTypeDiag)
16196 << FnDecl->getDeclName() << ExpectedFirstParamType;
16197 }
16198
16199 return false;
16200}
16201
16202static bool
16204 // C++ [basic.stc.dynamic.allocation]p1:
16205 // A program is ill-formed if an allocation function is declared in a
16206 // namespace scope other than global scope or declared static in global
16207 // scope.
16209 return true;
16210
16211 CanQualType SizeTy =
16213
16214 // C++ [basic.stc.dynamic.allocation]p1:
16215 // The return type shall be void*. The first parameter shall have type
16216 // std::size_t.
16218 SizeTy,
16219 diag::err_operator_new_dependent_param_type,
16220 diag::err_operator_new_param_type))
16221 return true;
16222
16223 // C++ [basic.stc.dynamic.allocation]p1:
16224 // The first parameter shall not have an associated default argument.
16225 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16226 return SemaRef.Diag(FnDecl->getLocation(),
16227 diag::err_operator_new_default_arg)
16228 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16229
16230 return false;
16231}
16232
16233static bool
16235 // C++ [basic.stc.dynamic.deallocation]p1:
16236 // A program is ill-formed if deallocation functions are declared in a
16237 // namespace scope other than global scope or declared static in global
16238 // scope.
16240 return true;
16241
16242 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16243
16244 // C++ P0722:
16245 // Within a class C, the first parameter of a destroying operator delete
16246 // shall be of type C *. The first parameter of any other deallocation
16247 // function shall be of type void *.
16248 CanQualType ExpectedFirstParamType =
16249 MD && MD->isDestroyingOperatorDelete()
16253
16254 // C++ [basic.stc.dynamic.deallocation]p2:
16255 // Each deallocation function shall return void
16257 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16258 diag::err_operator_delete_dependent_param_type,
16259 diag::err_operator_delete_param_type))
16260 return true;
16261
16262 // C++ P0722:
16263 // A destroying operator delete shall be a usual deallocation function.
16264 if (MD && !MD->getParent()->isDependentContext() &&
16267 SemaRef.Diag(MD->getLocation(),
16268 diag::err_destroying_operator_delete_not_usual);
16269 return true;
16270 }
16271
16272 return false;
16273}
16274
16276 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16277 "Expected an overloaded operator declaration");
16278
16280
16281 // C++ [over.oper]p5:
16282 // The allocation and deallocation functions, operator new,
16283 // operator new[], operator delete and operator delete[], are
16284 // described completely in 3.7.3. The attributes and restrictions
16285 // found in the rest of this subclause do not apply to them unless
16286 // explicitly stated in 3.7.3.
16287 if (Op == OO_Delete || Op == OO_Array_Delete)
16288 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16289
16290 if (Op == OO_New || Op == OO_Array_New)
16291 return CheckOperatorNewDeclaration(*this, FnDecl);
16292
16293 // C++ [over.oper]p7:
16294 // An operator function shall either be a member function or
16295 // be a non-member function and have at least one parameter
16296 // whose type is a class, a reference to a class, an enumeration,
16297 // or a reference to an enumeration.
16298 // Note: Before C++23, a member function could not be static. The only member
16299 // function allowed to be static is the call operator function.
16300 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16301 if (MethodDecl->isStatic()) {
16302 if (Op == OO_Call || Op == OO_Subscript)
16303 Diag(FnDecl->getLocation(),
16304 (LangOpts.CPlusPlus23
16305 ? diag::warn_cxx20_compat_operator_overload_static
16306 : diag::ext_operator_overload_static))
16307 << FnDecl;
16308 else
16309 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16310 << FnDecl;
16311 }
16312 } else {
16313 bool ClassOrEnumParam = false;
16314 for (auto *Param : FnDecl->parameters()) {
16315 QualType ParamType = Param->getType().getNonReferenceType();
16316 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16317 ParamType->isEnumeralType()) {
16318 ClassOrEnumParam = true;
16319 break;
16320 }
16321 }
16322
16323 if (!ClassOrEnumParam)
16324 return Diag(FnDecl->getLocation(),
16325 diag::err_operator_overload_needs_class_or_enum)
16326 << FnDecl->getDeclName();
16327 }
16328
16329 // C++ [over.oper]p8:
16330 // An operator function cannot have default arguments (8.3.6),
16331 // except where explicitly stated below.
16332 //
16333 // Only the function-call operator (C++ [over.call]p1) and the subscript
16334 // operator (CWG2507) allow default arguments.
16335 if (Op != OO_Call) {
16336 ParmVarDecl *FirstDefaultedParam = nullptr;
16337 for (auto *Param : FnDecl->parameters()) {
16338 if (Param->hasDefaultArg()) {
16339 FirstDefaultedParam = Param;
16340 break;
16341 }
16342 }
16343 if (FirstDefaultedParam) {
16344 if (Op == OO_Subscript) {
16345 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16346 ? diag::ext_subscript_overload
16347 : diag::error_subscript_overload)
16348 << FnDecl->getDeclName() << 1
16349 << FirstDefaultedParam->getDefaultArgRange();
16350 } else {
16351 return Diag(FirstDefaultedParam->getLocation(),
16352 diag::err_operator_overload_default_arg)
16353 << FnDecl->getDeclName()
16354 << FirstDefaultedParam->getDefaultArgRange();
16355 }
16356 }
16357 }
16358
16359 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16360 { false, false, false }
16361#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16362 , { Unary, Binary, MemberOnly }
16363#include "clang/Basic/OperatorKinds.def"
16364 };
16365
16366 bool CanBeUnaryOperator = OperatorUses[Op][0];
16367 bool CanBeBinaryOperator = OperatorUses[Op][1];
16368 bool MustBeMemberOperator = OperatorUses[Op][2];
16369
16370 // C++ [over.oper]p8:
16371 // [...] Operator functions cannot have more or fewer parameters
16372 // than the number required for the corresponding operator, as
16373 // described in the rest of this subclause.
16374 unsigned NumParams = FnDecl->getNumParams() +
16375 (isa<CXXMethodDecl>(FnDecl) &&
16377 ? 1
16378 : 0);
16379 if (Op != OO_Call && Op != OO_Subscript &&
16380 ((NumParams == 1 && !CanBeUnaryOperator) ||
16381 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16382 (NumParams > 2))) {
16383 // We have the wrong number of parameters.
16384 unsigned ErrorKind;
16385 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16386 ErrorKind = 2; // 2 -> unary or binary.
16387 } else if (CanBeUnaryOperator) {
16388 ErrorKind = 0; // 0 -> unary
16389 } else {
16390 assert(CanBeBinaryOperator &&
16391 "All non-call overloaded operators are unary or binary!");
16392 ErrorKind = 1; // 1 -> binary
16393 }
16394 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16395 << FnDecl->getDeclName() << NumParams << ErrorKind;
16396 }
16397
16398 if (Op == OO_Subscript && NumParams != 2) {
16399 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16400 ? diag::ext_subscript_overload
16401 : diag::error_subscript_overload)
16402 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16403 }
16404
16405 // Overloaded operators other than operator() and operator[] cannot be
16406 // variadic.
16407 if (Op != OO_Call &&
16408 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16409 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16410 << FnDecl->getDeclName();
16411 }
16412
16413 // Some operators must be member functions.
16414 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16415 return Diag(FnDecl->getLocation(),
16416 diag::err_operator_overload_must_be_member)
16417 << FnDecl->getDeclName();
16418 }
16419
16420 // C++ [over.inc]p1:
16421 // The user-defined function called operator++ implements the
16422 // prefix and postfix ++ operator. If this function is a member
16423 // function with no parameters, or a non-member function with one
16424 // parameter of class or enumeration type, it defines the prefix
16425 // increment operator ++ for objects of that type. If the function
16426 // is a member function with one parameter (which shall be of type
16427 // int) or a non-member function with two parameters (the second
16428 // of which shall be of type int), it defines the postfix
16429 // increment operator ++ for objects of that type.
16430 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16431 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16432 QualType ParamType = LastParam->getType();
16433
16434 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16435 !ParamType->isDependentType())
16436 return Diag(LastParam->getLocation(),
16437 diag::err_operator_overload_post_incdec_must_be_int)
16438 << LastParam->getType() << (Op == OO_MinusMinus);
16439 }
16440
16441 return false;
16442}
16443
16444static bool
16446 FunctionTemplateDecl *TpDecl) {
16447 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16448
16449 // Must have one or two template parameters.
16450 if (TemplateParams->size() == 1) {
16451 NonTypeTemplateParmDecl *PmDecl =
16452 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16453
16454 // The template parameter must be a char parameter pack.
16455 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16457 return false;
16458
16459 // C++20 [over.literal]p5:
16460 // A string literal operator template is a literal operator template
16461 // whose template-parameter-list comprises a single non-type
16462 // template-parameter of class type.
16463 //
16464 // As a DR resolution, we also allow placeholders for deduced class
16465 // template specializations.
16466 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16467 !PmDecl->isTemplateParameterPack() &&
16468 (PmDecl->getType()->isRecordType() ||
16470 return false;
16471 } else if (TemplateParams->size() == 2) {
16472 TemplateTypeParmDecl *PmType =
16473 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16474 NonTypeTemplateParmDecl *PmArgs =
16475 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16476
16477 // The second template parameter must be a parameter pack with the
16478 // first template parameter as its type.
16479 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16480 PmArgs->isTemplateParameterPack()) {
16481 const TemplateTypeParmType *TArgs =
16482 PmArgs->getType()->getAs<TemplateTypeParmType>();
16483 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16484 TArgs->getIndex() == PmType->getIndex()) {
16486 SemaRef.Diag(TpDecl->getLocation(),
16487 diag::ext_string_literal_operator_template);
16488 return false;
16489 }
16490 }
16491 }
16492
16494 diag::err_literal_operator_template)
16495 << TpDecl->getTemplateParameters()->getSourceRange();
16496 return true;
16497}
16498
16500 if (isa<CXXMethodDecl>(FnDecl)) {
16501 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16502 << FnDecl->getDeclName();
16503 return true;
16504 }
16505
16506 if (FnDecl->isExternC()) {
16507 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16508 if (const LinkageSpecDecl *LSD =
16509 FnDecl->getDeclContext()->getExternCContext())
16510 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16511 return true;
16512 }
16513
16514 // This might be the definition of a literal operator template.
16516
16517 // This might be a specialization of a literal operator template.
16518 if (!TpDecl)
16519 TpDecl = FnDecl->getPrimaryTemplate();
16520
16521 // template <char...> type operator "" name() and
16522 // template <class T, T...> type operator "" name() are the only valid
16523 // template signatures, and the only valid signatures with no parameters.
16524 //
16525 // C++20 also allows template <SomeClass T> type operator "" name().
16526 if (TpDecl) {
16527 if (FnDecl->param_size() != 0) {
16528 Diag(FnDecl->getLocation(),
16529 diag::err_literal_operator_template_with_params);
16530 return true;
16531 }
16532
16534 return true;
16535
16536 } else if (FnDecl->param_size() == 1) {
16537 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16538
16539 QualType ParamType = Param->getType().getUnqualifiedType();
16540
16541 // Only unsigned long long int, long double, any character type, and const
16542 // char * are allowed as the only parameters.
16543 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16544 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16545 Context.hasSameType(ParamType, Context.CharTy) ||
16546 Context.hasSameType(ParamType, Context.WideCharTy) ||
16547 Context.hasSameType(ParamType, Context.Char8Ty) ||
16548 Context.hasSameType(ParamType, Context.Char16Ty) ||
16549 Context.hasSameType(ParamType, Context.Char32Ty)) {
16550 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16551 QualType InnerType = Ptr->getPointeeType();
16552
16553 // Pointer parameter must be a const char *.
16554 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16555 Context.CharTy) &&
16556 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16557 Diag(Param->getSourceRange().getBegin(),
16558 diag::err_literal_operator_param)
16559 << ParamType << "'const char *'" << Param->getSourceRange();
16560 return true;
16561 }
16562
16563 } else if (ParamType->isRealFloatingType()) {
16564 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16565 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16566 return true;
16567
16568 } else if (ParamType->isIntegerType()) {
16569 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16570 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16571 return true;
16572
16573 } else {
16574 Diag(Param->getSourceRange().getBegin(),
16575 diag::err_literal_operator_invalid_param)
16576 << ParamType << Param->getSourceRange();
16577 return true;
16578 }
16579
16580 } else if (FnDecl->param_size() == 2) {
16581 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16582
16583 // First, verify that the first parameter is correct.
16584
16585 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16586
16587 // Two parameter function must have a pointer to const as a
16588 // first parameter; let's strip those qualifiers.
16589 const PointerType *PT = FirstParamType->getAs<PointerType>();
16590
16591 if (!PT) {
16592 Diag((*Param)->getSourceRange().getBegin(),
16593 diag::err_literal_operator_param)
16594 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16595 return true;
16596 }
16597
16598 QualType PointeeType = PT->getPointeeType();
16599 // First parameter must be const
16600 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16601 Diag((*Param)->getSourceRange().getBegin(),
16602 diag::err_literal_operator_param)
16603 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16604 return true;
16605 }
16606
16607 QualType InnerType = PointeeType.getUnqualifiedType();
16608 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16609 // const char32_t* are allowed as the first parameter to a two-parameter
16610 // function
16611 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16612 Context.hasSameType(InnerType, Context.WideCharTy) ||
16613 Context.hasSameType(InnerType, Context.Char8Ty) ||
16614 Context.hasSameType(InnerType, Context.Char16Ty) ||
16615 Context.hasSameType(InnerType, Context.Char32Ty))) {
16616 Diag((*Param)->getSourceRange().getBegin(),
16617 diag::err_literal_operator_param)
16618 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16619 return true;
16620 }
16621
16622 // Move on to the second and final parameter.
16623 ++Param;
16624
16625 // The second parameter must be a std::size_t.
16626 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16627 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16628 Diag((*Param)->getSourceRange().getBegin(),
16629 diag::err_literal_operator_param)
16630 << SecondParamType << Context.getSizeType()
16631 << (*Param)->getSourceRange();
16632 return true;
16633 }
16634 } else {
16635 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16636 return true;
16637 }
16638
16639 // Parameters are good.
16640
16641 // A parameter-declaration-clause containing a default argument is not
16642 // equivalent to any of the permitted forms.
16643 for (auto *Param : FnDecl->parameters()) {
16644 if (Param->hasDefaultArg()) {
16645 Diag(Param->getDefaultArgRange().getBegin(),
16646 diag::err_literal_operator_default_argument)
16647 << Param->getDefaultArgRange();
16648 break;
16649 }
16650 }
16651
16652 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16655 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16656 // C++23 [usrlit.suffix]p1:
16657 // Literal suffix identifiers that do not start with an underscore are
16658 // reserved for future standardization. Literal suffix identifiers that
16659 // contain a double underscore __ are reserved for use by C++
16660 // implementations.
16661 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16662 << static_cast<int>(Status)
16664 }
16665
16666 return false;
16667}
16668
16670 Expr *LangStr,
16671 SourceLocation LBraceLoc) {
16672 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16673 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16674
16675 StringRef Lang = Lit->getString();
16677 if (Lang == "C")
16679 else if (Lang == "C++")
16681 else {
16682 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16683 << LangStr->getSourceRange();
16684 return nullptr;
16685 }
16686
16687 // FIXME: Add all the various semantics of linkage specifications
16688
16690 LangStr->getExprLoc(), Language,
16691 LBraceLoc.isValid());
16692
16693 /// C++ [module.unit]p7.2.3
16694 /// - Otherwise, if the declaration
16695 /// - ...
16696 /// - ...
16697 /// - appears within a linkage-specification,
16698 /// it is attached to the global module.
16699 ///
16700 /// If the declaration is already in global module fragment, we don't
16701 /// need to attach it again.
16702 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16703 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16704 D->setLocalOwningModule(GlobalModule);
16705 }
16706
16708 PushDeclContext(S, D);
16709 return D;
16710}
16711
16713 Decl *LinkageSpec,
16714 SourceLocation RBraceLoc) {
16715 if (RBraceLoc.isValid()) {
16716 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16717 LSDecl->setRBraceLoc(RBraceLoc);
16718 }
16719
16720 // If the current module doesn't has Parent, it implies that the
16721 // LinkageSpec isn't in the module created by itself. So we don't
16722 // need to pop it.
16723 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16724 getCurrentModule()->isImplicitGlobalModule() &&
16726 PopImplicitGlobalModuleFragment();
16727
16729 return LinkageSpec;
16730}
16731
16733 const ParsedAttributesView &AttrList,
16734 SourceLocation SemiLoc) {
16735 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16736 // Attribute declarations appertain to empty declaration so we handle
16737 // them here.
16738 ProcessDeclAttributeList(S, ED, AttrList);
16739
16740 CurContext->addDecl(ED);
16741 return ED;
16742}
16743
16745 SourceLocation StartLoc,
16747 const IdentifierInfo *Name) {
16748 bool Invalid = false;
16749 QualType ExDeclType = TInfo->getType();
16750
16751 // Arrays and functions decay.
16752 if (ExDeclType->isArrayType())
16753 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16754 else if (ExDeclType->isFunctionType())
16755 ExDeclType = Context.getPointerType(ExDeclType);
16756
16757 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16758 // The exception-declaration shall not denote a pointer or reference to an
16759 // incomplete type, other than [cv] void*.
16760 // N2844 forbids rvalue references.
16761 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16762 Diag(Loc, diag::err_catch_rvalue_ref);
16763 Invalid = true;
16764 }
16765
16766 if (ExDeclType->isVariablyModifiedType()) {
16767 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16768 Invalid = true;
16769 }
16770
16771 QualType BaseType = ExDeclType;
16772 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16773 unsigned DK = diag::err_catch_incomplete;
16774 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16775 BaseType = Ptr->getPointeeType();
16776 Mode = 1;
16777 DK = diag::err_catch_incomplete_ptr;
16778 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16779 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16780 BaseType = Ref->getPointeeType();
16781 Mode = 2;
16782 DK = diag::err_catch_incomplete_ref;
16783 }
16784 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16785 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16786 Invalid = true;
16787
16788 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16789 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16790 Invalid = true;
16791 }
16792
16793 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16794 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16795 Invalid = true;
16796 }
16797
16798 if (!Invalid && !ExDeclType->isDependentType() &&
16799 RequireNonAbstractType(Loc, ExDeclType,
16800 diag::err_abstract_type_in_decl,
16802 Invalid = true;
16803
16804 // Only the non-fragile NeXT runtime currently supports C++ catches
16805 // of ObjC types, and no runtime supports catching ObjC types by value.
16806 if (!Invalid && getLangOpts().ObjC) {
16807 QualType T = ExDeclType;
16808 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16809 T = RT->getPointeeType();
16810
16811 if (T->isObjCObjectType()) {
16812 Diag(Loc, diag::err_objc_object_catch);
16813 Invalid = true;
16814 } else if (T->isObjCObjectPointerType()) {
16815 // FIXME: should this be a test for macosx-fragile specifically?
16817 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16818 }
16819 }
16820
16821 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16822 ExDeclType, TInfo, SC_None);
16823 ExDecl->setExceptionVariable(true);
16824
16825 // In ARC, infer 'retaining' for variables of retainable type.
16826 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16827 Invalid = true;
16828
16829 if (!Invalid && !ExDeclType->isDependentType()) {
16830 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16831 // Insulate this from anything else we might currently be parsing.
16834
16835 // C++ [except.handle]p16:
16836 // The object declared in an exception-declaration or, if the
16837 // exception-declaration does not specify a name, a temporary (12.2) is
16838 // copy-initialized (8.5) from the exception object. [...]
16839 // The object is destroyed when the handler exits, after the destruction
16840 // of any automatic objects initialized within the handler.
16841 //
16842 // We just pretend to initialize the object with itself, then make sure
16843 // it can be destroyed later.
16844 QualType initType = Context.getExceptionObjectType(ExDeclType);
16845
16846 InitializedEntity entity =
16848 InitializationKind initKind =
16850
16851 Expr *opaqueValue =
16852 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16853 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16854 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16855 if (result.isInvalid())
16856 Invalid = true;
16857 else {
16858 // If the constructor used was non-trivial, set this as the
16859 // "initializer".
16860 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16861 if (!construct->getConstructor()->isTrivial()) {
16862 Expr *init = MaybeCreateExprWithCleanups(construct);
16863 ExDecl->setInit(init);
16864 }
16865
16866 // And make sure it's destructable.
16868 }
16869 }
16870 }
16871
16872 if (Invalid)
16873 ExDecl->setInvalidDecl();
16874
16875 return ExDecl;
16876}
16877
16880 bool Invalid = D.isInvalidType();
16881
16882 // Check for unexpanded parameter packs.
16883 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16886 D.getIdentifierLoc());
16887 Invalid = true;
16888 }
16889
16890 const IdentifierInfo *II = D.getIdentifier();
16891 if (NamedDecl *PrevDecl =
16892 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16893 RedeclarationKind::ForVisibleRedeclaration)) {
16894 // The scope should be freshly made just for us. There is just no way
16895 // it contains any previous declaration, except for function parameters in
16896 // a function-try-block's catch statement.
16897 assert(!S->isDeclScope(PrevDecl));
16898 if (isDeclInScope(PrevDecl, CurContext, S)) {
16899 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16900 << D.getIdentifier();
16901 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16902 Invalid = true;
16903 } else if (PrevDecl->isTemplateParameter())
16904 // Maybe we will complain about the shadowed template parameter.
16905 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16906 }
16907
16908 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16909 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16910 << D.getCXXScopeSpec().getRange();
16911 Invalid = true;
16912 }
16913
16915 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16916 if (Invalid)
16917 ExDecl->setInvalidDecl();
16918
16919 // Add the exception declaration into this scope.
16920 if (II)
16921 PushOnScopeChains(ExDecl, S);
16922 else
16923 CurContext->addDecl(ExDecl);
16924
16925 ProcessDeclAttributes(S, ExDecl, D);
16926 return ExDecl;
16927}
16928
16930 Expr *AssertExpr,
16931 Expr *AssertMessageExpr,
16932 SourceLocation RParenLoc) {
16934 return nullptr;
16935
16936 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16937 AssertMessageExpr, RParenLoc, false);
16938}
16939
16940static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
16941 switch (BTK) {
16942 case BuiltinType::Char_S:
16943 case BuiltinType::Char_U:
16944 break;
16945 case BuiltinType::Char8:
16946 OS << "u8";
16947 break;
16948 case BuiltinType::Char16:
16949 OS << 'u';
16950 break;
16951 case BuiltinType::Char32:
16952 OS << 'U';
16953 break;
16954 case BuiltinType::WChar_S:
16955 case BuiltinType::WChar_U:
16956 OS << 'L';
16957 break;
16958 default:
16959 llvm_unreachable("Non-character type");
16960 }
16961}
16962
16963/// Convert character's value, interpreted as a code unit, to a string.
16964/// The value needs to be zero-extended to 32-bits.
16965/// FIXME: This assumes Unicode literal encodings
16966static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
16967 unsigned TyWidth,
16968 SmallVectorImpl<char> &Str) {
16969 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
16970 char *Ptr = Arr;
16971 BuiltinType::Kind K = BTy->getKind();
16972 llvm::raw_svector_ostream OS(Str);
16973
16974 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
16975 // other types.
16976 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
16977 K == BuiltinType::Char8 || Value <= 0x7F) {
16978 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
16979 if (!Escaped.empty())
16980 EscapeStringForDiagnostic(Escaped, Str);
16981 else
16982 OS << static_cast<char>(Value);
16983 return;
16984 }
16985
16986 switch (K) {
16987 case BuiltinType::Char16:
16988 case BuiltinType::Char32:
16989 case BuiltinType::WChar_S:
16990 case BuiltinType::WChar_U: {
16991 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
16992 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
16993 else
16994 OS << "\\x"
16995 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
16996 break;
16997 }
16998 default:
16999 llvm_unreachable("Non-character type is passed");
17000 }
17001}
17002
17003/// Convert \V to a string we can present to the user in a diagnostic
17004/// \T is the type of the expression that has been evaluated into \V
17008 if (!V.hasValue())
17009 return false;
17010
17011 switch (V.getKind()) {
17013 if (T->isBooleanType()) {
17014 // Bools are reduced to ints during evaluation, but for
17015 // diagnostic purposes we want to print them as
17016 // true or false.
17017 int64_t BoolValue = V.getInt().getExtValue();
17018 assert((BoolValue == 0 || BoolValue == 1) &&
17019 "Bool type, but value is not 0 or 1");
17020 llvm::raw_svector_ostream OS(Str);
17021 OS << (BoolValue ? "true" : "false");
17022 } else {
17023 llvm::raw_svector_ostream OS(Str);
17024 // Same is true for chars.
17025 // We want to print the character representation for textual types
17026 const auto *BTy = T->getAs<BuiltinType>();
17027 if (BTy) {
17028 switch (BTy->getKind()) {
17029 case BuiltinType::Char_S:
17030 case BuiltinType::Char_U:
17031 case BuiltinType::Char8:
17032 case BuiltinType::Char16:
17033 case BuiltinType::Char32:
17034 case BuiltinType::WChar_S:
17035 case BuiltinType::WChar_U: {
17036 unsigned TyWidth = Context.getIntWidth(T);
17037 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17038 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17039 WriteCharTypePrefix(BTy->getKind(), OS);
17040 OS << '\'';
17041 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17042 OS << "' (0x"
17043 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17044 /*Upper=*/true)
17045 << ", " << V.getInt() << ')';
17046 return true;
17047 }
17048 default:
17049 break;
17050 }
17051 }
17052 V.getInt().toString(Str);
17053 }
17054
17055 break;
17056
17058 V.getFloat().toString(Str);
17059 break;
17060
17062 if (V.isNullPointer()) {
17063 llvm::raw_svector_ostream OS(Str);
17064 OS << "nullptr";
17065 } else
17066 return false;
17067 break;
17068
17070 llvm::raw_svector_ostream OS(Str);
17071 OS << '(';
17072 V.getComplexFloatReal().toString(Str);
17073 OS << " + ";
17074 V.getComplexFloatImag().toString(Str);
17075 OS << "i)";
17076 } break;
17077
17079 llvm::raw_svector_ostream OS(Str);
17080 OS << '(';
17081 V.getComplexIntReal().toString(Str);
17082 OS << " + ";
17083 V.getComplexIntImag().toString(Str);
17084 OS << "i)";
17085 } break;
17086
17087 default:
17088 return false;
17089 }
17090
17091 return true;
17092}
17093
17094/// Some Expression types are not useful to print notes about,
17095/// e.g. literals and values that have already been expanded
17096/// before such as int-valued template parameters.
17097static bool UsefulToPrintExpr(const Expr *E) {
17098 E = E->IgnoreParenImpCasts();
17099 // Literals are pretty easy for humans to understand.
17102 return false;
17103
17104 // These have been substituted from template parameters
17105 // and appear as literals in the static assert error.
17106 if (isa<SubstNonTypeTemplateParmExpr>(E))
17107 return false;
17108
17109 // -5 is also simple to understand.
17110 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17111 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17112
17113 // Only print nested arithmetic operators.
17114 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17115 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17116 BO->isBitwiseOp());
17117
17118 return true;
17119}
17120
17122 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17123 Op && Op->getOpcode() != BO_LOr) {
17124 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17125 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17126
17127 // Ignore comparisons of boolean expressions with a boolean literal.
17128 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17129 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17130 return;
17131
17132 // Don't print obvious expressions.
17133 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17134 return;
17135
17136 struct {
17137 const clang::Expr *Cond;
17139 SmallString<12> ValueString;
17140 bool Print;
17141 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17142 {RHS, Expr::EvalResult(), {}, false}};
17143 for (unsigned I = 0; I < 2; I++) {
17144 const Expr *Side = DiagSide[I].Cond;
17145
17146 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17147
17148 DiagSide[I].Print =
17149 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17150 DiagSide[I].ValueString, Context);
17151 }
17152 if (DiagSide[0].Print && DiagSide[1].Print) {
17153 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17154 << DiagSide[0].ValueString << Op->getOpcodeStr()
17155 << DiagSide[1].ValueString << Op->getSourceRange();
17156 }
17157 }
17158}
17159
17161 std::string &Result,
17162 ASTContext &Ctx,
17163 bool ErrorOnInvalidMessage) {
17164 assert(Message);
17165 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17166 "can't evaluate a dependant static assert message");
17167
17168 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17169 assert(SL->isUnevaluated() && "expected an unevaluated string");
17170 Result.assign(SL->getString().begin(), SL->getString().end());
17171 return true;
17172 }
17173
17174 SourceLocation Loc = Message->getBeginLoc();
17175 QualType T = Message->getType().getNonReferenceType();
17176 auto *RD = T->getAsCXXRecordDecl();
17177 if (!RD) {
17178 Diag(Loc, diag::err_static_assert_invalid_message);
17179 return false;
17180 }
17181
17182 auto FindMember = [&](StringRef Member, bool &Empty,
17183 bool Diag = false) -> std::optional<LookupResult> {
17185 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17186 LookupQualifiedName(MemberLookup, RD);
17187 Empty = MemberLookup.empty();
17188 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17190 if (MemberLookup.empty())
17191 return std::nullopt;
17192 return std::move(MemberLookup);
17193 };
17194
17195 bool SizeNotFound, DataNotFound;
17196 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17197 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17198 if (SizeNotFound || DataNotFound) {
17199 Diag(Loc, diag::err_static_assert_missing_member_function)
17200 << ((SizeNotFound && DataNotFound) ? 2
17201 : SizeNotFound ? 0
17202 : 1);
17203 return false;
17204 }
17205
17206 if (!SizeMember || !DataMember) {
17207 if (!SizeMember)
17208 FindMember("size", SizeNotFound, /*Diag=*/true);
17209 if (!DataMember)
17210 FindMember("data", DataNotFound, /*Diag=*/true);
17211 return false;
17212 }
17213
17214 auto BuildExpr = [&](LookupResult &LR) {
17216 Message, Message->getType(), Message->getBeginLoc(), false,
17217 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17218 if (Res.isInvalid())
17219 return ExprError();
17220 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17221 false, true);
17222 if (Res.isInvalid())
17223 return ExprError();
17224 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17225 return ExprError();
17227 };
17228
17229 ExprResult SizeE = BuildExpr(*SizeMember);
17230 ExprResult DataE = BuildExpr(*DataMember);
17231
17232 QualType SizeT = Context.getSizeType();
17233 QualType ConstCharPtr =
17235
17236 ExprResult EvaluatedSize =
17237 SizeE.isInvalid() ? ExprError()
17239 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17240 if (EvaluatedSize.isInvalid()) {
17241 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17242 return false;
17243 }
17244
17245 ExprResult EvaluatedData =
17246 DataE.isInvalid()
17247 ? ExprError()
17248 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17250 if (EvaluatedData.isInvalid()) {
17251 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17252 return false;
17253 }
17254
17255 if (!ErrorOnInvalidMessage &&
17256 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17257 return true;
17258
17259 Expr::EvalResult Status;
17261 Status.Diag = &Notes;
17262 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17263 EvaluatedData.get(), Ctx, Status) ||
17264 !Notes.empty()) {
17265 Diag(Message->getBeginLoc(),
17266 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17267 : diag::warn_static_assert_message_constexpr);
17268 for (const auto &Note : Notes)
17269 Diag(Note.first, Note.second);
17270 return !ErrorOnInvalidMessage;
17271 }
17272 return true;
17273}
17274
17276 Expr *AssertExpr, Expr *AssertMessage,
17277 SourceLocation RParenLoc,
17278 bool Failed) {
17279 assert(AssertExpr != nullptr && "Expected non-null condition");
17280 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17281 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17282 !AssertMessage->isValueDependent())) &&
17283 !Failed) {
17284 // In a static_assert-declaration, the constant-expression shall be a
17285 // constant expression that can be contextually converted to bool.
17286 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17287 if (Converted.isInvalid())
17288 Failed = true;
17289
17290 ExprResult FullAssertExpr =
17291 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17292 /*DiscardedValue*/ false,
17293 /*IsConstexpr*/ true);
17294 if (FullAssertExpr.isInvalid())
17295 Failed = true;
17296 else
17297 AssertExpr = FullAssertExpr.get();
17298
17299 llvm::APSInt Cond;
17300 Expr *BaseExpr = AssertExpr;
17301 AllowFoldKind FoldKind = NoFold;
17302
17303 if (!getLangOpts().CPlusPlus) {
17304 // In C mode, allow folding as an extension for better compatibility with
17305 // C++ in terms of expressions like static_assert("test") or
17306 // static_assert(nullptr).
17307 FoldKind = AllowFold;
17308 }
17309
17310 if (!Failed && VerifyIntegerConstantExpression(
17311 BaseExpr, &Cond,
17312 diag::err_static_assert_expression_is_not_constant,
17313 FoldKind).isInvalid())
17314 Failed = true;
17315
17316 // If the static_assert passes, only verify that
17317 // the message is grammatically valid without evaluating it.
17318 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17319 std::string Str;
17320 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17321 /*ErrorOnInvalidMessage=*/false);
17322 }
17323
17324 // CWG2518
17325 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17326 // template definition, the declaration has no effect.
17327 bool InTemplateDefinition =
17328 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17329
17330 if (!Failed && !Cond && !InTemplateDefinition) {
17331 SmallString<256> MsgBuffer;
17332 llvm::raw_svector_ostream Msg(MsgBuffer);
17333 bool HasMessage = AssertMessage;
17334 if (AssertMessage) {
17335 std::string Str;
17336 HasMessage =
17338 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17339 !Str.empty();
17340 Msg << Str;
17341 }
17342 Expr *InnerCond = nullptr;
17343 std::string InnerCondDescription;
17344 std::tie(InnerCond, InnerCondDescription) =
17345 findFailedBooleanCondition(Converted.get());
17346 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17347 // Drill down into concept specialization expressions to see why they
17348 // weren't satisfied.
17349 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17350 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17351 ConstraintSatisfaction Satisfaction;
17352 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17353 DiagnoseUnsatisfiedConstraint(Satisfaction);
17354 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17355 && !isa<IntegerLiteral>(InnerCond)) {
17356 Diag(InnerCond->getBeginLoc(),
17357 diag::err_static_assert_requirement_failed)
17358 << InnerCondDescription << !HasMessage << Msg.str()
17359 << InnerCond->getSourceRange();
17360 DiagnoseStaticAssertDetails(InnerCond);
17361 } else {
17362 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17363 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17365 }
17366 Failed = true;
17367 }
17368 } else {
17369 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17370 /*DiscardedValue*/false,
17371 /*IsConstexpr*/true);
17372 if (FullAssertExpr.isInvalid())
17373 Failed = true;
17374 else
17375 AssertExpr = FullAssertExpr.get();
17376 }
17377
17379 AssertExpr, AssertMessage, RParenLoc,
17380 Failed);
17381
17383 return Decl;
17384}
17385
17387 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17388 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17389 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17390 MultiTemplateParamsArg TempParamLists) {
17392
17393 bool IsMemberSpecialization = false;
17394 bool Invalid = false;
17395
17396 if (TemplateParameterList *TemplateParams =
17398 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17399 IsMemberSpecialization, Invalid)) {
17400 if (TemplateParams->size() > 0) {
17401 // This is a declaration of a class template.
17402 if (Invalid)
17403 return true;
17404
17405 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17406 Name, NameLoc, Attr, TemplateParams, AS_public,
17407 /*ModulePrivateLoc=*/SourceLocation(),
17408 FriendLoc, TempParamLists.size() - 1,
17409 TempParamLists.data())
17410 .get();
17411 } else {
17412 // The "template<>" header is extraneous.
17413 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17414 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17415 IsMemberSpecialization = true;
17416 }
17417 }
17418
17419 if (Invalid) return true;
17420
17421 bool isAllExplicitSpecializations = true;
17422 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17423 if (TempParamLists[I]->size()) {
17424 isAllExplicitSpecializations = false;
17425 break;
17426 }
17427 }
17428
17429 // FIXME: don't ignore attributes.
17430
17431 // If it's explicit specializations all the way down, just forget
17432 // about the template header and build an appropriate non-templated
17433 // friend. TODO: for source fidelity, remember the headers.
17435 if (isAllExplicitSpecializations) {
17436 if (SS.isEmpty()) {
17437 bool Owned = false;
17438 bool IsDependent = false;
17439 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17440 Attr, AS_public,
17441 /*ModulePrivateLoc=*/SourceLocation(),
17442 MultiTemplateParamsArg(), Owned, IsDependent,
17443 /*ScopedEnumKWLoc=*/SourceLocation(),
17444 /*ScopedEnumUsesClassTag=*/false,
17445 /*UnderlyingType=*/TypeResult(),
17446 /*IsTypeSpecifier=*/false,
17447 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17448 }
17449
17450 ElaboratedTypeKeyword Keyword
17452 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17453 *Name, NameLoc);
17454 if (T.isNull())
17455 return true;
17456
17458 if (isa<DependentNameType>(T)) {
17461 TL.setElaboratedKeywordLoc(TagLoc);
17462 TL.setQualifierLoc(QualifierLoc);
17463 TL.setNameLoc(NameLoc);
17464 } else {
17466 TL.setElaboratedKeywordLoc(TagLoc);
17467 TL.setQualifierLoc(QualifierLoc);
17468 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17469 }
17470
17472 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17473 EllipsisLoc, TempParamLists);
17474 Friend->setAccess(AS_public);
17476 return Friend;
17477 }
17478
17479 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17480
17481 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17482 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17483 // shall not have been introduced by the template-declaration.
17485 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
17486 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17487 for (UnexpandedParameterPack &U : Unexpanded) {
17488 if (getDepthAndIndex(U).first >= FriendDeclDepth) {
17489 auto *ND = U.first.dyn_cast<NamedDecl *>();
17490 if (!ND)
17491 ND = U.first.get<const TemplateTypeParmType *>()->getDecl();
17492 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
17493 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
17494 return true;
17495 }
17496 }
17497
17498 // Handle the case of a templated-scope friend class. e.g.
17499 // template <class T> class A<T>::B;
17500 // FIXME: we don't support these right now.
17501 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17502 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17507 TL.setElaboratedKeywordLoc(TagLoc);
17509 TL.setNameLoc(NameLoc);
17510
17512 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17513 EllipsisLoc, TempParamLists);
17514 Friend->setAccess(AS_public);
17515 Friend->setUnsupportedFriend(true);
17517 return Friend;
17518}
17519
17521 MultiTemplateParamsArg TempParams,
17522 SourceLocation EllipsisLoc) {
17524 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17525
17526 assert(DS.isFriendSpecified());
17528
17529 // C++ [class.friend]p3:
17530 // A friend declaration that does not declare a function shall have one of
17531 // the following forms:
17532 // friend elaborated-type-specifier ;
17533 // friend simple-type-specifier ;
17534 // friend typename-specifier ;
17535 //
17536 // If the friend keyword isn't first, or if the declarations has any type
17537 // qualifiers, then the declaration doesn't have that form.
17539 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17540 if (DS.getTypeQualifiers()) {
17542 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17544 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17546 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17548 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17550 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17551 }
17552
17553 // Try to convert the decl specifier to a type. This works for
17554 // friend templates because ActOnTag never produces a ClassTemplateDecl
17555 // for a TagUseKind::Friend.
17556 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17558 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17559 QualType T = TSI->getType();
17560 if (TheDeclarator.isInvalidType())
17561 return nullptr;
17562
17563 // If '...' is present, the type must contain an unexpanded parameter
17564 // pack, and vice versa.
17565 bool Invalid = false;
17566 if (EllipsisLoc.isInvalid() &&
17568 return nullptr;
17569 if (EllipsisLoc.isValid() &&
17571 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
17572 << TSI->getTypeLoc().getSourceRange();
17573 Invalid = true;
17574 }
17575
17576 if (!T->isElaboratedTypeSpecifier()) {
17577 if (TempParams.size()) {
17578 // C++23 [dcl.pre]p5:
17579 // In a simple-declaration, the optional init-declarator-list can be
17580 // omitted only when declaring a class or enumeration, that is, when
17581 // the decl-specifier-seq contains either a class-specifier, an
17582 // elaborated-type-specifier with a class-key, or an enum-specifier.
17583 //
17584 // The declaration of a template-declaration or explicit-specialization
17585 // is never a member-declaration, so this must be a simple-declaration
17586 // with no init-declarator-list. Therefore, this is ill-formed.
17587 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17588 return nullptr;
17589 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17590 SmallString<16> InsertionText(" ");
17591 InsertionText += RD->getKindName();
17592
17594 ? diag::warn_cxx98_compat_unelaborated_friend_type
17595 : diag::ext_unelaborated_friend_type)
17596 << (unsigned)RD->getTagKind() << T
17598 InsertionText);
17599 } else {
17600 Diag(FriendLoc, getLangOpts().CPlusPlus11
17601 ? diag::warn_cxx98_compat_nonclass_type_friend
17602 : diag::ext_nonclass_type_friend)
17603 << T << DS.getSourceRange();
17604 }
17605 }
17606
17607 // C++98 [class.friend]p1: A friend of a class is a function
17608 // or class that is not a member of the class . . .
17609 // This is fixed in DR77, which just barely didn't make the C++03
17610 // deadline. It's also a very silly restriction that seriously
17611 // affects inner classes and which nobody else seems to implement;
17612 // thus we never diagnose it, not even in -pedantic.
17613 //
17614 // But note that we could warn about it: it's always useless to
17615 // friend one of your own members (it's not, however, worthless to
17616 // friend a member of an arbitrary specialization of your template).
17617
17618 Decl *D;
17619 if (!TempParams.empty())
17620 // TODO: Support variadic friend template decls?
17621 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17622 FriendLoc);
17623 else
17625 TSI, FriendLoc, EllipsisLoc);
17626
17627 if (!D)
17628 return nullptr;
17629
17632
17633 if (Invalid)
17634 D->setInvalidDecl();
17635
17636 return D;
17637}
17638
17640 MultiTemplateParamsArg TemplateParams) {
17641 const DeclSpec &DS = D.getDeclSpec();
17642
17643 assert(DS.isFriendSpecified());
17645
17646 SourceLocation Loc = D.getIdentifierLoc();
17648
17649 // C++ [class.friend]p1
17650 // A friend of a class is a function or class....
17651 // Note that this sees through typedefs, which is intended.
17652 // It *doesn't* see through dependent types, which is correct
17653 // according to [temp.arg.type]p3:
17654 // If a declaration acquires a function type through a
17655 // type dependent on a template-parameter and this causes
17656 // a declaration that does not use the syntactic form of a
17657 // function declarator to have a function type, the program
17658 // is ill-formed.
17659 if (!TInfo->getType()->isFunctionType()) {
17660 Diag(Loc, diag::err_unexpected_friend);
17661
17662 // It might be worthwhile to try to recover by creating an
17663 // appropriate declaration.
17664 return nullptr;
17665 }
17666
17667 // C++ [namespace.memdef]p3
17668 // - If a friend declaration in a non-local class first declares a
17669 // class or function, the friend class or function is a member
17670 // of the innermost enclosing namespace.
17671 // - The name of the friend is not found by simple name lookup
17672 // until a matching declaration is provided in that namespace
17673 // scope (either before or after the class declaration granting
17674 // friendship).
17675 // - If a friend function is called, its name may be found by the
17676 // name lookup that considers functions from namespaces and
17677 // classes associated with the types of the function arguments.
17678 // - When looking for a prior declaration of a class or a function
17679 // declared as a friend, scopes outside the innermost enclosing
17680 // namespace scope are not considered.
17681
17682 CXXScopeSpec &SS = D.getCXXScopeSpec();
17684 assert(NameInfo.getName());
17685
17686 // Check for unexpanded parameter packs.
17690 return nullptr;
17691
17692 // The context we found the declaration in, or in which we should
17693 // create the declaration.
17694 DeclContext *DC;
17695 Scope *DCScope = S;
17696 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17697 RedeclarationKind::ForExternalRedeclaration);
17698
17699 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17700
17701 // There are five cases here.
17702 // - There's no scope specifier and we're in a local class. Only look
17703 // for functions declared in the immediately-enclosing block scope.
17704 // We recover from invalid scope qualifiers as if they just weren't there.
17705 FunctionDecl *FunctionContainingLocalClass = nullptr;
17706 if ((SS.isInvalid() || !SS.isSet()) &&
17707 (FunctionContainingLocalClass =
17708 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17709 // C++11 [class.friend]p11:
17710 // If a friend declaration appears in a local class and the name
17711 // specified is an unqualified name, a prior declaration is
17712 // looked up without considering scopes that are outside the
17713 // innermost enclosing non-class scope. For a friend function
17714 // declaration, if there is no prior declaration, the program is
17715 // ill-formed.
17716
17717 // Find the innermost enclosing non-class scope. This is the block
17718 // scope containing the local class definition (or for a nested class,
17719 // the outer local class).
17720 DCScope = S->getFnParent();
17721
17722 // Look up the function name in the scope.
17724 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17725
17726 if (!Previous.empty()) {
17727 // All possible previous declarations must have the same context:
17728 // either they were declared at block scope or they are members of
17729 // one of the enclosing local classes.
17730 DC = Previous.getRepresentativeDecl()->getDeclContext();
17731 } else {
17732 // This is ill-formed, but provide the context that we would have
17733 // declared the function in, if we were permitted to, for error recovery.
17734 DC = FunctionContainingLocalClass;
17735 }
17737
17738 // - There's no scope specifier, in which case we just go to the
17739 // appropriate scope and look for a function or function template
17740 // there as appropriate.
17741 } else if (SS.isInvalid() || !SS.isSet()) {
17742 // C++11 [namespace.memdef]p3:
17743 // If the name in a friend declaration is neither qualified nor
17744 // a template-id and the declaration is a function or an
17745 // elaborated-type-specifier, the lookup to determine whether
17746 // the entity has been previously declared shall not consider
17747 // any scopes outside the innermost enclosing namespace.
17748
17749 // Find the appropriate context according to the above.
17750 DC = CurContext;
17751
17752 // Skip class contexts. If someone can cite chapter and verse
17753 // for this behavior, that would be nice --- it's what GCC and
17754 // EDG do, and it seems like a reasonable intent, but the spec
17755 // really only says that checks for unqualified existing
17756 // declarations should stop at the nearest enclosing namespace,
17757 // not that they should only consider the nearest enclosing
17758 // namespace.
17759 while (DC->isRecord())
17760 DC = DC->getParent();
17761
17762 DeclContext *LookupDC = DC->getNonTransparentContext();
17763 while (true) {
17764 LookupQualifiedName(Previous, LookupDC);
17765
17766 if (!Previous.empty()) {
17767 DC = LookupDC;
17768 break;
17769 }
17770
17771 if (isTemplateId) {
17772 if (isa<TranslationUnitDecl>(LookupDC)) break;
17773 } else {
17774 if (LookupDC->isFileContext()) break;
17775 }
17776 LookupDC = LookupDC->getParent();
17777 }
17778
17779 DCScope = getScopeForDeclContext(S, DC);
17780
17781 // - There's a non-dependent scope specifier, in which case we
17782 // compute it and do a previous lookup there for a function
17783 // or function template.
17784 } else if (!SS.getScopeRep()->isDependent()) {
17785 DC = computeDeclContext(SS);
17786 if (!DC) return nullptr;
17787
17788 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17789
17791
17792 // C++ [class.friend]p1: A friend of a class is a function or
17793 // class that is not a member of the class . . .
17794 if (DC->Equals(CurContext))
17797 diag::warn_cxx98_compat_friend_is_member :
17798 diag::err_friend_is_member);
17799
17800 // - There's a scope specifier that does not match any template
17801 // parameter lists, in which case we use some arbitrary context,
17802 // create a method or method template, and wait for instantiation.
17803 // - There's a scope specifier that does match some template
17804 // parameter lists, which we don't handle right now.
17805 } else {
17806 DC = CurContext;
17807 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17808 }
17809
17810 if (!DC->isRecord()) {
17811 int DiagArg = -1;
17812 switch (D.getName().getKind()) {
17815 DiagArg = 0;
17816 break;
17818 DiagArg = 1;
17819 break;
17821 DiagArg = 2;
17822 break;
17824 DiagArg = 3;
17825 break;
17831 break;
17832 }
17833 // This implies that it has to be an operator or function.
17834 if (DiagArg >= 0) {
17835 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17836 return nullptr;
17837 }
17838 }
17839
17840 // FIXME: This is an egregious hack to cope with cases where the scope stack
17841 // does not contain the declaration context, i.e., in an out-of-line
17842 // definition of a class.
17843 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17844 if (!DCScope) {
17845 FakeDCScope.setEntity(DC);
17846 DCScope = &FakeDCScope;
17847 }
17848
17849 bool AddToScope = true;
17850 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17851 TemplateParams, AddToScope);
17852 if (!ND) return nullptr;
17853
17854 assert(ND->getLexicalDeclContext() == CurContext);
17855
17856 // If we performed typo correction, we might have added a scope specifier
17857 // and changed the decl context.
17858 DC = ND->getDeclContext();
17859
17860 // Add the function declaration to the appropriate lookup tables,
17861 // adjusting the redeclarations list as necessary. We don't
17862 // want to do this yet if the friending class is dependent.
17863 //
17864 // Also update the scope-based lookup if the target context's
17865 // lookup context is in lexical scope.
17867 DC = DC->getRedeclContext();
17869 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17870 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17871 }
17872
17874 D.getIdentifierLoc(), ND,
17875 DS.getFriendSpecLoc());
17876 FrD->setAccess(AS_public);
17877 CurContext->addDecl(FrD);
17878
17879 if (ND->isInvalidDecl()) {
17880 FrD->setInvalidDecl();
17881 } else {
17882 if (DC->isRecord()) CheckFriendAccess(ND);
17883
17884 FunctionDecl *FD;
17885 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17886 FD = FTD->getTemplatedDecl();
17887 else
17888 FD = cast<FunctionDecl>(ND);
17889
17890 // C++ [class.friend]p6:
17891 // A function may be defined in a friend declaration of a class if and
17892 // only if the class is a non-local class, and the function name is
17893 // unqualified.
17894 if (D.isFunctionDefinition()) {
17895 // Qualified friend function definition.
17896 if (SS.isNotEmpty()) {
17897 // FIXME: We should only do this if the scope specifier names the
17898 // innermost enclosing namespace; otherwise the fixit changes the
17899 // meaning of the code.
17901 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17902
17903 DB << SS.getScopeRep();
17904 if (DC->isFileContext())
17906
17907 // Friend function defined in a local class.
17908 } else if (FunctionContainingLocalClass) {
17909 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17910
17911 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
17912 // a template-id, the function name is not unqualified because these is
17913 // no name. While the wording requires some reading in-between the
17914 // lines, GCC, MSVC, and EDG all consider a friend function
17915 // specialization definitions // to be de facto explicit specialization
17916 // and diagnose them as such.
17917 } else if (isTemplateId) {
17918 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
17919 }
17920 }
17921
17922 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17923 // default argument expression, that declaration shall be a definition
17924 // and shall be the only declaration of the function or function
17925 // template in the translation unit.
17927 // We can't look at FD->getPreviousDecl() because it may not have been set
17928 // if we're in a dependent context. If the function is known to be a
17929 // redeclaration, we will have narrowed Previous down to the right decl.
17930 if (D.isRedeclaration()) {
17931 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17932 Diag(Previous.getRepresentativeDecl()->getLocation(),
17933 diag::note_previous_declaration);
17934 } else if (!D.isFunctionDefinition())
17935 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17936 }
17937
17938 // Mark templated-scope function declarations as unsupported.
17939 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17940 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17941 << SS.getScopeRep() << SS.getRange()
17942 << cast<CXXRecordDecl>(CurContext);
17943 FrD->setUnsupportedFriend(true);
17944 }
17945 }
17946
17948
17949 return ND;
17950}
17951
17953 StringLiteral *Message) {
17955
17956 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17957 if (!Fn) {
17958 Diag(DelLoc, diag::err_deleted_non_function);
17959 return;
17960 }
17961
17962 // Deleted function does not have a body.
17963 Fn->setWillHaveBody(false);
17964
17965 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17966 // Don't consider the implicit declaration we generate for explicit
17967 // specializations. FIXME: Do not generate these implicit declarations.
17968 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17969 Prev->getPreviousDecl()) &&
17970 !Prev->isDefined()) {
17971 Diag(DelLoc, diag::err_deleted_decl_not_first);
17972 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17973 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17974 : diag::note_previous_declaration);
17975 // We can't recover from this; the declaration might have already
17976 // been used.
17977 Fn->setInvalidDecl();
17978 return;
17979 }
17980
17981 // To maintain the invariant that functions are only deleted on their first
17982 // declaration, mark the implicitly-instantiated declaration of the
17983 // explicitly-specialized function as deleted instead of marking the
17984 // instantiated redeclaration.
17985 Fn = Fn->getCanonicalDecl();
17986 }
17987
17988 // dllimport/dllexport cannot be deleted.
17989 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17990 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17991 Fn->setInvalidDecl();
17992 }
17993
17994 // C++11 [basic.start.main]p3:
17995 // A program that defines main as deleted [...] is ill-formed.
17996 if (Fn->isMain())
17997 Diag(DelLoc, diag::err_deleted_main);
17998
17999 // C++11 [dcl.fct.def.delete]p4:
18000 // A deleted function is implicitly inline.
18001 Fn->setImplicitlyInline();
18002 Fn->setDeletedAsWritten(true, Message);
18003}
18004
18006 if (!Dcl || Dcl->isInvalidDecl())
18007 return;
18008
18009 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18010 if (!FD) {
18011 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18012 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18013 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18014 return;
18015 }
18016 }
18017
18018 Diag(DefaultLoc, diag::err_default_special_members)
18019 << getLangOpts().CPlusPlus20;
18020 return;
18021 }
18022
18023 // Reject if this can't possibly be a defaultable function.
18025 if (!DefKind &&
18026 // A dependent function that doesn't locally look defaultable can
18027 // still instantiate to a defaultable function if it's a constructor
18028 // or assignment operator.
18029 (!FD->isDependentContext() ||
18030 (!isa<CXXConstructorDecl>(FD) &&
18031 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18032 Diag(DefaultLoc, diag::err_default_special_members)
18033 << getLangOpts().CPlusPlus20;
18034 return;
18035 }
18036
18037 // Issue compatibility warning. We already warned if the operator is
18038 // 'operator<=>' when parsing the '<=>' token.
18039 if (DefKind.isComparison() &&
18041 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18042 ? diag::warn_cxx17_compat_defaulted_comparison
18043 : diag::ext_defaulted_comparison);
18044 }
18045
18046 FD->setDefaulted();
18047 FD->setExplicitlyDefaulted();
18048 FD->setDefaultLoc(DefaultLoc);
18049
18050 // Defer checking functions that are defaulted in a dependent context.
18051 if (FD->isDependentContext())
18052 return;
18053
18054 // Unset that we will have a body for this function. We might not,
18055 // if it turns out to be trivial, and we don't need this marking now
18056 // that we've marked it as defaulted.
18057 FD->setWillHaveBody(false);
18058
18059 if (DefKind.isComparison()) {
18060 // If this comparison's defaulting occurs within the definition of its
18061 // lexical class context, we have to do the checking when complete.
18062 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18063 if (!RD->isCompleteDefinition())
18064 return;
18065 }
18066
18067 // If this member fn was defaulted on its first declaration, we will have
18068 // already performed the checking in CheckCompletedCXXClass. Such a
18069 // declaration doesn't trigger an implicit definition.
18070 if (isa<CXXMethodDecl>(FD)) {
18071 const FunctionDecl *Primary = FD;
18072 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18073 // Ask the template instantiation pattern that actually had the
18074 // '= default' on it.
18075 Primary = Pattern;
18076 if (Primary->getCanonicalDecl()->isDefaulted())
18077 return;
18078 }
18079
18080 if (DefKind.isComparison()) {
18081 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18082 FD->setInvalidDecl();
18083 else
18084 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18085 } else {
18086 auto *MD = cast<CXXMethodDecl>(FD);
18087
18089 DefaultLoc))
18090 MD->setInvalidDecl();
18091 else
18092 DefineDefaultedFunction(*this, MD, DefaultLoc);
18093 }
18094}
18095
18097 for (Stmt *SubStmt : S->children()) {
18098 if (!SubStmt)
18099 continue;
18100 if (isa<ReturnStmt>(SubStmt))
18101 Self.Diag(SubStmt->getBeginLoc(),
18102 diag::err_return_in_constructor_handler);
18103 if (!isa<Expr>(SubStmt))
18104 SearchForReturnInStmt(Self, SubStmt);
18105 }
18106}
18107
18109 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18110 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18111 SearchForReturnInStmt(*this, Handler);
18112 }
18113}
18114
18116 StringLiteral *DeletedMessage) {
18117 switch (BodyKind) {
18118 case FnBodyKind::Delete:
18119 SetDeclDeleted(D, Loc, DeletedMessage);
18120 break;
18123 break;
18124 case FnBodyKind::Other:
18125 llvm_unreachable(
18126 "Parsed function body should be '= delete;' or '= default;'");
18127 }
18128}
18129
18131 const CXXMethodDecl *Old) {
18132 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18133 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18134
18135 if (OldFT->hasExtParameterInfos()) {
18136 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18137 // A parameter of the overriding method should be annotated with noescape
18138 // if the corresponding parameter of the overridden method is annotated.
18139 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18140 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18141 Diag(New->getParamDecl(I)->getLocation(),
18142 diag::warn_overriding_method_missing_noescape);
18143 Diag(Old->getParamDecl(I)->getLocation(),
18144 diag::note_overridden_marked_noescape);
18145 }
18146 }
18147
18148 // SME attributes must match when overriding a function declaration.
18149 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18150 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18151 << New << New->getType() << Old->getType();
18152 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18153 return true;
18154 }
18155
18156 // Virtual overrides must have the same code_seg.
18157 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18158 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18159 if ((NewCSA || OldCSA) &&
18160 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18161 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18162 Diag(Old->getLocation(), diag::note_previous_declaration);
18163 return true;
18164 }
18165
18166 // Virtual overrides: check for matching effects.
18168 const auto OldFX = Old->getFunctionEffects();
18169 const auto NewFXOrig = New->getFunctionEffects();
18170
18171 if (OldFX != NewFXOrig) {
18172 FunctionEffectSet NewFX(NewFXOrig);
18173 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
18175 for (const auto &Diff : Diffs) {
18176 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18178 break;
18180 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18181 << Diff.effectName();
18182 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18183 << Old->getReturnTypeSourceRange();
18184 break;
18186 NewFX.insert(Diff.Old, Errs);
18187 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18188 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18190 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18191 NewFT->getParamTypes(), EPI);
18192 New->setType(ModQT);
18193 break;
18194 }
18195 }
18196 }
18197 if (!Errs.empty())
18199 Old->getLocation());
18200 }
18201 }
18202
18203 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18204
18205 // If the calling conventions match, everything is fine
18206 if (NewCC == OldCC)
18207 return false;
18208
18209 // If the calling conventions mismatch because the new function is static,
18210 // suppress the calling convention mismatch error; the error about static
18211 // function override (err_static_overrides_virtual from
18212 // Sema::CheckFunctionDeclaration) is more clear.
18213 if (New->getStorageClass() == SC_Static)
18214 return false;
18215
18216 Diag(New->getLocation(),
18217 diag::err_conflicting_overriding_cc_attributes)
18218 << New->getDeclName() << New->getType() << Old->getType();
18219 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18220 return true;
18221}
18222
18224 const CXXMethodDecl *Old) {
18225 // CWG2553
18226 // A virtual function shall not be an explicit object member function.
18228 return true;
18229 Diag(New->getParamDecl(0)->getBeginLoc(),
18230 diag::err_explicit_object_parameter_nonmember)
18231 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18232 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18233 New->setInvalidDecl();
18234 return false;
18235}
18236
18238 const CXXMethodDecl *Old) {
18239 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18240 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18241
18242 if (Context.hasSameType(NewTy, OldTy) ||
18243 NewTy->isDependentType() || OldTy->isDependentType())
18244 return false;
18245
18246 // Check if the return types are covariant
18247 QualType NewClassTy, OldClassTy;
18248
18249 /// Both types must be pointers or references to classes.
18250 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18251 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18252 NewClassTy = NewPT->getPointeeType();
18253 OldClassTy = OldPT->getPointeeType();
18254 }
18255 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18256 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18257 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18258 NewClassTy = NewRT->getPointeeType();
18259 OldClassTy = OldRT->getPointeeType();
18260 }
18261 }
18262 }
18263
18264 // The return types aren't either both pointers or references to a class type.
18265 if (NewClassTy.isNull()) {
18266 Diag(New->getLocation(),
18267 diag::err_different_return_type_for_overriding_virtual_function)
18268 << New->getDeclName() << NewTy << OldTy
18269 << New->getReturnTypeSourceRange();
18270 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18271 << Old->getReturnTypeSourceRange();
18272
18273 return true;
18274 }
18275
18276 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18277 // C++14 [class.virtual]p8:
18278 // If the class type in the covariant return type of D::f differs from
18279 // that of B::f, the class type in the return type of D::f shall be
18280 // complete at the point of declaration of D::f or shall be the class
18281 // type D.
18282 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18283 if (!RT->isBeingDefined() &&
18284 RequireCompleteType(New->getLocation(), NewClassTy,
18285 diag::err_covariant_return_incomplete,
18286 New->getDeclName()))
18287 return true;
18288 }
18289
18290 // Check if the new class derives from the old class.
18291 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18292 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18293 << New->getDeclName() << NewTy << OldTy
18294 << New->getReturnTypeSourceRange();
18295 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18296 << Old->getReturnTypeSourceRange();
18297 return true;
18298 }
18299
18300 // Check if we the conversion from derived to base is valid.
18302 NewClassTy, OldClassTy,
18303 diag::err_covariant_return_inaccessible_base,
18304 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18306 New->getDeclName(), nullptr)) {
18307 // FIXME: this note won't trigger for delayed access control
18308 // diagnostics, and it's impossible to get an undelayed error
18309 // here from access control during the original parse because
18310 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18311 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18312 << Old->getReturnTypeSourceRange();
18313 return true;
18314 }
18315 }
18316
18317 // The qualifiers of the return types must be the same.
18318 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18319 Diag(New->getLocation(),
18320 diag::err_covariant_return_type_different_qualifications)
18321 << New->getDeclName() << NewTy << OldTy
18322 << New->getReturnTypeSourceRange();
18323 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18324 << Old->getReturnTypeSourceRange();
18325 return true;
18326 }
18327
18328
18329 // The new class type must have the same or less qualifiers as the old type.
18330 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18331 Diag(New->getLocation(),
18332 diag::err_covariant_return_type_class_type_more_qualified)
18333 << New->getDeclName() << NewTy << OldTy
18334 << New->getReturnTypeSourceRange();
18335 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18336 << Old->getReturnTypeSourceRange();
18337 return true;
18338 }
18339
18340 return false;
18341}
18342
18344 SourceLocation EndLoc = InitRange.getEnd();
18345 if (EndLoc.isValid())
18346 Method->setRangeEnd(EndLoc);
18347
18348 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18349 Method->setIsPureVirtual();
18350 return false;
18351 }
18352
18353 if (!Method->isInvalidDecl())
18354 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18355 << Method->getDeclName() << InitRange;
18356 return true;
18357}
18358
18360 if (D->getFriendObjectKind())
18361 Diag(D->getLocation(), diag::err_pure_friend);
18362 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18363 CheckPureMethod(M, ZeroLoc);
18364 else
18365 Diag(D->getLocation(), diag::err_illegal_initializer);
18366}
18367
18368/// Invoked when we are about to parse an initializer for the declaration
18369/// 'Dcl'.
18370///
18371/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18372/// static data member of class X, names should be looked up in the scope of
18373/// class X. If the declaration had a scope specifier, a scope will have
18374/// been created and passed in for this purpose. Otherwise, S will be null.
18376 assert(D && !D->isInvalidDecl());
18377
18378 // We will always have a nested name specifier here, but this declaration
18379 // might not be out of line if the specifier names the current namespace:
18380 // extern int n;
18381 // int ::n = 0;
18382 if (S && D->isOutOfLine())
18384
18387}
18388
18390 assert(D);
18391
18392 if (S && D->isOutOfLine())
18394
18395 if (getLangOpts().CPlusPlus23) {
18396 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18397 // [...]
18398 // - the initializer of a variable that is usable in constant expressions or
18399 // has constant initialization.
18400 if (auto *VD = dyn_cast<VarDecl>(D);
18403 // An expression or conversion is in an 'immediate function context' if it
18404 // is potentially evaluated and either:
18405 // [...]
18406 // - it is a subexpression of a manifestly constant-evaluated expression
18407 // or conversion.
18408 ExprEvalContexts.back().InImmediateFunctionContext = true;
18409 }
18410 }
18411
18412 // Unless the initializer is in an immediate function context (as determined
18413 // above), this will evaluate all contained immediate function calls as
18414 // constant expressions. If the initializer IS an immediate function context,
18415 // the initializer has been determined to be a constant expression, and all
18416 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18417 // it was a constant expression).
18419}
18420
18422 // C++ 6.4p2:
18423 // The declarator shall not specify a function or an array.
18424 // The type-specifier-seq shall not contain typedef and shall not declare a
18425 // new class or enumeration.
18426 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18427 "Parser allowed 'typedef' as storage class of condition decl.");
18428
18429 Decl *Dcl = ActOnDeclarator(S, D);
18430 if (!Dcl)
18431 return true;
18432
18433 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18434 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18435 << D.getSourceRange();
18436 return true;
18437 }
18438
18439 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18440 VD->setCXXCondDecl();
18441
18442 return Dcl;
18443}
18444
18446 if (!ExternalSource)
18447 return;
18448
18450 ExternalSource->ReadUsedVTables(VTables);
18452 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18453 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18454 = VTablesUsed.find(VTables[I].Record);
18455 // Even if a definition wasn't required before, it may be required now.
18456 if (Pos != VTablesUsed.end()) {
18457 if (!Pos->second && VTables[I].DefinitionRequired)
18458 Pos->second = true;
18459 continue;
18460 }
18461
18462 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18463 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18464 }
18465
18466 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18467}
18468
18470 bool DefinitionRequired) {
18471 // Ignore any vtable uses in unevaluated operands or for classes that do
18472 // not have a vtable.
18473 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18475 return;
18476 // Do not mark as used if compiling for the device outside of the target
18477 // region.
18478 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18479 !OpenMP().isInOpenMPDeclareTargetContext() &&
18480 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18481 if (!DefinitionRequired)
18483 return;
18484 }
18485
18486 // Try to insert this class into the map.
18488 Class = Class->getCanonicalDecl();
18489 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18490 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18491 if (!Pos.second) {
18492 // If we already had an entry, check to see if we are promoting this vtable
18493 // to require a definition. If so, we need to reappend to the VTableUses
18494 // list, since we may have already processed the first entry.
18495 if (DefinitionRequired && !Pos.first->second) {
18496 Pos.first->second = true;
18497 } else {
18498 // Otherwise, we can early exit.
18499 return;
18500 }
18501 } else {
18502 // The Microsoft ABI requires that we perform the destructor body
18503 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18504 // the deleting destructor is emitted with the vtable, not with the
18505 // destructor definition as in the Itanium ABI.
18507 CXXDestructorDecl *DD = Class->getDestructor();
18508 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18509 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18510 // If this is an out-of-line declaration, marking it referenced will
18511 // not do anything. Manually call CheckDestructor to look up operator
18512 // delete().
18513 ContextRAII SavedContext(*this, DD);
18514 CheckDestructor(DD);
18515 } else {
18516 MarkFunctionReferenced(Loc, Class->getDestructor());
18517 }
18518 }
18519 }
18520 }
18521
18522 // Local classes need to have their virtual members marked
18523 // immediately. For all other classes, we mark their virtual members
18524 // at the end of the translation unit.
18525 if (Class->isLocalClass())
18526 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18527 else
18528 VTableUses.push_back(std::make_pair(Class, Loc));
18529}
18530
18533 if (VTableUses.empty())
18534 return false;
18535
18536 // Note: The VTableUses vector could grow as a result of marking
18537 // the members of a class as "used", so we check the size each
18538 // time through the loop and prefer indices (which are stable) to
18539 // iterators (which are not).
18540 bool DefinedAnything = false;
18541 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18542 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18543 if (!Class)
18544 continue;
18546 Class->getTemplateSpecializationKind();
18547
18548 SourceLocation Loc = VTableUses[I].second;
18549
18550 bool DefineVTable = true;
18551
18552 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18553 // V-tables for non-template classes with an owning module are always
18554 // uniquely emitted in that module.
18555 if (Class->isInCurrentModuleUnit()) {
18556 DefineVTable = true;
18557 } else if (KeyFunction && !KeyFunction->hasBody()) {
18558 // If this class has a key function, but that key function is
18559 // defined in another translation unit, we don't need to emit the
18560 // vtable even though we're using it.
18561 // The key function is in another translation unit.
18562 DefineVTable = false;
18564 KeyFunction->getTemplateSpecializationKind();
18567 "Instantiations don't have key functions");
18568 (void)TSK;
18569 } else if (!KeyFunction) {
18570 // If we have a class with no key function that is the subject
18571 // of an explicit instantiation declaration, suppress the
18572 // vtable; it will live with the explicit instantiation
18573 // definition.
18574 bool IsExplicitInstantiationDeclaration =
18576 for (auto *R : Class->redecls()) {
18578 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18580 IsExplicitInstantiationDeclaration = true;
18581 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18582 IsExplicitInstantiationDeclaration = false;
18583 break;
18584 }
18585 }
18586
18587 if (IsExplicitInstantiationDeclaration)
18588 DefineVTable = false;
18589 }
18590
18591 // The exception specifications for all virtual members may be needed even
18592 // if we are not providing an authoritative form of the vtable in this TU.
18593 // We may choose to emit it available_externally anyway.
18594 if (!DefineVTable) {
18596 continue;
18597 }
18598
18599 // Mark all of the virtual members of this class as referenced, so
18600 // that we can build a vtable. Then, tell the AST consumer that a
18601 // vtable for this class is required.
18602 DefinedAnything = true;
18604 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18605 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
18607
18608 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18609 // no key function or the key function is inlined. Don't warn in C++ ABIs
18610 // that lack key functions, since the user won't be able to make one.
18612 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18614 const FunctionDecl *KeyFunctionDef = nullptr;
18615 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18616 KeyFunctionDef->isInlined()))
18617 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18618 }
18619 }
18620 VTableUses.clear();
18621
18622 return DefinedAnything;
18623}
18624
18626 const CXXRecordDecl *RD) {
18627 for (const auto *I : RD->methods())
18628 if (I->isVirtual() && !I->isPureVirtual())
18629 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18630}
18631
18633 const CXXRecordDecl *RD,
18634 bool ConstexprOnly) {
18635 // Mark all functions which will appear in RD's vtable as used.
18636 CXXFinalOverriderMap FinalOverriders;
18637 RD->getFinalOverriders(FinalOverriders);
18638 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18639 E = FinalOverriders.end();
18640 I != E; ++I) {
18641 for (OverridingMethods::const_iterator OI = I->second.begin(),
18642 OE = I->second.end();
18643 OI != OE; ++OI) {
18644 assert(OI->second.size() > 0 && "no final overrider");
18645 CXXMethodDecl *Overrider = OI->second.front().Method;
18646
18647 // C++ [basic.def.odr]p2:
18648 // [...] A virtual member function is used if it is not pure. [...]
18649 if (!Overrider->isPureVirtual() &&
18650 (!ConstexprOnly || Overrider->isConstexpr()))
18651 MarkFunctionReferenced(Loc, Overrider);
18652 }
18653 }
18654
18655 // Only classes that have virtual bases need a VTT.
18656 if (RD->getNumVBases() == 0)
18657 return;
18658
18659 for (const auto &I : RD->bases()) {
18660 const auto *Base =
18661 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18662 if (Base->getNumVBases() == 0)
18663 continue;
18665 }
18666}
18667
18668static
18673 Sema &S) {
18674 if (Ctor->isInvalidDecl())
18675 return;
18676
18678
18679 // Target may not be determinable yet, for instance if this is a dependent
18680 // call in an uninstantiated template.
18681 if (Target) {
18682 const FunctionDecl *FNTarget = nullptr;
18683 (void)Target->hasBody(FNTarget);
18684 Target = const_cast<CXXConstructorDecl*>(
18685 cast_or_null<CXXConstructorDecl>(FNTarget));
18686 }
18687
18688 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18689 // Avoid dereferencing a null pointer here.
18690 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18691
18692 if (!Current.insert(Canonical).second)
18693 return;
18694
18695 // We know that beyond here, we aren't chaining into a cycle.
18696 if (!Target || !Target->isDelegatingConstructor() ||
18697 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18698 Valid.insert(Current.begin(), Current.end());
18699 Current.clear();
18700 // We've hit a cycle.
18701 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18702 Current.count(TCanonical)) {
18703 // If we haven't diagnosed this cycle yet, do so now.
18704 if (!Invalid.count(TCanonical)) {
18705 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18706 diag::warn_delegating_ctor_cycle)
18707 << Ctor;
18708
18709 // Don't add a note for a function delegating directly to itself.
18710 if (TCanonical != Canonical)
18711 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18712
18714 while (C->getCanonicalDecl() != Canonical) {
18715 const FunctionDecl *FNTarget = nullptr;
18716 (void)C->getTargetConstructor()->hasBody(FNTarget);
18717 assert(FNTarget && "Ctor cycle through bodiless function");
18718
18719 C = const_cast<CXXConstructorDecl*>(
18720 cast<CXXConstructorDecl>(FNTarget));
18721 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18722 }
18723 }
18724
18725 Invalid.insert(Current.begin(), Current.end());
18726 Current.clear();
18727 } else {
18728 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18729 }
18730}
18731
18732
18735
18736 for (DelegatingCtorDeclsType::iterator
18739 I != E; ++I)
18740 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18741
18742 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18743 (*CI)->setInvalidDecl();
18744}
18745
18746namespace {
18747 /// AST visitor that finds references to the 'this' expression.
18748 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18749 Sema &S;
18750
18751 public:
18752 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18753
18754 bool VisitCXXThisExpr(CXXThisExpr *E) {
18755 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18756 << E->isImplicit();
18757 return false;
18758 }
18759 };
18760}
18761
18763 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18764 if (!TSInfo)
18765 return false;
18766
18767 TypeLoc TL = TSInfo->getTypeLoc();
18769 if (!ProtoTL)
18770 return false;
18771
18772 // C++11 [expr.prim.general]p3:
18773 // [The expression this] shall not appear before the optional
18774 // cv-qualifier-seq and it shall not appear within the declaration of a
18775 // static member function (although its type and value category are defined
18776 // within a static member function as they are within a non-static member
18777 // function). [ Note: this is because declaration matching does not occur
18778 // until the complete declarator is known. - end note ]
18779 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18780 FindCXXThisExpr Finder(*this);
18781
18782 // If the return type came after the cv-qualifier-seq, check it now.
18783 if (Proto->hasTrailingReturn() &&
18784 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18785 return true;
18786
18787 // Check the exception specification.
18789 return true;
18790
18791 // Check the trailing requires clause
18792 if (Expr *E = Method->getTrailingRequiresClause())
18793 if (!Finder.TraverseStmt(E))
18794 return true;
18795
18797}
18798
18800 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18801 if (!TSInfo)
18802 return false;
18803
18804 TypeLoc TL = TSInfo->getTypeLoc();
18806 if (!ProtoTL)
18807 return false;
18808
18809 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18810 FindCXXThisExpr Finder(*this);
18811
18812 switch (Proto->getExceptionSpecType()) {
18813 case EST_Unparsed:
18814 case EST_Uninstantiated:
18815 case EST_Unevaluated:
18816 case EST_BasicNoexcept:
18817 case EST_NoThrow:
18818 case EST_DynamicNone:
18819 case EST_MSAny:
18820 case EST_None:
18821 break;
18822
18824 case EST_NoexceptFalse:
18825 case EST_NoexceptTrue:
18826 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18827 return true;
18828 [[fallthrough]];
18829
18830 case EST_Dynamic:
18831 for (const auto &E : Proto->exceptions()) {
18832 if (!Finder.TraverseType(E))
18833 return true;
18834 }
18835 break;
18836 }
18837
18838 return false;
18839}
18840
18842 FindCXXThisExpr Finder(*this);
18843
18844 // Check attributes.
18845 for (const auto *A : Method->attrs()) {
18846 // FIXME: This should be emitted by tblgen.
18847 Expr *Arg = nullptr;
18848 ArrayRef<Expr *> Args;
18849 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18850 Arg = G->getArg();
18851 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18852 Arg = G->getArg();
18853 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18854 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18855 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18856 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18857 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18858 Arg = ETLF->getSuccessValue();
18859 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18860 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18861 Arg = STLF->getSuccessValue();
18862 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18863 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18864 Arg = LR->getArg();
18865 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18866 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18867 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18868 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18869 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18870 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18871 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18872 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18873 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18874 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18875
18876 if (Arg && !Finder.TraverseStmt(Arg))
18877 return true;
18878
18879 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18880 if (!Finder.TraverseStmt(Args[I]))
18881 return true;
18882 }
18883 }
18884
18885 return false;
18886}
18887
18889 bool IsTopLevel, ExceptionSpecificationType EST,
18890 ArrayRef<ParsedType> DynamicExceptions,
18891 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18892 SmallVectorImpl<QualType> &Exceptions,
18894 Exceptions.clear();
18895 ESI.Type = EST;
18896 if (EST == EST_Dynamic) {
18897 Exceptions.reserve(DynamicExceptions.size());
18898 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18899 // FIXME: Preserve type source info.
18900 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18901
18902 if (IsTopLevel) {
18904 collectUnexpandedParameterPacks(ET, Unexpanded);
18905 if (!Unexpanded.empty()) {
18907 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18908 Unexpanded);
18909 continue;
18910 }
18911 }
18912
18913 // Check that the type is valid for an exception spec, and
18914 // drop it if not.
18915 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18916 Exceptions.push_back(ET);
18917 }
18918 ESI.Exceptions = Exceptions;
18919 return;
18920 }
18921
18922 if (isComputedNoexcept(EST)) {
18923 assert((NoexceptExpr->isTypeDependent() ||
18924 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18925 Context.BoolTy) &&
18926 "Parser should have made sure that the expression is boolean");
18927 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18928 ESI.Type = EST_BasicNoexcept;
18929 return;
18930 }
18931
18932 ESI.NoexceptExpr = NoexceptExpr;
18933 return;
18934 }
18935}
18936
18938 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
18939 ArrayRef<ParsedType> DynamicExceptions,
18940 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
18941 if (!D)
18942 return;
18943
18944 // Dig out the function we're referring to.
18945 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
18946 D = FTD->getTemplatedDecl();
18947
18948 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
18949 if (!FD)
18950 return;
18951
18952 // Check the exception specification.
18955 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
18956 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18957 ESI);
18958
18959 // Update the exception specification on the function type.
18960 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
18961
18962 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
18963 if (MD->isStatic())
18965
18966 if (MD->isVirtual()) {
18967 // Check overrides, which we previously had to delay.
18968 for (const CXXMethodDecl *O : MD->overridden_methods())
18970 }
18971 }
18972}
18973
18974/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18975///
18977 SourceLocation DeclStart, Declarator &D,
18978 Expr *BitWidth,
18979 InClassInitStyle InitStyle,
18980 AccessSpecifier AS,
18981 const ParsedAttr &MSPropertyAttr) {
18982 const IdentifierInfo *II = D.getIdentifier();
18983 if (!II) {
18984 Diag(DeclStart, diag::err_anonymous_property);
18985 return nullptr;
18986 }
18987 SourceLocation Loc = D.getIdentifierLoc();
18988
18990 QualType T = TInfo->getType();
18991 if (getLangOpts().CPlusPlus) {
18993
18994 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18996 D.setInvalidType();
18997 T = Context.IntTy;
18999 }
19000 }
19001
19002 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19003
19004 if (D.getDeclSpec().isInlineSpecified())
19005 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19006 << getLangOpts().CPlusPlus17;
19007 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19008 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19009 diag::err_invalid_thread)
19011
19012 // Check to see if this name was declared as a member previously
19013 NamedDecl *PrevDecl = nullptr;
19015 RedeclarationKind::ForVisibleRedeclaration);
19016 LookupName(Previous, S);
19017 switch (Previous.getResultKind()) {
19020 PrevDecl = Previous.getAsSingle<NamedDecl>();
19021 break;
19022
19024 PrevDecl = Previous.getRepresentativeDecl();
19025 break;
19026
19030 break;
19031 }
19032
19033 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19034 // Maybe we will complain about the shadowed template parameter.
19035 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19036 // Just pretend that we didn't see the previous declaration.
19037 PrevDecl = nullptr;
19038 }
19039
19040 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19041 PrevDecl = nullptr;
19042
19043 SourceLocation TSSL = D.getBeginLoc();
19044 MSPropertyDecl *NewPD =
19045 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19046 MSPropertyAttr.getPropertyDataGetter(),
19047 MSPropertyAttr.getPropertyDataSetter());
19049 NewPD->setAccess(AS);
19050
19051 if (NewPD->isInvalidDecl())
19052 Record->setInvalidDecl();
19053
19054 if (D.getDeclSpec().isModulePrivateSpecified())
19055 NewPD->setModulePrivate();
19056
19057 if (NewPD->isInvalidDecl() && PrevDecl) {
19058 // Don't introduce NewFD into scope; there's already something
19059 // with the same name in the same scope.
19060 } else if (II) {
19061 PushOnScopeChains(NewPD, S);
19062 } else
19063 Record->addDecl(NewPD);
19064
19065 return NewPD;
19066}
19067
19069 Declarator &Declarator, unsigned TemplateParameterDepth) {
19070 auto &Info = InventedParameterInfos.emplace_back();
19071 TemplateParameterList *ExplicitParams = nullptr;
19072 ArrayRef<TemplateParameterList *> ExplicitLists =
19074 if (!ExplicitLists.empty()) {
19075 bool IsMemberSpecialization, IsInvalid;
19078 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19079 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19080 /*SuppressDiagnostic=*/true);
19081 }
19082 // C++23 [dcl.fct]p23:
19083 // An abbreviated function template can have a template-head. The invented
19084 // template-parameters are appended to the template-parameter-list after
19085 // the explicitly declared template-parameters.
19086 //
19087 // A template-head must have one or more template-parameters (read:
19088 // 'template<>' is *not* a template-head). Only append the invented
19089 // template parameters if we matched the nested-name-specifier to a non-empty
19090 // TemplateParameterList.
19091 if (ExplicitParams && !ExplicitParams->empty()) {
19092 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19093 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19094 Info.NumExplicitTemplateParams = ExplicitParams->size();
19095 } else {
19096 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19097 Info.NumExplicitTemplateParams = 0;
19098 }
19099}
19100
19102 auto &FSI = InventedParameterInfos.back();
19103 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19104 if (FSI.NumExplicitTemplateParams != 0) {
19105 TemplateParameterList *ExplicitParams =
19109 Context, ExplicitParams->getTemplateLoc(),
19110 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19111 ExplicitParams->getRAngleLoc(),
19112 ExplicitParams->getRequiresClause()));
19113 } else {
19116 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19117 SourceLocation(), /*RequiresClause=*/nullptr));
19118 }
19119 }
19120 InventedParameterInfos.pop_back();
19121}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1658::IndirectLocalPathEntry::EntryKind Kind
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
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...
int Category
Definition: Format.cpp:3004
LangStandard::Kind Std
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.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
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 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 RefersToRValueRef(Expr *MemRef)
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.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
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 bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
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 Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
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 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 findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
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 bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
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 Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
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 checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
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 CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
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 NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
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 ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
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 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.
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 void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
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 lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
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 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 CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
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.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
bool Indirect
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
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.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
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)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:124
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3291
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3305
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
CanQualType Char16Ty
Definition: ASTContext.h:1126
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
void Deallocate(void *Ptr) const
Definition: ASTContext.h:740
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1147
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
CanQualType WideCharTy
Definition: ASTContext.h:1123
IdentifierTable & Idents
Definition: ASTContext.h:660
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1345
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<=>,...
Definition: ASTContext.h:2325
QualType AutoDeductTy
Definition: ASTContext.h:1181
CanQualType BoolTy
Definition: ASTContext.h:1120
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3270
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2924
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1121
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3284
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3277
CanQualType IntTy
Definition: ASTContext.h:1128
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3301
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3266
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3298
CanQualType VoidTy
Definition: ASTContext.h:1119
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3280
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
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.
Definition: ASTContext.h:3085
CanQualType Char32Ty
Definition: ASTContext.h:1127
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3273
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3287
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1125
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3294
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:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:95
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6375
AutoTypeKeyword getKeyword() const
Definition: Type.h:6406
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3421
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3499
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3157
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3491
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3166
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
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:4804
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3351
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Kind getKind() const
Definition: Type.h:3071
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
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...
std::list< CXXBasePath >::iterator paths_iterator
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:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
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:1160
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1609
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2781
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:2805
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2610
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2635
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2782
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:2800
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2791
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2776
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(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2761
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2304
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2476
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2710
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2697
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2450
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2895
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:1737
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:723
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2493
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2500
bool isVirtual() const
Definition: DeclCXX.h:2119
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2218
bool isVolatile() const
Definition: DeclCXX.h:2117
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2167
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2572
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2566
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2614
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2240
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2556
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
bool isInstance() const
Definition: DeclCXX.h:2091
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2312
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2214
bool isStatic() const
Definition: DeclCXX.cpp:2224
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2504
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2160
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
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:1275
friend_range friends() const
Definition: DeclFriend.h:261
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1346
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:612
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1245
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1603
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1371
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1006
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:832
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1425
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1396
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1375
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:718
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1429
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:966
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1361
base_class_range bases()
Definition: DeclCXX.h:620
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:605
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1023
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1306
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:778
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:897
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:915
method_range methods() const
Definition: DeclCXX.h:662
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:936
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:1268
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1283
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:978
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:600
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1219
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:709
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1287
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:731
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1944
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1333
base_class_range vbases()
Definition: DeclCXX.h:637
base_class_iterator vbases_begin()
Definition: DeclCXX.h:644
ctor_range ctors() const
Definition: DeclCXX.h:682
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:879
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1226
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1241
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:870
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1153
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:811
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1407
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1205
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:805
bool hasDefinition() const
Definition: DeclCXX.h:572
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:921
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1012
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1936
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:907
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:999
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2014
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1018
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1419
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1645
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:817
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:858
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:988
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2043
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:930
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1311
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1633
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
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:951
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:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents the this expression in C++.
Definition: ExprCXX.h:1152
SourceLocation getBeginLoc() 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:2830
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
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.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this 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
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
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.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
QualType getElementType() const
Definition: Type.h:3144
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1669
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4203
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3660
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3602
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3666
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3139
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:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2043
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1685
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
decl_iterator decls_end() const
Definition: DeclBase.h:2352
bool isStdNamespace() const
Definition: DeclBase.cpp:1317
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1388
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1403
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1740
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2083
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1414
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1622
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
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:1333
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1457
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:691
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:827
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:825
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:655
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
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:561
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
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:456
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_auto
Definition: DeclSpec.h:318
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1523
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:1051
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:580
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1204
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2767
bool isInvalidDecl() const
Definition: DeclBase.h:595
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:879
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:823
void setImplicit(bool I=true)
Definition: DeclBase.h:601
void setReferenced(bool R=true)
Definition: DeclBase.h:630
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:455
attr_range attrs() const
Definition: DeclBase.h:542
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
void dropAttr()
Definition: DeclBase.h:563
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Kind getKind() const
Definition: DeclBase.h:449
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:871
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
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:731
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:819
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2339
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2065
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2652
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2659
bool isInvalidType() const
Definition: DeclSpec.h:2717
A decomposition declaration.
Definition: DeclCXX.h:4170
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4202
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Represents a C++17 deduced template specialization type.
Definition: Type.h:6423
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:770
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5628
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:3274
Represents an enum.
Definition: Decl.h:3844
enumerator_range enumerators() const
Definition: Decl.h:3977
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
const Expr * getExpr() const
Definition: DeclCXX.h:1910
void setExpr(Expr *E)
Definition: DeclCXX.h:1935
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1934
This represents one expression.
Definition: Expr.h:110
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:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
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:3204
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:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4556
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4630
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4546
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3185
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3218
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4566
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3258
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:110
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:189
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:35
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:3084
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2741
bool isTrivialForCall() const
Definition: Decl.h:2305
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3699
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
bool isImmediateFunction() const
Definition: Decl.cpp:3276
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3105
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3859
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3460
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3717
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
SourceLocation getDefaultLoc() const
Definition: Decl.h:2323
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2314
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2654
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3603
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3853
param_iterator param_begin()
Definition: Decl.h:2658
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2258
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2411
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3006
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4092
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2760
bool isStatic() const
Definition: Decl.h:2801
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3478
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3168
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4381
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4252
void setDefaulted(bool D=true)
Definition: Decl.h:2311
bool isConsteval() const
Definition: Decl.h:2407
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2335
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:2734
void setBody(Stmt *B)
Definition: Decl.cpp:3236
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2276
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3731
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
size_t param_size() const
Definition: Decl.h:2662
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2143
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
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:3191
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2771
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3139
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2677
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4939
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition: Type.cpp:5202
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4882
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5468
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5282
unsigned getNumParams() const
Definition: Type.h:5255
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5395
QualType getParamType(unsigned i) const
Definition: Type.h:5257
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:5340
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
ArrayRef< QualType > exceptions() const
Definition: Type.h:5425
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5440
Declaration of a template function.
Definition: DeclTemplate.h:957
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4534
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
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...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2143
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5782
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2510
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2522
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5029
unsigned getNumInits() const
Definition: Expr.h:5059
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5075
child_range children()
Definition: Expr.h:5221
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.
Definition: SemaInit.cpp:7521
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.
Definition: SemaInit.cpp:3580
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.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6612
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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3472
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1340
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1353
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:629
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
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:1024
Represents a linkage specification.
Definition: DeclCXX.h:2938
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2958
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2980
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
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.
Definition: SemaLookup.cpp:485
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4239
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3416
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
Expr * getBase() const
Definition: Expr.h:3264
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3382
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
bool isExplicitGlobalModule() const
Definition: Module.h:203
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:700
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represents a C++ namespace alias.
Definition: DeclCXX.h:3124
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3053
Represent a C++ namespace.
Definition: Decl.h:547
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:603
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3013
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition: Decl.h:630
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:649
Class that aids in the construction of nested-name-specifiers along with 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>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
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:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4746
Represents a parameter to a function.
Definition: Decl.h:1722
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2968
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1818
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1863
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1851
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2973
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2993
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1855
bool hasInheritedDefaultArg() const
Definition: Decl.h:1867
bool isExplicitObjectParameter() const
Definition: Decl.h:1810
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:2903
Expr * getDefaultArg()
Definition: Decl.cpp:2956
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2998
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3004
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1871
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2926
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:487
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:481
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:838
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:918
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6487
ArrayRef< Expr * > semantics()
Definition: Expr.h:6566
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7839
QualType withConst() const
Definition: Type.h:1166
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1232
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.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: Type.h:7951
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2840
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1093
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7922
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7796
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2596
Represents a template name as written in source code.
Definition: TemplateName.h:434
The collection of all-type qualifiers we support.
Definition: Type.h:319
void addAddressSpace(LangAS space)
Definition: Type.h:584
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
void removeConst()
Definition: Type.h:446
void removeAddressSpace()
Definition: Type.h:583
void addConst()
Definition: Type.h:447
void removeVolatile()
Definition: Type.h:456
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3490
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasFlexibleArrayMember() const
Definition: Decl.h:4178
field_iterator field_end() const
Definition: Decl.h:4354
field_range fields() const
Definition: Decl.h:4351
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5034
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4197
bool field_empty() const
Definition: Decl.h:4359
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4978
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
QualType getPointeeType() const
Definition: Type.h:3446
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
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:392
void AddDecl(Decl *D)
Definition: Scope.h:345
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:372
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
A RAII object to enter scope of a compound statement.
Definition: Sema.h:1011
bool isInvalid() const
Definition: Sema.h:7393
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3065
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5943
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5975
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5972
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:5046
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
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:9009
CXXMethodDecl * getMethod() const
Definition: Sema.h:9021
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:13125
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7291
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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.
Definition: SemaDecl.cpp:10909
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6665
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, ASTContext &Ctx, bool ErrorOnInvalidMessage)
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:12698
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)
Definition: SemaDecl.cpp:9681
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:6126
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',...
Definition: SemaDecl.cpp:1557
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3582
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15280
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:5887
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9057
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9084
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9092
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9080
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9065
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:411
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6601
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, CXXScopeSpec *SS=nullptr)
VariadicCallType
Definition: Sema.h:2388
@ VariadicDoesNotApply
Definition: Sema.h:2393
@ VariadicConstructor
Definition: Sema.h:2392
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.
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)
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.
Definition: SemaDecl.cpp:6078
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)
void PrintContextStack()
Definition: Sema.h:13267
SemaOpenMP & OpenMP()
Definition: Sema.h:1221
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5862
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,...
Definition: SemaDecl.cpp:6063
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:960
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:6103
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:6084
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1094
SemaCUDA & CUDA()
Definition: Sema.h:1166
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)
Definition: SemaExpr.cpp:17174
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'.
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 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:1357
@ AR_accessible
Definition: Sema.h:1355
@ AR_inaccessible
Definition: Sema.h:1356
@ AR_delayed
Definition: Sema.h:1358
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2295
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:2164
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)
Definition: SemaDecl.cpp:6206
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16932
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)
Definition: SemaDecl.cpp:4796
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...
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
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:52
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.
Definition: SemaDecl.cpp:18258
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1752
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.
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:1004
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5770
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:599
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1206
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...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4906
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:7305
@ AllowFold
Definition: Sema.h:7307
@ NoFold
Definition: Sema.h:7306
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
ASTContext & getASTContext() const
Definition: Sema.h:602
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:6110
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,...
Definition: SemaExpr.cpp:19654
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:6188
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17595
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
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:701
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:5658
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
@ None
This is not a defaultable comparison operator.
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9272
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:6121
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:910
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2190
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=std::nullopt)
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:11844
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1585
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:8029
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1566
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2183
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:597
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20156
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_RequiresClause
Definition: Sema.h:14001
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:13956
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:13974
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13965
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:13935
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13959
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13968
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13938
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13941
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:13947
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:595
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:5448
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.
Definition: SemaDecl.cpp:1386
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:1003
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.
Definition: SemaExpr.cpp:6400
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.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
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 ...
Definition: SemaDecl.cpp:8167
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
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.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14410
const LangOptions & LangOpts
Definition: Sema.h:1002
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.
Definition: SemaExpr.cpp:17291
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7484
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6088
SemaHLSL & HLSL()
Definition: Sema.h:1171
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.
Definition: SemaDecl.cpp:11808
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:5454
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4843
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:6081
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19805
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
Definition: SemaStmt.cpp:3618
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:6180
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6114
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)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9368
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
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 CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1373
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.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1842
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:12710
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:5444
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:639
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)
Definition: SemaExpr.cpp:3167
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15025
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:9655
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)
Definition: SemaDecl.cpp:15330
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:6554
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:6095
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15254
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1139
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
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.
Definition: SemaDecl.cpp:14834
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5775
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 SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:5927
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5929
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:5932
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7838
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 MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
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.
Definition: SemaExpr.cpp:19754
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2164
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:13532
SourceManager & getSourceManager() const
Definition: Sema.h:600
@ AA_Passing
Definition: Sema.h:6539
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 EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1338
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.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:9037
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9522
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.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1364
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 ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:215
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.
Definition: SemaDecl.cpp:8190
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)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:3789
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14980
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...
@ CTK_ErrorRecovery
Definition: Sema.h:9451
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14200
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
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:6106
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.
@ CCEK_StaticAssertMessageSize
Call to size() in a static assert message.
Definition: Sema.h:10072
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10070
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:10074
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3077
ASTConsumer & Consumer
Definition: Sema.h:1005
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:4280
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9854
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9846
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9850
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5094
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...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
Definition: SemaType.cpp:9490
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5651
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 {'.
Definition: SemaDecl.cpp:17005
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.
Definition: SemaType.cpp:8905
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:965
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18860
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' ...
Definition: SemaAttr.cpp:1373
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...
Definition: SemaInit.cpp:7338
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17673
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7988
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:1007
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:1006
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:7363
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
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...
Definition: SemaDecl.cpp:7192
@ TPC_TypeAliasTemplate
Definition: Sema.h:11344
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,...
Definition: SemaDecl.cpp:6702
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5519
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1313
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2849
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6118
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.
Definition: SemaDecl.cpp:1577
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8800
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.
Definition: SemaDecl.cpp:1562
@ OOK_Outside
Definition: Sema.h:3921
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13272
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:297
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:5861
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,...
Definition: SemaExpr.cpp:17854
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,...
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5885
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20293
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20906
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6037
AbstractDiagSelID
Definition: Sema.h:5807
@ AbstractVariableType
Definition: Sema.h:5811
@ AbstractReturnType
Definition: Sema.h:5809
@ AbstractNone
Definition: Sema.h:5808
@ AbstractFieldType
Definition: Sema.h:5812
@ AbstractArrayType
Definition: Sema.h:5815
@ AbstractParamType
Definition: Sema.h:5810
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:908
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)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1701
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:8033
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14592
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition: Sema.h:6003
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
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)
Definition: SemaType.cpp:2729
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:415
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:3058
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
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)
Definition: SemaDecl.cpp:6024
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.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7369
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.
Definition: SemaExpr.cpp:5306
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:599
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8335
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
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 isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3324
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
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:1778
bool isUnevaluated() const
Definition: Expr.h:1907
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3684
StringRef getKindName() const
Definition: Decl.h:3752
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4725
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4719
bool isUnion() const
Definition: Decl.h:3767
TagKind getTagKind() const
Definition: Decl.h:3756
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3715
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:206
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:593
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
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.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6480
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6548
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6546
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.
unsigned getIndex() const
Definition: Type.h:6173
unsigned getDepth() const
Definition: Type.h:6172
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3532
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5553
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3551
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:3367
const Type * getTypeForDecl() const
Definition: Decl.h:3391
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:170
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:1225
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:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
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:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3151
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6743
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3133
The base class of the type hierarchy.
Definition: Type.h:1829
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2477
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isUndeducedAutoType() const
Definition: Type.h:8162
bool isRValueReferenceType() const
Definition: Type.h:8029
bool isArrayType() const
Definition: Type.h:8075
bool isPointerType() const
Definition: Type.h:8003
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isEnumeralType() const
Definition: Type.h:8107
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3258
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8288
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2354
QualType getCanonicalTypeInternal() const
Definition: Type.h:2978
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2689
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isFunctionProtoType() const
Definition: Type.h:2528
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8460
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
bool isObjCObjectType() const
Definition: Type.h:8149
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isRecordType() const
Definition: Type.h:8103
bool isUnionType() const
Definition: Type.cpp:671
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1890
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
QualType getUnderlyingType() const
Definition: Decl.h:3464
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...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
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:4861
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
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:420
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:90
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4044
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3303
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3963
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3282
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3866
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3254
Represents a C++ using-declaration.
Definition: DeclCXX.h:3516
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3565
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3557
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3188
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3553
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3543
Represents C++ using-directive.
Definition: DeclCXX.h:3019
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2975
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3717
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3209
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3232
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3360
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3388
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3128
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2801
void setCXXCondDecl()
Definition: Decl.h:1560
bool isInlineSpecified() const
Definition: Decl.h:1495
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2539
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2612
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:1156
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2808
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:905
void setInit(Expr *I)
Definition: Decl.cpp:2442
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
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:2493
void setExceptionVariable(bool EV)
Definition: Decl.h:1438
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
QualType getElementType() const
Definition: Type.h:4035
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2783
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2803
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2815
bool isOverrideSpecified() const
Definition: DeclSpec.h:2802
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2807
bool isFinalSpecified() const
Definition: DeclSpec.h:2805
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2806
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
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:776
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2237
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:876
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.
@ 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.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ 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.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus23
Definition: LangStandard.h:61
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus26
Definition: LangStandard.h:62
@ CPlusPlus17
Definition: LangStandard.h:59
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
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2930
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: Type.h:1778
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
@ 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:1538
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:806
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6690
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanPassInRegs
The argument of this type can be passed directly in registers.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1043
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:445
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
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
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:258
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
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
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6665
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ 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)
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
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
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:1368
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1377
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1431
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1529
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1558
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1561
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1467
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1554
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1343
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
enum clang::DeclaratorChunk::@223 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1642
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Holds information about the various types of exception specification.
Definition: Type.h:5059
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5071
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5064
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5067
Extra information about a function prototype.
Definition: Type.h:5087
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5094
FunctionEffectsRef FunctionEffects
Definition: Type.h:5097
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1038
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12715
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12832
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12809
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12806
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12759
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12773
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12777
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12835
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:12861
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7929
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.