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 QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();
7060 for (const CXXBaseSpecifier &B : RD->bases())
7061 if (B.getType().getCanonicalType().getUnqualifiedType() !=
7062 CanUnqualT &&
7063 !Check(B.getType(), Check))
7064 return false;
7065 for (const FieldDecl *FD : RD->fields())
7067 CanUnqualT &&
7068 !Check(FD->getType(), Check))
7069 return false;
7070 return true;
7071 };
7072 EffectivelyConstexprDestructor =
7073 Check(QualType(Record->getTypeForDecl(), 0), Check);
7074 }
7075
7076 // Define defaulted constexpr virtual functions that override a base class
7077 // function right away.
7078 // FIXME: We can defer doing this until the vtable is marked as used.
7079 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7080 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7081 EffectivelyConstexprDestructor)
7082 DefineDefaultedFunction(*this, M, M->getLocation());
7083
7084 if (!Incomplete)
7085 CheckCompletedMemberFunction(M);
7086 };
7087
7088 // Check the destructor before any other member function. We need to
7089 // determine whether it's trivial in order to determine whether the claas
7090 // type is a literal type, which is a prerequisite for determining whether
7091 // other special member functions are valid and whether they're implicitly
7092 // 'constexpr'.
7093 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7094 CompleteMemberFunction(Dtor);
7095
7096 bool HasMethodWithOverrideControl = false,
7097 HasOverridingMethodWithoutOverrideControl = false;
7098 for (auto *D : Record->decls()) {
7099 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7100 // FIXME: We could do this check for dependent types with non-dependent
7101 // bases.
7102 if (!Record->isDependentType()) {
7103 // See if a method overloads virtual methods in a base
7104 // class without overriding any.
7105 if (!M->isStatic())
7107 if (M->hasAttr<OverrideAttr>())
7108 HasMethodWithOverrideControl = true;
7109 else if (M->size_overridden_methods() > 0)
7110 HasOverridingMethodWithoutOverrideControl = true;
7111 }
7112
7113 if (!isa<CXXDestructorDecl>(M))
7114 CompleteMemberFunction(M);
7115 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7116 CheckForDefaultedFunction(
7117 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7118 }
7119 }
7120
7121 if (HasOverridingMethodWithoutOverrideControl) {
7122 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7123 for (auto *M : Record->methods())
7124 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7125 }
7126
7127 // Check the defaulted secondary comparisons after any other member functions.
7128 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7130
7131 // If this is a member function, we deferred checking it until now.
7132 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7133 CheckCompletedMemberFunction(MD);
7134 }
7135
7136 // ms_struct is a request to use the same ABI rules as MSVC. Check
7137 // whether this class uses any C++ features that are implemented
7138 // completely differently in MSVC, and if so, emit a diagnostic.
7139 // That diagnostic defaults to an error, but we allow projects to
7140 // map it down to a warning (or ignore it). It's a fairly common
7141 // practice among users of the ms_struct pragma to mass-annotate
7142 // headers, sweeping up a bunch of types that the project doesn't
7143 // really rely on MSVC-compatible layout for. We must therefore
7144 // support "ms_struct except for C++ stuff" as a secondary ABI.
7145 // Don't emit this diagnostic if the feature was enabled as a
7146 // language option (as opposed to via a pragma or attribute), as
7147 // the option -mms-bitfields otherwise essentially makes it impossible
7148 // to build C++ code, unless this diagnostic is turned off.
7149 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7150 (Record->isPolymorphic() || Record->getNumBases())) {
7151 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7152 }
7153
7156
7157 bool ClangABICompat4 =
7158 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7160 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7161 bool CanPass = canPassInRegisters(*this, Record, CCK);
7162
7163 // Do not change ArgPassingRestrictions if it has already been set to
7164 // RecordArgPassingKind::CanNeverPassInRegs.
7165 if (Record->getArgPassingRestrictions() !=
7167 Record->setArgPassingRestrictions(
7170
7171 // If canPassInRegisters returns true despite the record having a non-trivial
7172 // destructor, the record is destructed in the callee. This happens only when
7173 // the record or one of its subobjects has a field annotated with trivial_abi
7174 // or a field qualified with ObjC __strong/__weak.
7176 Record->setParamDestroyedInCallee(true);
7177 else if (Record->hasNonTrivialDestructor())
7178 Record->setParamDestroyedInCallee(CanPass);
7179
7180 if (getLangOpts().ForceEmitVTables) {
7181 // If we want to emit all the vtables, we need to mark it as used. This
7182 // is especially required for cases like vtable assumption loads.
7183 MarkVTableUsed(Record->getInnerLocStart(), Record);
7184 }
7185
7186 if (getLangOpts().CUDA) {
7187 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7189 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7191 }
7192}
7193
7194/// Look up the special member function that would be called by a special
7195/// member function for a subobject of class type.
7196///
7197/// \param Class The class type of the subobject.
7198/// \param CSM The kind of special member function.
7199/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7200/// \param ConstRHS True if this is a copy operation with a const object
7201/// on its RHS, that is, if the argument to the outer special member
7202/// function is 'const' and this is not a field marked 'mutable'.
7205 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7206 bool ConstRHS) {
7207 unsigned LHSQuals = 0;
7210 LHSQuals = FieldQuals;
7211
7212 unsigned RHSQuals = FieldQuals;
7215 RHSQuals = 0;
7216 else if (ConstRHS)
7217 RHSQuals |= Qualifiers::Const;
7218
7219 return S.LookupSpecialMember(Class, CSM,
7220 RHSQuals & Qualifiers::Const,
7221 RHSQuals & Qualifiers::Volatile,
7222 false,
7223 LHSQuals & Qualifiers::Const,
7224 LHSQuals & Qualifiers::Volatile);
7225}
7226
7228 Sema &S;
7229 SourceLocation UseLoc;
7230
7231 /// A mapping from the base classes through which the constructor was
7232 /// inherited to the using shadow declaration in that base class (or a null
7233 /// pointer if the constructor was declared in that base class).
7234 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7235 InheritedFromBases;
7236
7237public:
7240 : S(S), UseLoc(UseLoc) {
7241 bool DiagnosedMultipleConstructedBases = false;
7242 CXXRecordDecl *ConstructedBase = nullptr;
7243 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7244
7245 // Find the set of such base class subobjects and check that there's a
7246 // unique constructed subobject.
7247 for (auto *D : Shadow->redecls()) {
7248 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7249 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7250 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7251
7252 InheritedFromBases.insert(
7253 std::make_pair(DNominatedBase->getCanonicalDecl(),
7254 DShadow->getNominatedBaseClassShadowDecl()));
7255 if (DShadow->constructsVirtualBase())
7256 InheritedFromBases.insert(
7257 std::make_pair(DConstructedBase->getCanonicalDecl(),
7258 DShadow->getConstructedBaseClassShadowDecl()));
7259 else
7260 assert(DNominatedBase == DConstructedBase);
7261
7262 // [class.inhctor.init]p2:
7263 // If the constructor was inherited from multiple base class subobjects
7264 // of type B, the program is ill-formed.
7265 if (!ConstructedBase) {
7266 ConstructedBase = DConstructedBase;
7267 ConstructedBaseIntroducer = D->getIntroducer();
7268 } else if (ConstructedBase != DConstructedBase &&
7269 !Shadow->isInvalidDecl()) {
7270 if (!DiagnosedMultipleConstructedBases) {
7271 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7272 << Shadow->getTargetDecl();
7273 S.Diag(ConstructedBaseIntroducer->getLocation(),
7274 diag::note_ambiguous_inherited_constructor_using)
7275 << ConstructedBase;
7276 DiagnosedMultipleConstructedBases = true;
7277 }
7278 S.Diag(D->getIntroducer()->getLocation(),
7279 diag::note_ambiguous_inherited_constructor_using)
7280 << DConstructedBase;
7281 }
7282 }
7283
7284 if (DiagnosedMultipleConstructedBases)
7285 Shadow->setInvalidDecl();
7286 }
7287
7288 /// Find the constructor to use for inherited construction of a base class,
7289 /// and whether that base class constructor inherits the constructor from a
7290 /// virtual base class (in which case it won't actually invoke it).
7291 std::pair<CXXConstructorDecl *, bool>
7293 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7294 if (It == InheritedFromBases.end())
7295 return std::make_pair(nullptr, false);
7296
7297 // This is an intermediary class.
7298 if (It->second)
7299 return std::make_pair(
7300 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7301 It->second->constructsVirtualBase());
7302
7303 // This is the base class from which the constructor was inherited.
7304 return std::make_pair(Ctor, false);
7305 }
7306};
7307
7308/// Is the special member function which would be selected to perform the
7309/// specified operation on the specified class type a constexpr constructor?
7311 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7312 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7313 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7314 // Suppress duplicate constraint checking here, in case a constraint check
7315 // caused us to decide to do this. Any truely recursive checks will get
7316 // caught during these checks anyway.
7318
7319 // If we're inheriting a constructor, see if we need to call it for this base
7320 // class.
7321 if (InheritedCtor) {
7323 auto BaseCtor =
7324 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7325 if (BaseCtor)
7326 return BaseCtor->isConstexpr();
7327 }
7328
7330 return ClassDecl->hasConstexprDefaultConstructor();
7332 return ClassDecl->hasConstexprDestructor();
7333
7335 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7336 if (!SMOR.getMethod())
7337 // A constructor we wouldn't select can't be "involved in initializing"
7338 // anything.
7339 return true;
7340 return SMOR.getMethod()->isConstexpr();
7341}
7342
7343/// Determine whether the specified special member function would be constexpr
7344/// if it were implicitly defined.
7346 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7347 CXXConstructorDecl *InheritedCtor = nullptr,
7348 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7349 if (!S.getLangOpts().CPlusPlus11)
7350 return false;
7351
7352 // C++11 [dcl.constexpr]p4:
7353 // In the definition of a constexpr constructor [...]
7354 bool Ctor = true;
7355 switch (CSM) {
7357 if (Inherited)
7358 break;
7359 // Since default constructor lookup is essentially trivial (and cannot
7360 // involve, for instance, template instantiation), we compute whether a
7361 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7362 //
7363 // This is important for performance; we need to know whether the default
7364 // constructor is constexpr to determine whether the type is a literal type.
7365 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7366
7369 // For copy or move constructors, we need to perform overload resolution.
7370 break;
7371
7374 if (!S.getLangOpts().CPlusPlus14)
7375 return false;
7376 // In C++1y, we need to perform overload resolution.
7377 Ctor = false;
7378 break;
7379
7381 return ClassDecl->defaultedDestructorIsConstexpr();
7382
7384 return false;
7385 }
7386
7387 // -- if the class is a non-empty union, or for each non-empty anonymous
7388 // union member of a non-union class, exactly one non-static data member
7389 // shall be initialized; [DR1359]
7390 //
7391 // If we squint, this is guaranteed, since exactly one non-static data member
7392 // will be initialized (if the constructor isn't deleted), we just don't know
7393 // which one.
7394 if (Ctor && ClassDecl->isUnion())
7396 ? ClassDecl->hasInClassInitializer() ||
7397 !ClassDecl->hasVariantMembers()
7398 : true;
7399
7400 // -- the class shall not have any virtual base classes;
7401 if (Ctor && ClassDecl->getNumVBases())
7402 return false;
7403
7404 // C++1y [class.copy]p26:
7405 // -- [the class] is a literal type, and
7406 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7407 return false;
7408
7409 // -- every constructor involved in initializing [...] base class
7410 // sub-objects shall be a constexpr constructor;
7411 // -- the assignment operator selected to copy/move each direct base
7412 // class is a constexpr function, and
7413 if (!S.getLangOpts().CPlusPlus23) {
7414 for (const auto &B : ClassDecl->bases()) {
7415 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7416 if (!BaseType)
7417 continue;
7418 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7419 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7420 InheritedCtor, Inherited))
7421 return false;
7422 }
7423 }
7424
7425 // -- every constructor involved in initializing non-static data members
7426 // [...] shall be a constexpr constructor;
7427 // -- every non-static data member and base class sub-object shall be
7428 // initialized
7429 // -- for each non-static data member of X that is of class type (or array
7430 // thereof), the assignment operator selected to copy/move that member is
7431 // a constexpr function
7432 if (!S.getLangOpts().CPlusPlus23) {
7433 for (const auto *F : ClassDecl->fields()) {
7434 if (F->isInvalidDecl())
7435 continue;
7437 F->hasInClassInitializer())
7438 continue;
7439 QualType BaseType = S.Context.getBaseElementType(F->getType());
7440 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7441 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7442 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7443 BaseType.getCVRQualifiers(),
7444 ConstArg && !F->isMutable()))
7445 return false;
7446 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7447 return false;
7448 }
7449 }
7450 }
7451
7452 // All OK, it's constexpr!
7453 return true;
7454}
7455
7456namespace {
7457/// RAII object to register a defaulted function as having its exception
7458/// specification computed.
7459struct ComputingExceptionSpec {
7460 Sema &S;
7461
7462 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7463 : S(S) {
7467 Ctx.Entity = FD;
7469 }
7470 ~ComputingExceptionSpec() {
7472 }
7473};
7474}
7475
7478 CXXMethodDecl *MD,
7481
7484 FunctionDecl *FD,
7486
7489 auto DFK = S.getDefaultedFunctionKind(FD);
7490 if (DFK.isSpecialMember())
7492 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7493 if (DFK.isComparison())
7495 DFK.asComparison());
7496
7497 auto *CD = cast<CXXConstructorDecl>(FD);
7498 assert(CD->getInheritedConstructor() &&
7499 "only defaulted functions and inherited constructors have implicit "
7500 "exception specs");
7502 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7505}
7506
7508 CXXMethodDecl *MD) {
7510
7511 // Build an exception specification pointing back at this member.
7513 EPI.ExceptionSpec.SourceDecl = MD;
7514
7515 // Set the calling convention to the default for C++ instance methods.
7517 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7518 /*IsCXXMethod=*/true));
7519 return EPI;
7520}
7521
7523 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7525 return;
7526
7527 // Evaluate the exception specification.
7528 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7529 auto ESI = IES.getExceptionSpec();
7530
7531 // Update the type of the special member to use it.
7532 UpdateExceptionSpec(FD, ESI);
7533}
7534
7536 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7537
7539 if (!DefKind) {
7540 assert(FD->getDeclContext()->isDependentContext());
7541 return;
7542 }
7543
7544 if (DefKind.isComparison())
7545 UnusedPrivateFields.clear();
7546
7547 if (DefKind.isSpecialMember()
7548 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7549 DefKind.asSpecialMember(),
7550 FD->getDefaultLoc())
7552 FD->setInvalidDecl();
7553}
7554
7557 SourceLocation DefaultLoc) {
7558 CXXRecordDecl *RD = MD->getParent();
7559
7561 "not an explicitly-defaulted special member");
7562
7563 // Defer all checking for special members of a dependent type.
7564 if (RD->isDependentType())
7565 return false;
7566
7567 // Whether this was the first-declared instance of the constructor.
7568 // This affects whether we implicitly add an exception spec and constexpr.
7569 bool First = MD == MD->getCanonicalDecl();
7570
7571 bool HadError = false;
7572
7573 // C++11 [dcl.fct.def.default]p1:
7574 // A function that is explicitly defaulted shall
7575 // -- be a special member function [...] (checked elsewhere),
7576 // -- have the same type (except for ref-qualifiers, and except that a
7577 // copy operation can take a non-const reference) as an implicit
7578 // declaration, and
7579 // -- not have default arguments.
7580 // C++2a changes the second bullet to instead delete the function if it's
7581 // defaulted on its first declaration, unless it's "an assignment operator,
7582 // and its return type differs or its parameter type is not a reference".
7583 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7584 bool ShouldDeleteForTypeMismatch = false;
7585 unsigned ExpectedParams = 1;
7588 ExpectedParams = 0;
7589 if (MD->getNumExplicitParams() != ExpectedParams) {
7590 // This checks for default arguments: a copy or move constructor with a
7591 // default argument is classified as a default constructor, and assignment
7592 // operations and destructors can't have default arguments.
7593 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7594 << llvm::to_underlying(CSM) << MD->getSourceRange();
7595 HadError = true;
7596 } else if (MD->isVariadic()) {
7597 if (DeleteOnTypeMismatch)
7598 ShouldDeleteForTypeMismatch = true;
7599 else {
7600 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7601 << llvm::to_underlying(CSM) << MD->getSourceRange();
7602 HadError = true;
7603 }
7604 }
7605
7607
7608 bool CanHaveConstParam = false;
7610 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7612 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7613
7614 QualType ReturnType = Context.VoidTy;
7617 // Check for return type matching.
7618 ReturnType = Type->getReturnType();
7620
7621 QualType DeclType = Context.getTypeDeclType(RD);
7623 DeclType, nullptr);
7624 DeclType = Context.getAddrSpaceQualType(
7625 DeclType, ThisType.getQualifiers().getAddressSpace());
7626 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7627
7628 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7629 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7631 << ExpectedReturnType;
7632 HadError = true;
7633 }
7634
7635 // A defaulted special member cannot have cv-qualifiers.
7636 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7637 if (DeleteOnTypeMismatch)
7638 ShouldDeleteForTypeMismatch = true;
7639 else {
7640 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7642 << getLangOpts().CPlusPlus14;
7643 HadError = true;
7644 }
7645 }
7646 // [C++23][dcl.fct.def.default]/p2.2
7647 // if F2 has an implicit object parameter of type “reference to C”,
7648 // F1 may be an explicit object member function whose explicit object
7649 // parameter is of (possibly different) type “reference to C”,
7650 // in which case the type of F1 would differ from the type of F2
7651 // in that the type of F1 has an additional parameter;
7652 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7653 ? MD->getParamDecl(0)->getType()
7654 : QualType();
7655 if (!ExplicitObjectParameter.isNull() &&
7656 (!ExplicitObjectParameter->isReferenceType() ||
7657 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7658 Context.getRecordType(RD)))) {
7659 if (DeleteOnTypeMismatch)
7660 ShouldDeleteForTypeMismatch = true;
7661 else {
7662 Diag(MD->getLocation(),
7663 diag::err_defaulted_special_member_explicit_object_mismatch)
7664 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7665 << MD->getSourceRange();
7666 HadError = true;
7667 }
7668 }
7669 }
7670
7671 // Check for parameter type matching.
7672 QualType ArgType =
7673 ExpectedParams
7674 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7675 : QualType();
7676 bool HasConstParam = false;
7677 if (ExpectedParams && ArgType->isReferenceType()) {
7678 // Argument must be reference to possibly-const T.
7679 QualType ReferentType = ArgType->getPointeeType();
7680 HasConstParam = ReferentType.isConstQualified();
7681
7682 if (ReferentType.isVolatileQualified()) {
7683 if (DeleteOnTypeMismatch)
7684 ShouldDeleteForTypeMismatch = true;
7685 else {
7686 Diag(MD->getLocation(),
7687 diag::err_defaulted_special_member_volatile_param)
7688 << llvm::to_underlying(CSM);
7689 HadError = true;
7690 }
7691 }
7692
7693 if (HasConstParam && !CanHaveConstParam) {
7694 if (DeleteOnTypeMismatch)
7695 ShouldDeleteForTypeMismatch = true;
7696 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7698 Diag(MD->getLocation(),
7699 diag::err_defaulted_special_member_copy_const_param)
7701 // FIXME: Explain why this special member can't be const.
7702 HadError = true;
7703 } else {
7704 Diag(MD->getLocation(),
7705 diag::err_defaulted_special_member_move_const_param)
7707 HadError = true;
7708 }
7709 }
7710 } else if (ExpectedParams) {
7711 // A copy assignment operator can take its argument by value, but a
7712 // defaulted one cannot.
7714 "unexpected non-ref argument");
7715 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7716 HadError = true;
7717 }
7718
7719 // C++11 [dcl.fct.def.default]p2:
7720 // An explicitly-defaulted function may be declared constexpr only if it
7721 // would have been implicitly declared as constexpr,
7722 // Do not apply this rule to members of class templates, since core issue 1358
7723 // makes such functions always instantiate to constexpr functions. For
7724 // functions which cannot be constexpr (for non-constructors in C++11 and for
7725 // destructors in C++14 and C++17), this is checked elsewhere.
7726 //
7727 // FIXME: This should not apply if the member is deleted.
7728 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7729 HasConstParam);
7730
7731 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7732 // If the instantiated template specialization of a constexpr function
7733 // template or member function of a class template would fail to satisfy
7734 // the requirements for a constexpr function or constexpr constructor, that
7735 // specialization is still a constexpr function or constexpr constructor,
7736 // even though a call to such a function cannot appear in a constant
7737 // expression.
7738 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7739 Constexpr = true;
7740
7741 if ((getLangOpts().CPlusPlus20 ||
7742 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7743 : isa<CXXConstructorDecl>(MD))) &&
7744 MD->isConstexpr() && !Constexpr &&
7746 if (!MD->isConsteval() && RD->getNumVBases()) {
7747 Diag(MD->getBeginLoc(),
7748 diag::err_incorrect_defaulted_constexpr_with_vb)
7749 << llvm::to_underlying(CSM);
7750 for (const auto &I : RD->vbases())
7751 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7752 } else {
7753 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7754 << llvm::to_underlying(CSM) << MD->isConsteval();
7755 }
7756 HadError = true;
7757 // FIXME: Explain why the special member can't be constexpr.
7758 }
7759
7760 if (First) {
7761 // C++2a [dcl.fct.def.default]p3:
7762 // If a function is explicitly defaulted on its first declaration, it is
7763 // implicitly considered to be constexpr if the implicit declaration
7764 // would be.
7769
7770 if (!Type->hasExceptionSpec()) {
7771 // C++2a [except.spec]p3:
7772 // If a declaration of a function does not have a noexcept-specifier
7773 // [and] is defaulted on its first declaration, [...] the exception
7774 // specification is as specified below
7775 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7777 EPI.ExceptionSpec.SourceDecl = MD;
7778 MD->setType(
7779 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7780 }
7781 }
7782
7783 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7784 if (First) {
7785 SetDeclDeleted(MD, MD->getLocation());
7786 if (!inTemplateInstantiation() && !HadError) {
7787 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7788 << llvm::to_underlying(CSM);
7789 if (ShouldDeleteForTypeMismatch) {
7790 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7791 << llvm::to_underlying(CSM);
7792 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7793 /*Diagnose*/ true) &&
7794 DefaultLoc.isValid()) {
7795 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7796 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7797 }
7798 }
7799 if (ShouldDeleteForTypeMismatch && !HadError) {
7800 Diag(MD->getLocation(),
7801 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7802 << llvm::to_underlying(CSM);
7803 }
7804 } else {
7805 // C++11 [dcl.fct.def.default]p4:
7806 // [For a] user-provided explicitly-defaulted function [...] if such a
7807 // function is implicitly defined as deleted, the program is ill-formed.
7808 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7809 << llvm::to_underlying(CSM);
7810 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7811 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7812 HadError = true;
7813 }
7814 }
7815
7816 return HadError;
7817}
7818
7819namespace {
7820/// Helper class for building and checking a defaulted comparison.
7821///
7822/// Defaulted functions are built in two phases:
7823///
7824/// * First, the set of operations that the function will perform are
7825/// identified, and some of them are checked. If any of the checked
7826/// operations is invalid in certain ways, the comparison function is
7827/// defined as deleted and no body is built.
7828/// * Then, if the function is not defined as deleted, the body is built.
7829///
7830/// This is accomplished by performing two visitation steps over the eventual
7831/// body of the function.
7832template<typename Derived, typename ResultList, typename Result,
7833 typename Subobject>
7834class DefaultedComparisonVisitor {
7835public:
7836 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7837
7838 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7839 DefaultedComparisonKind DCK)
7840 : S(S), RD(RD), FD(FD), DCK(DCK) {
7841 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7842 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7843 // UnresolvedSet to avoid this copy.
7844 Fns.assign(Info->getUnqualifiedLookups().begin(),
7845 Info->getUnqualifiedLookups().end());
7846 }
7847 }
7848
7849 ResultList visit() {
7850 // The type of an lvalue naming a parameter of this function.
7851 QualType ParamLvalType =
7853
7854 ResultList Results;
7855
7856 switch (DCK) {
7857 case DefaultedComparisonKind::None:
7858 llvm_unreachable("not a defaulted comparison");
7859
7860 case DefaultedComparisonKind::Equal:
7861 case DefaultedComparisonKind::ThreeWay:
7862 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7863 return Results;
7864
7865 case DefaultedComparisonKind::NotEqual:
7866 case DefaultedComparisonKind::Relational:
7867 Results.add(getDerived().visitExpandedSubobject(
7868 ParamLvalType, getDerived().getCompleteObject()));
7869 return Results;
7870 }
7871 llvm_unreachable("");
7872 }
7873
7874protected:
7875 Derived &getDerived() { return static_cast<Derived&>(*this); }
7876
7877 /// Visit the expanded list of subobjects of the given type, as specified in
7878 /// C++2a [class.compare.default].
7879 ///
7880 /// \return \c true if the ResultList object said we're done, \c false if not.
7881 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7882 Qualifiers Quals) {
7883 // C++2a [class.compare.default]p4:
7884 // The direct base class subobjects of C
7885 for (CXXBaseSpecifier &Base : Record->bases())
7886 if (Results.add(getDerived().visitSubobject(
7887 S.Context.getQualifiedType(Base.getType(), Quals),
7888 getDerived().getBase(&Base))))
7889 return true;
7890
7891 // followed by the non-static data members of C
7892 for (FieldDecl *Field : Record->fields()) {
7893 // C++23 [class.bit]p2:
7894 // Unnamed bit-fields are not members ...
7895 if (Field->isUnnamedBitField())
7896 continue;
7897 // Recursively expand anonymous structs.
7898 if (Field->isAnonymousStructOrUnion()) {
7899 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7900 Quals))
7901 return true;
7902 continue;
7903 }
7904
7905 // Figure out the type of an lvalue denoting this field.
7906 Qualifiers FieldQuals = Quals;
7907 if (Field->isMutable())
7908 FieldQuals.removeConst();
7909 QualType FieldType =
7910 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7911
7912 if (Results.add(getDerived().visitSubobject(
7913 FieldType, getDerived().getField(Field))))
7914 return true;
7915 }
7916
7917 // form a list of subobjects.
7918 return false;
7919 }
7920
7921 Result visitSubobject(QualType Type, Subobject Subobj) {
7922 // In that list, any subobject of array type is recursively expanded
7923 const ArrayType *AT = S.Context.getAsArrayType(Type);
7924 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7925 return getDerived().visitSubobjectArray(CAT->getElementType(),
7926 CAT->getSize(), Subobj);
7927 return getDerived().visitExpandedSubobject(Type, Subobj);
7928 }
7929
7930 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7931 Subobject Subobj) {
7932 return getDerived().visitSubobject(Type, Subobj);
7933 }
7934
7935protected:
7936 Sema &S;
7937 CXXRecordDecl *RD;
7938 FunctionDecl *FD;
7939 DefaultedComparisonKind DCK;
7941};
7942
7943/// Information about a defaulted comparison, as determined by
7944/// DefaultedComparisonAnalyzer.
7945struct DefaultedComparisonInfo {
7946 bool Deleted = false;
7947 bool Constexpr = true;
7948 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7949
7950 static DefaultedComparisonInfo deleted() {
7951 DefaultedComparisonInfo Deleted;
7952 Deleted.Deleted = true;
7953 return Deleted;
7954 }
7955
7956 bool add(const DefaultedComparisonInfo &R) {
7957 Deleted |= R.Deleted;
7958 Constexpr &= R.Constexpr;
7959 Category = commonComparisonType(Category, R.Category);
7960 return Deleted;
7961 }
7962};
7963
7964/// An element in the expanded list of subobjects of a defaulted comparison, as
7965/// specified in C++2a [class.compare.default]p4.
7966struct DefaultedComparisonSubobject {
7967 enum { CompleteObject, Member, Base } Kind;
7968 NamedDecl *Decl;
7970};
7971
7972/// A visitor over the notional body of a defaulted comparison that determines
7973/// whether that body would be deleted or constexpr.
7974class DefaultedComparisonAnalyzer
7975 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7976 DefaultedComparisonInfo,
7977 DefaultedComparisonInfo,
7978 DefaultedComparisonSubobject> {
7979public:
7980 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7981
7982private:
7983 DiagnosticKind Diagnose;
7984
7985public:
7986 using Base = DefaultedComparisonVisitor;
7987 using Result = DefaultedComparisonInfo;
7988 using Subobject = DefaultedComparisonSubobject;
7989
7990 friend Base;
7991
7992 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7993 DefaultedComparisonKind DCK,
7994 DiagnosticKind Diagnose = NoDiagnostics)
7995 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7996
7997 Result visit() {
7998 if ((DCK == DefaultedComparisonKind::Equal ||
7999 DCK == DefaultedComparisonKind::ThreeWay) &&
8000 RD->hasVariantMembers()) {
8001 // C++2a [class.compare.default]p2 [P2002R0]:
8002 // A defaulted comparison operator function for class C is defined as
8003 // deleted if [...] C has variant members.
8004 if (Diagnose == ExplainDeleted) {
8005 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8006 << FD << RD->isUnion() << RD;
8007 }
8008 return Result::deleted();
8009 }
8010
8011 return Base::visit();
8012 }
8013
8014private:
8015 Subobject getCompleteObject() {
8016 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8017 }
8018
8019 Subobject getBase(CXXBaseSpecifier *Base) {
8020 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8021 Base->getBaseTypeLoc()};
8022 }
8023
8024 Subobject getField(FieldDecl *Field) {
8025 return Subobject{Subobject::Member, Field, Field->getLocation()};
8026 }
8027
8028 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8029 // C++2a [class.compare.default]p2 [P2002R0]:
8030 // A defaulted <=> or == operator function for class C is defined as
8031 // deleted if any non-static data member of C is of reference type
8032 if (Type->isReferenceType()) {
8033 if (Diagnose == ExplainDeleted) {
8034 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8035 << FD << RD;
8036 }
8037 return Result::deleted();
8038 }
8039
8040 // [...] Let xi be an lvalue denoting the ith element [...]
8042 Expr *Args[] = {&Xi, &Xi};
8043
8044 // All operators start by trying to apply that same operator recursively.
8046 assert(OO != OO_None && "not an overloaded operator!");
8047 return visitBinaryOperator(OO, Args, Subobj);
8048 }
8049
8050 Result
8051 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8052 Subobject Subobj,
8053 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8054 // Note that there is no need to consider rewritten candidates here if
8055 // we've already found there is no viable 'operator<=>' candidate (and are
8056 // considering synthesizing a '<=>' from '==' and '<').
8057 OverloadCandidateSet CandidateSet(
8060 OO, FD->getLocation(),
8061 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8062
8063 /// C++2a [class.compare.default]p1 [P2002R0]:
8064 /// [...] the defaulted function itself is never a candidate for overload
8065 /// resolution [...]
8066 CandidateSet.exclude(FD);
8067
8068 if (Args[0]->getType()->isOverloadableType())
8069 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8070 else
8071 // FIXME: We determine whether this is a valid expression by checking to
8072 // see if there's a viable builtin operator candidate for it. That isn't
8073 // really what the rules ask us to do, but should give the right results.
8074 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8075
8076 Result R;
8077
8079 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8080 case OR_Success: {
8081 // C++2a [class.compare.secondary]p2 [P2002R0]:
8082 // The operator function [...] is defined as deleted if [...] the
8083 // candidate selected by overload resolution is not a rewritten
8084 // candidate.
8085 if ((DCK == DefaultedComparisonKind::NotEqual ||
8086 DCK == DefaultedComparisonKind::Relational) &&
8087 !Best->RewriteKind) {
8088 if (Diagnose == ExplainDeleted) {
8089 if (Best->Function) {
8090 S.Diag(Best->Function->getLocation(),
8091 diag::note_defaulted_comparison_not_rewritten_callee)
8092 << FD;
8093 } else {
8094 assert(Best->Conversions.size() == 2 &&
8095 Best->Conversions[0].isUserDefined() &&
8096 "non-user-defined conversion from class to built-in "
8097 "comparison");
8098 S.Diag(Best->Conversions[0]
8099 .UserDefined.FoundConversionFunction.getDecl()
8100 ->getLocation(),
8101 diag::note_defaulted_comparison_not_rewritten_conversion)
8102 << FD;
8103 }
8104 }
8105 return Result::deleted();
8106 }
8107
8108 // Throughout C++2a [class.compare]: if overload resolution does not
8109 // result in a usable function, the candidate function is defined as
8110 // deleted. This requires that we selected an accessible function.
8111 //
8112 // Note that this only considers the access of the function when named
8113 // within the type of the subobject, and not the access path for any
8114 // derived-to-base conversion.
8115 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8116 if (ArgClass && Best->FoundDecl.getDecl() &&
8117 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8118 QualType ObjectType = Subobj.Kind == Subobject::Member
8119 ? Args[0]->getType()
8120 : S.Context.getRecordType(RD);
8122 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8123 Diagnose == ExplainDeleted
8124 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8125 << FD << Subobj.Kind << Subobj.Decl
8126 : S.PDiag()))
8127 return Result::deleted();
8128 }
8129
8130 bool NeedsDeducing =
8131 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8132
8133 if (FunctionDecl *BestFD = Best->Function) {
8134 // C++2a [class.compare.default]p3 [P2002R0]:
8135 // A defaulted comparison function is constexpr-compatible if
8136 // [...] no overlod resolution performed [...] results in a
8137 // non-constexpr function.
8138 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8139 // If it's not constexpr, explain why not.
8140 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8141 if (Subobj.Kind != Subobject::CompleteObject)
8142 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8143 << Subobj.Kind << Subobj.Decl;
8144 S.Diag(BestFD->getLocation(),
8145 diag::note_defaulted_comparison_not_constexpr_here);
8146 // Bail out after explaining; we don't want any more notes.
8147 return Result::deleted();
8148 }
8149 R.Constexpr &= BestFD->isConstexpr();
8150
8151 if (NeedsDeducing) {
8152 // If any callee has an undeduced return type, deduce it now.
8153 // FIXME: It's not clear how a failure here should be handled. For
8154 // now, we produce an eager diagnostic, because that is forward
8155 // compatible with most (all?) other reasonable options.
8156 if (BestFD->getReturnType()->isUndeducedType() &&
8157 S.DeduceReturnType(BestFD, FD->getLocation(),
8158 /*Diagnose=*/false)) {
8159 // Don't produce a duplicate error when asked to explain why the
8160 // comparison is deleted: we diagnosed that when initially checking
8161 // the defaulted operator.
8162 if (Diagnose == NoDiagnostics) {
8163 S.Diag(
8164 FD->getLocation(),
8165 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8166 << Subobj.Kind << Subobj.Decl;
8167 S.Diag(
8168 Subobj.Loc,
8169 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8170 << Subobj.Kind << Subobj.Decl;
8171 S.Diag(BestFD->getLocation(),
8172 diag::note_defaulted_comparison_cannot_deduce_callee)
8173 << Subobj.Kind << Subobj.Decl;
8174 }
8175 return Result::deleted();
8176 }
8178 BestFD->getCallResultType());
8179 if (!Info) {
8180 if (Diagnose == ExplainDeleted) {
8181 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8182 << Subobj.Kind << Subobj.Decl
8183 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8184 S.Diag(BestFD->getLocation(),
8185 diag::note_defaulted_comparison_cannot_deduce_callee)
8186 << Subobj.Kind << Subobj.Decl;
8187 }
8188 return Result::deleted();
8189 }
8190 R.Category = Info->Kind;
8191 }
8192 } else {
8193 QualType T = Best->BuiltinParamTypes[0];
8194 assert(T == Best->BuiltinParamTypes[1] &&
8195 "builtin comparison for different types?");
8196 assert(Best->BuiltinParamTypes[2].isNull() &&
8197 "invalid builtin comparison");
8198
8199 if (NeedsDeducing) {
8200 std::optional<ComparisonCategoryType> Cat =
8202 assert(Cat && "no category for builtin comparison?");
8203 R.Category = *Cat;
8204 }
8205 }
8206
8207 // Note that we might be rewriting to a different operator. That call is
8208 // not considered until we come to actually build the comparison function.
8209 break;
8210 }
8211
8212 case OR_Ambiguous:
8213 if (Diagnose == ExplainDeleted) {
8214 unsigned Kind = 0;
8215 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8216 Kind = OO == OO_EqualEqual ? 1 : 2;
8217 CandidateSet.NoteCandidates(
8219 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8220 << FD << Kind << Subobj.Kind << Subobj.Decl),
8221 S, OCD_AmbiguousCandidates, Args);
8222 }
8223 R = Result::deleted();
8224 break;
8225
8226 case OR_Deleted:
8227 if (Diagnose == ExplainDeleted) {
8228 if ((DCK == DefaultedComparisonKind::NotEqual ||
8229 DCK == DefaultedComparisonKind::Relational) &&
8230 !Best->RewriteKind) {
8231 S.Diag(Best->Function->getLocation(),
8232 diag::note_defaulted_comparison_not_rewritten_callee)
8233 << FD;
8234 } else {
8235 S.Diag(Subobj.Loc,
8236 diag::note_defaulted_comparison_calls_deleted)
8237 << FD << Subobj.Kind << Subobj.Decl;
8238 S.NoteDeletedFunction(Best->Function);
8239 }
8240 }
8241 R = Result::deleted();
8242 break;
8243
8245 // If there's no usable candidate, we're done unless we can rewrite a
8246 // '<=>' in terms of '==' and '<'.
8247 if (OO == OO_Spaceship &&
8249 // For any kind of comparison category return type, we need a usable
8250 // '==' and a usable '<'.
8251 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8252 &CandidateSet)))
8253 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8254 break;
8255 }
8256
8257 if (Diagnose == ExplainDeleted) {
8258 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8259 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8260 << Subobj.Kind << Subobj.Decl;
8261
8262 // For a three-way comparison, list both the candidates for the
8263 // original operator and the candidates for the synthesized operator.
8264 if (SpaceshipCandidates) {
8265 SpaceshipCandidates->NoteCandidates(
8266 S, Args,
8267 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8268 Args, FD->getLocation()));
8269 S.Diag(Subobj.Loc,
8270 diag::note_defaulted_comparison_no_viable_function_synthesized)
8271 << (OO == OO_EqualEqual ? 0 : 1);
8272 }
8273
8274 CandidateSet.NoteCandidates(
8275 S, Args,
8276 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8277 FD->getLocation()));
8278 }
8279 R = Result::deleted();
8280 break;
8281 }
8282
8283 return R;
8284 }
8285};
8286
8287/// A list of statements.
8288struct StmtListResult {
8289 bool IsInvalid = false;
8291
8292 bool add(const StmtResult &S) {
8293 IsInvalid |= S.isInvalid();
8294 if (IsInvalid)
8295 return true;
8296 Stmts.push_back(S.get());
8297 return false;
8298 }
8299};
8300
8301/// A visitor over the notional body of a defaulted comparison that synthesizes
8302/// the actual body.
8303class DefaultedComparisonSynthesizer
8304 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8305 StmtListResult, StmtResult,
8306 std::pair<ExprResult, ExprResult>> {
8308 unsigned ArrayDepth = 0;
8309
8310public:
8311 using Base = DefaultedComparisonVisitor;
8312 using ExprPair = std::pair<ExprResult, ExprResult>;
8313
8314 friend Base;
8315
8316 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8317 DefaultedComparisonKind DCK,
8318 SourceLocation BodyLoc)
8319 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8320
8321 /// Build a suitable function body for this defaulted comparison operator.
8322 StmtResult build() {
8323 Sema::CompoundScopeRAII CompoundScope(S);
8324
8325 StmtListResult Stmts = visit();
8326 if (Stmts.IsInvalid)
8327 return StmtError();
8328
8329 ExprResult RetVal;
8330 switch (DCK) {
8331 case DefaultedComparisonKind::None:
8332 llvm_unreachable("not a defaulted comparison");
8333
8334 case DefaultedComparisonKind::Equal: {
8335 // C++2a [class.eq]p3:
8336 // [...] compar[e] the corresponding elements [...] until the first
8337 // index i where xi == yi yields [...] false. If no such index exists,
8338 // V is true. Otherwise, V is false.
8339 //
8340 // Join the comparisons with '&&'s and return the result. Use a right
8341 // fold (traversing the conditions right-to-left), because that
8342 // short-circuits more naturally.
8343 auto OldStmts = std::move(Stmts.Stmts);
8344 Stmts.Stmts.clear();
8345 ExprResult CmpSoFar;
8346 // Finish a particular comparison chain.
8347 auto FinishCmp = [&] {
8348 if (Expr *Prior = CmpSoFar.get()) {
8349 // Convert the last expression to 'return ...;'
8350 if (RetVal.isUnset() && Stmts.Stmts.empty())
8351 RetVal = CmpSoFar;
8352 // Convert any prior comparison to 'if (!(...)) return false;'
8353 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8354 return true;
8355 CmpSoFar = ExprResult();
8356 }
8357 return false;
8358 };
8359 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8360 Expr *E = dyn_cast<Expr>(EAsStmt);
8361 if (!E) {
8362 // Found an array comparison.
8363 if (FinishCmp() || Stmts.add(EAsStmt))
8364 return StmtError();
8365 continue;
8366 }
8367
8368 if (CmpSoFar.isUnset()) {
8369 CmpSoFar = E;
8370 continue;
8371 }
8372 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8373 if (CmpSoFar.isInvalid())
8374 return StmtError();
8375 }
8376 if (FinishCmp())
8377 return StmtError();
8378 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8379 // If no such index exists, V is true.
8380 if (RetVal.isUnset())
8381 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8382 break;
8383 }
8384
8385 case DefaultedComparisonKind::ThreeWay: {
8386 // Per C++2a [class.spaceship]p3, as a fallback add:
8387 // return static_cast<R>(std::strong_ordering::equal);
8389 ComparisonCategoryType::StrongOrdering, Loc,
8390 Sema::ComparisonCategoryUsage::DefaultedOperator);
8391 if (StrongOrdering.isNull())
8392 return StmtError();
8394 .getValueInfo(ComparisonCategoryResult::Equal)
8395 ->VD;
8396 RetVal = getDecl(EqualVD);
8397 if (RetVal.isInvalid())
8398 return StmtError();
8399 RetVal = buildStaticCastToR(RetVal.get());
8400 break;
8401 }
8402
8403 case DefaultedComparisonKind::NotEqual:
8404 case DefaultedComparisonKind::Relational:
8405 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8406 break;
8407 }
8408
8409 // Build the final return statement.
8410 if (RetVal.isInvalid())
8411 return StmtError();
8413 if (ReturnStmt.isInvalid())
8414 return StmtError();
8415 Stmts.Stmts.push_back(ReturnStmt.get());
8416
8417 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8418 }
8419
8420private:
8421 ExprResult getDecl(ValueDecl *VD) {
8422 return S.BuildDeclarationNameExpr(
8424 }
8425
8426 ExprResult getParam(unsigned I) {
8427 ParmVarDecl *PD = FD->getParamDecl(I);
8428 return getDecl(PD);
8429 }
8430
8431 ExprPair getCompleteObject() {
8432 unsigned Param = 0;
8433 ExprResult LHS;
8434 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8435 MD && MD->isImplicitObjectMemberFunction()) {
8436 // LHS is '*this'.
8437 LHS = S.ActOnCXXThis(Loc);
8438 if (!LHS.isInvalid())
8439 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8440 } else {
8441 LHS = getParam(Param++);
8442 }
8443 ExprResult RHS = getParam(Param++);
8444 assert(Param == FD->getNumParams());
8445 return {LHS, RHS};
8446 }
8447
8448 ExprPair getBase(CXXBaseSpecifier *Base) {
8449 ExprPair Obj = getCompleteObject();
8450 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8451 return {ExprError(), ExprError()};
8452 CXXCastPath Path = {Base};
8453 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8454 CK_DerivedToBase, VK_LValue, &Path),
8455 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8456 CK_DerivedToBase, VK_LValue, &Path)};
8457 }
8458
8459 ExprPair getField(FieldDecl *Field) {
8460 ExprPair Obj = getCompleteObject();
8461 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8462 return {ExprError(), ExprError()};
8463
8464 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8465 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8466 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8467 CXXScopeSpec(), Field, Found, NameInfo),
8468 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8469 CXXScopeSpec(), Field, Found, NameInfo)};
8470 }
8471
8472 // FIXME: When expanding a subobject, register a note in the code synthesis
8473 // stack to say which subobject we're comparing.
8474
8475 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8476 if (Cond.isInvalid())
8477 return StmtError();
8478
8479 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8480 if (NotCond.isInvalid())
8481 return StmtError();
8482
8483 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8484 assert(!False.isInvalid() && "should never fail");
8485 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8486 if (ReturnFalse.isInvalid())
8487 return StmtError();
8488
8489 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8490 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8491 Sema::ConditionKind::Boolean),
8492 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8493 }
8494
8495 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8496 ExprPair Subobj) {
8497 QualType SizeType = S.Context.getSizeType();
8498 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8499
8500 // Build 'size_t i$n = 0'.
8501 IdentifierInfo *IterationVarName = nullptr;
8502 {
8503 SmallString<8> Str;
8504 llvm::raw_svector_ostream OS(Str);
8505 OS << "i" << ArrayDepth;
8506 IterationVarName = &S.Context.Idents.get(OS.str());
8507 }
8508 VarDecl *IterationVar = VarDecl::Create(
8509 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8511 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8512 IterationVar->setInit(
8513 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8514 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8515
8516 auto IterRef = [&] {
8518 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8519 IterationVar);
8520 assert(!Ref.isInvalid() && "can't reference our own variable?");
8521 return Ref.get();
8522 };
8523
8524 // Build 'i$n != Size'.
8526 Loc, BO_NE, IterRef(),
8527 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8528 assert(!Cond.isInvalid() && "should never fail");
8529
8530 // Build '++i$n'.
8531 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8532 assert(!Inc.isInvalid() && "should never fail");
8533
8534 // Build 'a[i$n]' and 'b[i$n]'.
8535 auto Index = [&](ExprResult E) {
8536 if (E.isInvalid())
8537 return ExprError();
8538 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8539 };
8540 Subobj.first = Index(Subobj.first);
8541 Subobj.second = Index(Subobj.second);
8542
8543 // Compare the array elements.
8544 ++ArrayDepth;
8545 StmtResult Substmt = visitSubobject(Type, Subobj);
8546 --ArrayDepth;
8547
8548 if (Substmt.isInvalid())
8549 return StmtError();
8550
8551 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8552 // For outer levels or for an 'operator<=>' we already have a suitable
8553 // statement that returns as necessary.
8554 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8555 assert(DCK == DefaultedComparisonKind::Equal &&
8556 "should have non-expression statement");
8557 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8558 if (Substmt.isInvalid())
8559 return StmtError();
8560 }
8561
8562 // Build 'for (...) ...'
8563 return S.ActOnForStmt(Loc, Loc, Init,
8564 S.ActOnCondition(nullptr, Loc, Cond.get(),
8565 Sema::ConditionKind::Boolean),
8567 Substmt.get());
8568 }
8569
8570 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8571 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8572 return StmtError();
8573
8576 ExprResult Op;
8577 if (Type->isOverloadableType())
8578 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8579 Obj.second.get(), /*PerformADL=*/true,
8580 /*AllowRewrittenCandidates=*/true, FD);
8581 else
8582 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8583 if (Op.isInvalid())
8584 return StmtError();
8585
8586 switch (DCK) {
8587 case DefaultedComparisonKind::None:
8588 llvm_unreachable("not a defaulted comparison");
8589
8590 case DefaultedComparisonKind::Equal:
8591 // Per C++2a [class.eq]p2, each comparison is individually contextually
8592 // converted to bool.
8594 if (Op.isInvalid())
8595 return StmtError();
8596 return Op.get();
8597
8598 case DefaultedComparisonKind::ThreeWay: {
8599 // Per C++2a [class.spaceship]p3, form:
8600 // if (R cmp = static_cast<R>(op); cmp != 0)
8601 // return cmp;
8602 QualType R = FD->getReturnType();
8603 Op = buildStaticCastToR(Op.get());
8604 if (Op.isInvalid())
8605 return StmtError();
8606
8607 // R cmp = ...;
8608 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8609 VarDecl *VD =
8610 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8612 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8613 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8614
8615 // cmp != 0
8616 ExprResult VDRef = getDecl(VD);
8617 if (VDRef.isInvalid())
8618 return StmtError();
8619 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8620 Expr *Zero =
8623 if (VDRef.get()->getType()->isOverloadableType())
8624 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8625 true, FD);
8626 else
8627 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8628 if (Comp.isInvalid())
8629 return StmtError();
8631 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8632 if (Cond.isInvalid())
8633 return StmtError();
8634
8635 // return cmp;
8636 VDRef = getDecl(VD);
8637 if (VDRef.isInvalid())
8638 return StmtError();
8640 if (ReturnStmt.isInvalid())
8641 return StmtError();
8642
8643 // if (...)
8644 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8645 Loc, ReturnStmt.get(),
8646 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8647 }
8648
8649 case DefaultedComparisonKind::NotEqual:
8650 case DefaultedComparisonKind::Relational:
8651 // C++2a [class.compare.secondary]p2:
8652 // Otherwise, the operator function yields x @ y.
8653 return Op.get();
8654 }
8655 llvm_unreachable("");
8656 }
8657
8658 /// Build "static_cast<R>(E)".
8659 ExprResult buildStaticCastToR(Expr *E) {
8660 QualType R = FD->getReturnType();
8661 assert(!R->isUndeducedType() && "type should have been deduced already");
8662
8663 // Don't bother forming a no-op cast in the common case.
8664 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8665 return E;
8666 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8669 }
8670};
8671}
8672
8673/// Perform the unqualified lookups that might be needed to form a defaulted
8674/// comparison function for the given operator.
8676 UnresolvedSetImpl &Operators,
8678 auto Lookup = [&](OverloadedOperatorKind OO) {
8679 Self.LookupOverloadedOperatorName(OO, S, Operators);
8680 };
8681
8682 // Every defaulted operator looks up itself.
8683 Lookup(Op);
8684 // ... and the rewritten form of itself, if any.
8686 Lookup(ExtraOp);
8687
8688 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8689 // synthesize a three-way comparison from '<' and '=='. In a dependent
8690 // context, we also need to look up '==' in case we implicitly declare a
8691 // defaulted 'operator=='.
8692 if (Op == OO_Spaceship) {
8693 Lookup(OO_ExclaimEqual);
8694 Lookup(OO_Less);
8695 Lookup(OO_EqualEqual);
8696 }
8697}
8698
8701 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8702
8703 // Perform any unqualified lookups we're going to need to default this
8704 // function.
8705 if (S) {
8706 UnresolvedSet<32> Operators;
8707 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8708 FD->getOverloadedOperator());
8711 Context, Operators.pairs()));
8712 }
8713
8714 // C++2a [class.compare.default]p1:
8715 // A defaulted comparison operator function for some class C shall be a
8716 // non-template function declared in the member-specification of C that is
8717 // -- a non-static const non-volatile member of C having one parameter of
8718 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8719 // -- a friend of C having two parameters of type const C& or two
8720 // parameters of type C.
8721
8722 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8723 bool IsMethod = isa<CXXMethodDecl>(FD);
8724 if (IsMethod) {
8725 auto *MD = cast<CXXMethodDecl>(FD);
8726 assert(!MD->isStatic() && "comparison function cannot be a static member");
8727
8728 if (MD->getRefQualifier() == RQ_RValue) {
8729 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8730
8731 // Remove the ref qualifier to recover.
8732 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8733 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8734 EPI.RefQualifier = RQ_None;
8735 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8736 FPT->getParamTypes(), EPI));
8737 }
8738
8739 // If we're out-of-class, this is the class we're comparing.
8740 if (!RD)
8741 RD = MD->getParent();
8743 if (!T.getNonReferenceType().isConstQualified() &&
8745 SourceLocation Loc, InsertLoc;
8747 Loc = MD->getParamDecl(0)->getBeginLoc();
8748 InsertLoc = getLocForEndOfToken(
8750 } else {
8751 Loc = MD->getLocation();
8753 InsertLoc = Loc.getRParenLoc();
8754 }
8755 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8756 // corresponding defaulted 'operator<=>' already.
8757 if (!MD->isImplicit()) {
8758 Diag(Loc, diag::err_defaulted_comparison_non_const)
8759 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8760 }
8761
8762 // Add the 'const' to the type to recover.
8764 assert(T->isLValueReferenceType());
8766 T.getNonReferenceType().withConst()));
8767 } else {
8768 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8769 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8770 EPI.TypeQuals.addConst();
8771 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8772 FPT->getParamTypes(), EPI));
8773 }
8774 }
8775
8776 if (MD->isVolatile()) {
8777 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8778
8779 // Remove the 'volatile' from the type to recover.
8780 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8781 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8783 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8784 FPT->getParamTypes(), EPI));
8785 }
8786 }
8787
8788 if ((FD->getNumParams() -
8789 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8790 (IsMethod ? 1 : 2)) {
8791 // Let's not worry about using a variadic template pack here -- who would do
8792 // such a thing?
8793 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8794 << int(IsMethod) << int(DCK);
8795 return true;
8796 }
8797
8798 const ParmVarDecl *KnownParm = nullptr;
8799 for (const ParmVarDecl *Param : FD->parameters()) {
8800 QualType ParmTy = Param->getType();
8801 if (!KnownParm) {
8802 auto CTy = ParmTy;
8803 // Is it `T const &`?
8804 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8805 QualType ExpectedTy;
8806 if (RD)
8807 ExpectedTy = Context.getRecordType(RD);
8808 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8809 CTy = Ref->getPointeeType();
8810 if (RD)
8811 ExpectedTy.addConst();
8812 Ok = true;
8813 }
8814
8815 // Is T a class?
8816 if (RD) {
8817 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
8818 } else {
8819 RD = CTy->getAsCXXRecordDecl();
8820 Ok &= RD != nullptr;
8821 }
8822
8823 if (Ok) {
8824 KnownParm = Param;
8825 } else {
8826 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8827 // corresponding defaulted 'operator<=>' already.
8828 if (!FD->isImplicit()) {
8829 if (RD) {
8830 QualType PlainTy = Context.getRecordType(RD);
8831 QualType RefTy =
8833 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8834 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8835 << Param->getSourceRange();
8836 } else {
8837 assert(!IsMethod && "should know expected type for method");
8838 Diag(FD->getLocation(),
8839 diag::err_defaulted_comparison_param_unknown)
8840 << int(DCK) << ParmTy << Param->getSourceRange();
8841 }
8842 }
8843 return true;
8844 }
8845 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8846 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8847 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8848 << ParmTy << Param->getSourceRange();
8849 return true;
8850 }
8851 }
8852
8853 assert(RD && "must have determined class");
8854 if (IsMethod) {
8855 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8856 // In-class, must be a friend decl.
8857 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8858 } else {
8859 // Out of class, require the defaulted comparison to be a friend (of a
8860 // complete type, per CWG2547).
8862 diag::err_defaulted_comparison_not_friend, int(DCK),
8863 int(1)))
8864 return true;
8865
8866 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8867 return FD->getCanonicalDecl() ==
8868 F->getFriendDecl()->getCanonicalDecl();
8869 })) {
8870 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8871 << int(DCK) << int(0) << RD;
8872 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8873 return true;
8874 }
8875 }
8876
8877 // C++2a [class.eq]p1, [class.rel]p1:
8878 // A [defaulted comparison other than <=>] shall have a declared return
8879 // type bool.
8883 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8884 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8885 << FD->getReturnTypeSourceRange();
8886 return true;
8887 }
8888 // C++2a [class.spaceship]p2 [P2002R0]:
8889 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8890 // R shall not contain a placeholder type.
8891 if (QualType RT = FD->getDeclaredReturnType();
8893 RT->getContainedDeducedType() &&
8895 RT->getContainedAutoType()->isConstrained())) {
8896 Diag(FD->getLocation(),
8897 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8898 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8899 << FD->getReturnTypeSourceRange();
8900 return true;
8901 }
8902
8903 // For a defaulted function in a dependent class, defer all remaining checks
8904 // until instantiation.
8905 if (RD->isDependentType())
8906 return false;
8907
8908 // Determine whether the function should be defined as deleted.
8909 DefaultedComparisonInfo Info =
8910 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8911
8912 bool First = FD == FD->getCanonicalDecl();
8913
8914 if (!First) {
8915 if (Info.Deleted) {
8916 // C++11 [dcl.fct.def.default]p4:
8917 // [For a] user-provided explicitly-defaulted function [...] if such a
8918 // function is implicitly defined as deleted, the program is ill-formed.
8919 //
8920 // This is really just a consequence of the general rule that you can
8921 // only delete a function on its first declaration.
8922 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8923 << FD->isImplicit() << (int)DCK;
8924 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8925 DefaultedComparisonAnalyzer::ExplainDeleted)
8926 .visit();
8927 return true;
8928 }
8929 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8930 // C++20 [class.compare.default]p1:
8931 // [...] A definition of a comparison operator as defaulted that appears
8932 // in a class shall be the first declaration of that function.
8933 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8934 << (int)DCK;
8936 diag::note_previous_declaration);
8937 return true;
8938 }
8939 }
8940
8941 // If we want to delete the function, then do so; there's nothing else to
8942 // check in that case.
8943 if (Info.Deleted) {
8944 SetDeclDeleted(FD, FD->getLocation());
8945 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8946 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8947 << (int)DCK;
8948 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8949 DefaultedComparisonAnalyzer::ExplainDeleted)
8950 .visit();
8951 if (FD->getDefaultLoc().isValid())
8952 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8953 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8954 }
8955 return false;
8956 }
8957
8958 // C++2a [class.spaceship]p2:
8959 // The return type is deduced as the common comparison type of R0, R1, ...
8963 if (RetLoc.isInvalid())
8964 RetLoc = FD->getBeginLoc();
8965 // FIXME: Should we really care whether we have the complete type and the
8966 // 'enumerator' constants here? A forward declaration seems sufficient.
8968 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8969 if (Cat.isNull())
8970 return true;
8972 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8973 }
8974
8975 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8976 // An explicitly-defaulted function that is not defined as deleted may be
8977 // declared constexpr or consteval only if it is constexpr-compatible.
8978 // C++2a [class.compare.default]p3 [P2002R0]:
8979 // A defaulted comparison function is constexpr-compatible if it satisfies
8980 // the requirements for a constexpr function [...]
8981 // The only relevant requirements are that the parameter and return types are
8982 // literal types. The remaining conditions are checked by the analyzer.
8983 //
8984 // We support P2448R2 in language modes earlier than C++23 as an extension.
8985 // The concept of constexpr-compatible was removed.
8986 // C++23 [dcl.fct.def.default]p3 [P2448R2]
8987 // A function explicitly defaulted on its first declaration is implicitly
8988 // inline, and is implicitly constexpr if it is constexpr-suitable.
8989 // C++23 [dcl.constexpr]p3
8990 // A function is constexpr-suitable if
8991 // - it is not a coroutine, and
8992 // - if the function is a constructor or destructor, its class does not
8993 // have any virtual base classes.
8994 if (FD->isConstexpr()) {
8995 if (!getLangOpts().CPlusPlus23 &&
8998 !Info.Constexpr) {
8999 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9000 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9001 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9002 DefaultedComparisonAnalyzer::ExplainConstexpr)
9003 .visit();
9004 }
9005 }
9006
9007 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9008 // If a constexpr-compatible function is explicitly defaulted on its first
9009 // declaration, it is implicitly considered to be constexpr.
9010 // FIXME: Only applying this to the first declaration seems problematic, as
9011 // simple reorderings can affect the meaning of the program.
9012 if (First && !FD->isConstexpr() && Info.Constexpr)
9014
9015 // C++2a [except.spec]p3:
9016 // If a declaration of a function does not have a noexcept-specifier
9017 // [and] is defaulted on its first declaration, [...] the exception
9018 // specification is as specified below
9019 if (FD->getExceptionSpecType() == EST_None) {
9020 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9021 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9023 EPI.ExceptionSpec.SourceDecl = FD;
9024 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9025 FPT->getParamTypes(), EPI));
9026 }
9027
9028 return false;
9029}
9030
9032 FunctionDecl *Spaceship) {
9035 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9036 Ctx.Entity = Spaceship;
9038
9039 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9040 EqualEqual->setImplicit();
9041
9043}
9044
9047 assert(FD->isDefaulted() && !FD->isDeleted() &&
9049 if (FD->willHaveBody() || FD->isInvalidDecl())
9050 return;
9051
9053
9054 // Add a context note for diagnostics produced after this point.
9055 Scope.addContextNote(UseLoc);
9056
9057 {
9058 // Build and set up the function body.
9059 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9060 // the type of the class being compared.
9061 auto PT = FD->getParamDecl(0)->getType();
9062 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9063 SourceLocation BodyLoc =
9064 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9065 StmtResult Body =
9066 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9067 if (Body.isInvalid()) {
9068 FD->setInvalidDecl();
9069 return;
9070 }
9071 FD->setBody(Body.get());
9072 FD->markUsed(Context);
9073 }
9074
9075 // The exception specification is needed because we are defining the
9076 // function. Note that this will reuse the body we just built.
9078
9080 L->CompletedImplicitDefinition(FD);
9081}
9082
9085 FunctionDecl *FD,
9087 ComputingExceptionSpec CES(S, FD, Loc);
9089
9090 if (FD->isInvalidDecl())
9091 return ExceptSpec;
9092
9093 // The common case is that we just defined the comparison function. In that
9094 // case, just look at whether the body can throw.
9095 if (FD->hasBody()) {
9096 ExceptSpec.CalledStmt(FD->getBody());
9097 } else {
9098 // Otherwise, build a body so we can check it. This should ideally only
9099 // happen when we're not actually marking the function referenced. (This is
9100 // only really important for efficiency: we don't want to build and throw
9101 // away bodies for comparison functions more than we strictly need to.)
9102
9103 // Pretend to synthesize the function body in an unevaluated context.
9104 // Note that we can't actually just go ahead and define the function here:
9105 // we are not permitted to mark its callees as referenced.
9109
9110 CXXRecordDecl *RD =
9111 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9112 ? FD->getDeclContext()
9113 : FD->getLexicalDeclContext());
9114 SourceLocation BodyLoc =
9115 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9116 StmtResult Body =
9117 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9118 if (!Body.isInvalid())
9119 ExceptSpec.CalledStmt(Body.get());
9120
9121 // FIXME: Can we hold onto this body and just transform it to potentially
9122 // evaluated when we're asked to define the function rather than rebuilding
9123 // it? Either that, or we should only build the bits of the body that we
9124 // need (the expressions, not the statements).
9125 }
9126
9127 return ExceptSpec;
9128}
9129
9131 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9133
9134 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9136
9137 // Perform any deferred checking of exception specifications for virtual
9138 // destructors.
9139 for (auto &Check : Overriding)
9140 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9141
9142 // Perform any deferred checking of exception specifications for befriended
9143 // special members.
9144 for (auto &Check : Equivalent)
9145 CheckEquivalentExceptionSpec(Check.second, Check.first);
9146}
9147
9148namespace {
9149/// CRTP base class for visiting operations performed by a special member
9150/// function (or inherited constructor).
9151template<typename Derived>
9152struct SpecialMemberVisitor {
9153 Sema &S;
9154 CXXMethodDecl *MD;
9157
9158 // Properties of the special member, computed for convenience.
9159 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9160
9161 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9163 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9164 switch (CSM) {
9165 case CXXSpecialMemberKind::DefaultConstructor:
9166 case CXXSpecialMemberKind::CopyConstructor:
9167 case CXXSpecialMemberKind::MoveConstructor:
9168 IsConstructor = true;
9169 break;
9170 case CXXSpecialMemberKind::CopyAssignment:
9171 case CXXSpecialMemberKind::MoveAssignment:
9172 IsAssignment = true;
9173 break;
9174 case CXXSpecialMemberKind::Destructor:
9175 break;
9176 case CXXSpecialMemberKind::Invalid:
9177 llvm_unreachable("invalid special member kind");
9178 }
9179
9180 if (MD->getNumExplicitParams()) {
9181 if (const ReferenceType *RT =
9183 ConstArg = RT->getPointeeType().isConstQualified();
9184 }
9185 }
9186
9187 Derived &getDerived() { return static_cast<Derived&>(*this); }
9188
9189 /// Is this a "move" special member?
9190 bool isMove() const {
9191 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9192 CSM == CXXSpecialMemberKind::MoveAssignment;
9193 }
9194
9195 /// Look up the corresponding special member in the given class.
9197 unsigned Quals, bool IsMutable) {
9198 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9199 ConstArg && !IsMutable);
9200 }
9201
9202 /// Look up the constructor for the specified base class to see if it's
9203 /// overridden due to this being an inherited constructor.
9204 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9205 if (!ICI)
9206 return {};
9207 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9208 auto *BaseCtor =
9209 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9210 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9211 return MD;
9212 return {};
9213 }
9214
9215 /// A base or member subobject.
9216 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9217
9218 /// Get the location to use for a subobject in diagnostics.
9219 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9220 // FIXME: For an indirect virtual base, the direct base leading to
9221 // the indirect virtual base would be a more useful choice.
9222 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9223 return B->getBaseTypeLoc();
9224 else
9225 return Subobj.get<FieldDecl*>()->getLocation();
9226 }
9227
9228 enum BasesToVisit {
9229 /// Visit all non-virtual (direct) bases.
9230 VisitNonVirtualBases,
9231 /// Visit all direct bases, virtual or not.
9232 VisitDirectBases,
9233 /// Visit all non-virtual bases, and all virtual bases if the class
9234 /// is not abstract.
9235 VisitPotentiallyConstructedBases,
9236 /// Visit all direct or virtual bases.
9237 VisitAllBases
9238 };
9239
9240 // Visit the bases and members of the class.
9241 bool visit(BasesToVisit Bases) {
9242 CXXRecordDecl *RD = MD->getParent();
9243
9244 if (Bases == VisitPotentiallyConstructedBases)
9245 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9246
9247 for (auto &B : RD->bases())
9248 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9249 getDerived().visitBase(&B))
9250 return true;
9251
9252 if (Bases == VisitAllBases)
9253 for (auto &B : RD->vbases())
9254 if (getDerived().visitBase(&B))
9255 return true;
9256
9257 for (auto *F : RD->fields())
9258 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9259 getDerived().visitField(F))
9260 return true;
9261
9262 return false;
9263 }
9264};
9265}
9266
9267namespace {
9268struct SpecialMemberDeletionInfo
9269 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9270 bool Diagnose;
9271
9273
9274 bool AllFieldsAreConst;
9275
9276 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9278 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9279 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9280 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9281
9282 bool inUnion() const { return MD->getParent()->isUnion(); }
9283
9284 CXXSpecialMemberKind getEffectiveCSM() {
9285 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9286 }
9287
9288 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9289
9290 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9291 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9292
9293 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9294 bool shouldDeleteForField(FieldDecl *FD);
9295 bool shouldDeleteForAllConstMembers();
9296
9297 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9298 unsigned Quals);
9299 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9301 bool IsDtorCallInCtor);
9302
9303 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9304};
9305}
9306
9307/// Is the given special member inaccessible when used on the given
9308/// sub-object.
9309bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9310 CXXMethodDecl *target) {
9311 /// If we're operating on a base class, the object type is the
9312 /// type of this special member.
9313 QualType objectTy;
9314 AccessSpecifier access = target->getAccess();
9315 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9316 objectTy = S.Context.getTypeDeclType(MD->getParent());
9317 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9318
9319 // If we're operating on a field, the object type is the type of the field.
9320 } else {
9321 objectTy = S.Context.getTypeDeclType(target->getParent());
9322 }
9323
9325 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9326}
9327
9328/// Check whether we should delete a special member due to the implicit
9329/// definition containing a call to a special member of a subobject.
9330bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9331 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9332 bool IsDtorCallInCtor) {
9333 CXXMethodDecl *Decl = SMOR.getMethod();
9334 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9335
9336 int DiagKind = -1;
9337
9339 DiagKind = !Decl ? 0 : 1;
9341 DiagKind = 2;
9342 else if (!isAccessible(Subobj, Decl))
9343 DiagKind = 3;
9344 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9345 !Decl->isTrivial()) {
9346 // A member of a union must have a trivial corresponding special member.
9347 // As a weird special case, a destructor call from a union's constructor
9348 // must be accessible and non-deleted, but need not be trivial. Such a
9349 // destructor is never actually called, but is semantically checked as
9350 // if it were.
9352 // [class.default.ctor]p2:
9353 // A defaulted default constructor for class X is defined as deleted if
9354 // - X is a union that has a variant member with a non-trivial default
9355 // constructor and no variant member of X has a default member
9356 // initializer
9357 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9358 if (!RD->hasInClassInitializer())
9359 DiagKind = 4;
9360 } else {
9361 DiagKind = 4;
9362 }
9363 }
9364
9365 if (DiagKind == -1)
9366 return false;
9367
9368 if (Diagnose) {
9369 if (Field) {
9370 S.Diag(Field->getLocation(),
9371 diag::note_deleted_special_member_class_subobject)
9372 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9373 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9374 << /*IsObjCPtr*/ false;
9375 } else {
9376 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9377 S.Diag(Base->getBeginLoc(),
9378 diag::note_deleted_special_member_class_subobject)
9379 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9380 << /*IsField*/ false << Base->getType() << DiagKind
9381 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9382 }
9383
9384 if (DiagKind == 1)
9386 // FIXME: Explain inaccessibility if DiagKind == 3.
9387 }
9388
9389 return true;
9390}
9391
9392/// Check whether we should delete a special member function due to having a
9393/// direct or virtual base class or non-static data member of class type M.
9394bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9395 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9396 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9397 bool IsMutable = Field && Field->isMutable();
9398
9399 // C++11 [class.ctor]p5:
9400 // -- any direct or virtual base class, or non-static data member with no
9401 // brace-or-equal-initializer, has class type M (or array thereof) and
9402 // either M has no default constructor or overload resolution as applied
9403 // to M's default constructor results in an ambiguity or in a function
9404 // that is deleted or inaccessible
9405 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9406 // -- a direct or virtual base class B that cannot be copied/moved because
9407 // overload resolution, as applied to B's corresponding special member,
9408 // results in an ambiguity or a function that is deleted or inaccessible
9409 // from the defaulted special member
9410 // C++11 [class.dtor]p5:
9411 // -- any direct or virtual base class [...] has a type with a destructor
9412 // that is deleted or inaccessible
9413 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9414 Field->hasInClassInitializer()) &&
9415 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9416 false))
9417 return true;
9418
9419 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9420 // -- any direct or virtual base class or non-static data member has a
9421 // type with a destructor that is deleted or inaccessible
9422 if (IsConstructor) {
9425 false, false, false, false);
9426 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9427 return true;
9428 }
9429
9430 return false;
9431}
9432
9433bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9434 FieldDecl *FD, QualType FieldType) {
9435 // The defaulted special functions are defined as deleted if this is a variant
9436 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9437 // type under ARC.
9438 if (!FieldType.hasNonTrivialObjCLifetime())
9439 return false;
9440
9441 // Don't make the defaulted default constructor defined as deleted if the
9442 // member has an in-class initializer.
9445 return false;
9446
9447 if (Diagnose) {
9448 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9449 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9450 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9451 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9452 << /*IsObjCPtr*/ true;
9453 }
9454
9455 return true;
9456}
9457
9458/// Check whether we should delete a special member function due to the class
9459/// having a particular direct or virtual base class.
9460bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9461 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9462 // If program is correct, BaseClass cannot be null, but if it is, the error
9463 // must be reported elsewhere.
9464 if (!BaseClass)
9465 return false;
9466 // If we have an inheriting constructor, check whether we're calling an
9467 // inherited constructor instead of a default constructor.
9468 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9469 if (auto *BaseCtor = SMOR.getMethod()) {
9470 // Note that we do not check access along this path; other than that,
9471 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9472 // FIXME: Check that the base has a usable destructor! Sink this into
9473 // shouldDeleteForClassSubobject.
9474 if (BaseCtor->isDeleted() && Diagnose) {
9475 S.Diag(Base->getBeginLoc(),
9476 diag::note_deleted_special_member_class_subobject)
9477 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9478 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9479 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9480 S.NoteDeletedFunction(BaseCtor);
9481 }
9482 return BaseCtor->isDeleted();
9483 }
9484 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9485}
9486
9487/// Check whether we should delete a special member function due to the class
9488/// having a particular non-static data member.
9489bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9490 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9491 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9492
9493 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9494 return true;
9495
9497 // For a default constructor, all references must be initialized in-class
9498 // and, if a union, it must have a non-const member.
9499 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9500 if (Diagnose)
9501 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9502 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9503 return true;
9504 }
9505 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9506 // data member of const-qualified type (or array thereof) with no
9507 // brace-or-equal-initializer is not const-default-constructible.
9508 if (!inUnion() && FieldType.isConstQualified() &&
9509 !FD->hasInClassInitializer() &&
9510 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9511 if (Diagnose)
9512 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9513 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9514 return true;
9515 }
9516
9517 if (inUnion() && !FieldType.isConstQualified())
9518 AllFieldsAreConst = false;
9519 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9520 // For a copy constructor, data members must not be of rvalue reference
9521 // type.
9522 if (FieldType->isRValueReferenceType()) {
9523 if (Diagnose)
9524 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9525 << MD->getParent() << FD << FieldType;
9526 return true;
9527 }
9528 } else if (IsAssignment) {
9529 // For an assignment operator, data members must not be of reference type.
9530 if (FieldType->isReferenceType()) {
9531 if (Diagnose)
9532 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9533 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9534 return true;
9535 }
9536 if (!FieldRecord && FieldType.isConstQualified()) {
9537 // C++11 [class.copy]p23:
9538 // -- a non-static data member of const non-class type (or array thereof)
9539 if (Diagnose)
9540 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9541 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9542 return true;
9543 }
9544 }
9545
9546 if (FieldRecord) {
9547 // Some additional restrictions exist on the variant members.
9548 if (!inUnion() && FieldRecord->isUnion() &&
9549 FieldRecord->isAnonymousStructOrUnion()) {
9550 bool AllVariantFieldsAreConst = true;
9551
9552 // FIXME: Handle anonymous unions declared within anonymous unions.
9553 for (auto *UI : FieldRecord->fields()) {
9554 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9555
9556 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9557 return true;
9558
9559 if (!UnionFieldType.isConstQualified())
9560 AllVariantFieldsAreConst = false;
9561
9562 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9563 if (UnionFieldRecord &&
9564 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9565 UnionFieldType.getCVRQualifiers()))
9566 return true;
9567 }
9568
9569 // At least one member in each anonymous union must be non-const
9571 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9572 if (Diagnose)
9573 S.Diag(FieldRecord->getLocation(),
9574 diag::note_deleted_default_ctor_all_const)
9575 << !!ICI << MD->getParent() << /*anonymous union*/1;
9576 return true;
9577 }
9578
9579 // Don't check the implicit member of the anonymous union type.
9580 // This is technically non-conformant but supported, and we have a
9581 // diagnostic for this elsewhere.
9582 return false;
9583 }
9584
9585 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9586 FieldType.getCVRQualifiers()))
9587 return true;
9588 }
9589
9590 return false;
9591}
9592
9593/// C++11 [class.ctor] p5:
9594/// A defaulted default constructor for a class X is defined as deleted if
9595/// X is a union and all of its variant members are of const-qualified type.
9596bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9597 // This is a silly definition, because it gives an empty union a deleted
9598 // default constructor. Don't do that.
9599 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9600 AllFieldsAreConst) {
9601 bool AnyFields = false;
9602 for (auto *F : MD->getParent()->fields())
9603 if ((AnyFields = !F->isUnnamedBitField()))
9604 break;
9605 if (!AnyFields)
9606 return false;
9607 if (Diagnose)
9608 S.Diag(MD->getParent()->getLocation(),
9609 diag::note_deleted_default_ctor_all_const)
9610 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9611 return true;
9612 }
9613 return false;
9614}
9615
9616/// Determine whether a defaulted special member function should be defined as
9617/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9618/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9622 bool Diagnose) {
9623 if (MD->isInvalidDecl())
9624 return false;
9625 CXXRecordDecl *RD = MD->getParent();
9626 assert(!RD->isDependentType() && "do deletion after instantiation");
9627 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9628 RD->isInvalidDecl())
9629 return false;
9630
9631 // C++11 [expr.lambda.prim]p19:
9632 // The closure type associated with a lambda-expression has a
9633 // deleted (8.4.3) default constructor and a deleted copy
9634 // assignment operator.
9635 // C++2a adds back these operators if the lambda has no lambda-capture.
9639 if (Diagnose)
9640 Diag(RD->getLocation(), diag::note_lambda_decl);
9641 return true;
9642 }
9643
9644 // For an anonymous struct or union, the copy and assignment special members
9645 // will never be used, so skip the check. For an anonymous union declared at
9646 // namespace scope, the constructor and destructor are used.
9649 return false;
9650
9651 // C++11 [class.copy]p7, p18:
9652 // If the class definition declares a move constructor or move assignment
9653 // operator, an implicitly declared copy constructor or copy assignment
9654 // operator is defined as deleted.
9657 CXXMethodDecl *UserDeclaredMove = nullptr;
9658
9659 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9660 // deletion of the corresponding copy operation, not both copy operations.
9661 // MSVC 2015 has adopted the standards conforming behavior.
9662 bool DeletesOnlyMatchingCopy =
9663 getLangOpts().MSVCCompat &&
9665
9667 (!DeletesOnlyMatchingCopy ||
9669 if (!Diagnose) return true;
9670
9671 // Find any user-declared move constructor.
9672 for (auto *I : RD->ctors()) {
9673 if (I->isMoveConstructor()) {
9674 UserDeclaredMove = I;
9675 break;
9676 }
9677 }
9678 assert(UserDeclaredMove);
9679 } else if (RD->hasUserDeclaredMoveAssignment() &&
9680 (!DeletesOnlyMatchingCopy ||
9682 if (!Diagnose) return true;
9683
9684 // Find any user-declared move assignment operator.
9685 for (auto *I : RD->methods()) {
9686 if (I->isMoveAssignmentOperator()) {
9687 UserDeclaredMove = I;
9688 break;
9689 }
9690 }
9691 assert(UserDeclaredMove);
9692 }
9693
9694 if (UserDeclaredMove) {
9695 Diag(UserDeclaredMove->getLocation(),
9696 diag::note_deleted_copy_user_declared_move)
9697 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9698 << UserDeclaredMove->isMoveAssignmentOperator();
9699 return true;
9700 }
9701 }
9702
9703 // Do access control from the special member function
9704 ContextRAII MethodContext(*this, MD);
9705
9706 // C++11 [class.dtor]p5:
9707 // -- for a virtual destructor, lookup of the non-array deallocation function
9708 // results in an ambiguity or in a function that is deleted or inaccessible
9709 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9710 FunctionDecl *OperatorDelete = nullptr;
9711 DeclarationName Name =
9713 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9714 OperatorDelete, /*Diagnose*/false)) {
9715 if (Diagnose)
9716 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9717 return true;
9718 }
9719 }
9720
9721 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9722
9723 // Per DR1611, do not consider virtual bases of constructors of abstract
9724 // classes, since we are not going to construct them.
9725 // Per DR1658, do not consider virtual bases of destructors of abstract
9726 // classes either.
9727 // Per DR2180, for assignment operators we only assign (and thus only
9728 // consider) direct bases.
9729 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9730 : SMI.VisitPotentiallyConstructedBases))
9731 return true;
9732
9733 if (SMI.shouldDeleteForAllConstMembers())
9734 return true;
9735
9736 if (getLangOpts().CUDA) {
9737 // We should delete the special member in CUDA mode if target inference
9738 // failed.
9739 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9740 // is treated as certain special member, which may not reflect what special
9741 // member MD really is. However inferTargetForImplicitSpecialMember
9742 // expects CSM to match MD, therefore recalculate CSM.
9743 assert(ICI || CSM == getSpecialMember(MD));
9744 auto RealCSM = CSM;
9745 if (ICI)
9746 RealCSM = getSpecialMember(MD);
9747
9748 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9749 SMI.ConstArg, Diagnose);
9750 }
9751
9752 return false;
9753}
9754
9757 assert(DFK && "not a defaultable function");
9758 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9759
9760 if (DFK.isSpecialMember()) {
9761 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9762 nullptr, /*Diagnose=*/true);
9763 } else {
9764 DefaultedComparisonAnalyzer(
9765 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9766 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9767 .visit();
9768 }
9769}
9770
9771/// Perform lookup for a special member of the specified kind, and determine
9772/// whether it is trivial. If the triviality can be determined without the
9773/// lookup, skip it. This is intended for use when determining whether a
9774/// special member of a containing object is trivial, and thus does not ever
9775/// perform overload resolution for default constructors.
9776///
9777/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9778/// member that was most likely to be intended to be trivial, if any.
9779///
9780/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9781/// determine whether the special member is trivial.
9783 CXXSpecialMemberKind CSM, unsigned Quals,
9784 bool ConstRHS,
9786 CXXMethodDecl **Selected) {
9787 if (Selected)
9788 *Selected = nullptr;
9789
9790 switch (CSM) {
9792 llvm_unreachable("not a special member");
9793
9795 // C++11 [class.ctor]p5:
9796 // A default constructor is trivial if:
9797 // - all the [direct subobjects] have trivial default constructors
9798 //
9799 // Note, no overload resolution is performed in this case.
9801 return true;
9802
9803 if (Selected) {
9804 // If there's a default constructor which could have been trivial, dig it
9805 // out. Otherwise, if there's any user-provided default constructor, point
9806 // to that as an example of why there's not a trivial one.
9807 CXXConstructorDecl *DefCtor = nullptr;
9810 for (auto *CI : RD->ctors()) {
9811 if (!CI->isDefaultConstructor())
9812 continue;
9813 DefCtor = CI;
9814 if (!DefCtor->isUserProvided())
9815 break;
9816 }
9817
9818 *Selected = DefCtor;
9819 }
9820
9821 return false;
9822
9824 // C++11 [class.dtor]p5:
9825 // A destructor is trivial if:
9826 // - all the direct [subobjects] have trivial destructors
9827 if (RD->hasTrivialDestructor() ||
9830 return true;
9831
9832 if (Selected) {
9833 if (RD->needsImplicitDestructor())
9835 *Selected = RD->getDestructor();
9836 }
9837
9838 return false;
9839
9841 // C++11 [class.copy]p12:
9842 // A copy constructor is trivial if:
9843 // - the constructor selected to copy each direct [subobject] is trivial
9844 if (RD->hasTrivialCopyConstructor() ||
9847 if (Quals == Qualifiers::Const)
9848 // We must either select the trivial copy constructor or reach an
9849 // ambiguity; no need to actually perform overload resolution.
9850 return true;
9851 } else if (!Selected) {
9852 return false;
9853 }
9854 // In C++98, we are not supposed to perform overload resolution here, but we
9855 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9856 // cases like B as having a non-trivial copy constructor:
9857 // struct A { template<typename T> A(T&); };
9858 // struct B { mutable A a; };
9859 goto NeedOverloadResolution;
9860
9862 // C++11 [class.copy]p25:
9863 // A copy assignment operator is trivial if:
9864 // - the assignment operator selected to copy each direct [subobject] is
9865 // trivial
9866 if (RD->hasTrivialCopyAssignment()) {
9867 if (Quals == Qualifiers::Const)
9868 return true;
9869 } else if (!Selected) {
9870 return false;
9871 }
9872 // In C++98, we are not supposed to perform overload resolution here, but we
9873 // treat that as a language defect.
9874 goto NeedOverloadResolution;
9875
9878 NeedOverloadResolution:
9880 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9881
9882 // The standard doesn't describe how to behave if the lookup is ambiguous.
9883 // We treat it as not making the member non-trivial, just like the standard
9884 // mandates for the default constructor. This should rarely matter, because
9885 // the member will also be deleted.
9887 return true;
9888
9889 if (!SMOR.getMethod()) {
9890 assert(SMOR.getKind() ==
9892 return false;
9893 }
9894
9895 // We deliberately don't check if we found a deleted special member. We're
9896 // not supposed to!
9897 if (Selected)
9898 *Selected = SMOR.getMethod();
9899
9900 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9903 return SMOR.getMethod()->isTrivialForCall();
9904 return SMOR.getMethod()->isTrivial();
9905 }
9906
9907 llvm_unreachable("unknown special method kind");
9908}
9909
9911 for (auto *CI : RD->ctors())
9912 if (!CI->isImplicit())
9913 return CI;
9914
9915 // Look for constructor templates.
9917 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9918 if (CXXConstructorDecl *CD =
9919 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9920 return CD;
9921 }
9922
9923 return nullptr;
9924}
9925
9926/// The kind of subobject we are checking for triviality. The values of this
9927/// enumeration are used in diagnostics.
9929 /// The subobject is a base class.
9931 /// The subobject is a non-static data member.
9933 /// The object is actually the complete object.
9936
9937/// Check whether the special member selected for a given type would be trivial.
9939 QualType SubType, bool ConstRHS,
9943 bool Diagnose) {
9944 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9945 if (!SubRD)
9946 return true;
9947
9948 CXXMethodDecl *Selected;
9949 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9950 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9951 return true;
9952
9953 if (Diagnose) {
9954 if (ConstRHS)
9955 SubType.addConst();
9956
9957 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
9958 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9959 << Kind << SubType.getUnqualifiedType();
9961 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9962 } else if (!Selected)
9963 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9964 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
9965 << SubType;
9966 else if (Selected->isUserProvided()) {
9967 if (Kind == TSK_CompleteObject)
9968 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9969 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9970 else {
9971 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9972 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9973 S.Diag(Selected->getLocation(), diag::note_declared_at);
9974 }
9975 } else {
9976 if (Kind != TSK_CompleteObject)
9977 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9978 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9979
9980 // Explain why the defaulted or deleted special member isn't trivial.
9982 Diagnose);
9983 }
9984 }
9985
9986 return false;
9987}
9988
9989/// Check whether the members of a class type allow a special member to be
9990/// trivial.
9992 CXXSpecialMemberKind CSM, bool ConstArg,
9994 bool Diagnose) {
9995 for (const auto *FI : RD->fields()) {
9996 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
9997 continue;
9998
9999 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10000
10001 // Pretend anonymous struct or union members are members of this class.
10002 if (FI->isAnonymousStructOrUnion()) {
10003 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10004 CSM, ConstArg, TAH, Diagnose))
10005 return false;
10006 continue;
10007 }
10008
10009 // C++11 [class.ctor]p5:
10010 // A default constructor is trivial if [...]
10011 // -- no non-static data member of its class has a
10012 // brace-or-equal-initializer
10014 FI->hasInClassInitializer()) {
10015 if (Diagnose)
10016 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10017 << FI;
10018 return false;
10019 }
10020
10021 // Objective C ARC 4.3.5:
10022 // [...] nontrivally ownership-qualified types are [...] not trivially
10023 // default constructible, copy constructible, move constructible, copy
10024 // assignable, move assignable, or destructible [...]
10025 if (FieldType.hasNonTrivialObjCLifetime()) {
10026 if (Diagnose)
10027 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10028 << RD << FieldType.getObjCLifetime();
10029 return false;
10030 }
10031
10032 bool ConstRHS = ConstArg && !FI->isMutable();
10033 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10034 CSM, TSK_Field, TAH, Diagnose))
10035 return false;
10036 }
10037
10038 return true;
10039}
10040
10044
10045 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10047 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10049 /*Diagnose*/true);
10050}
10051
10053 TrivialABIHandling TAH, bool Diagnose) {
10054 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10055 "not special enough");
10056
10057 CXXRecordDecl *RD = MD->getParent();
10058
10059 bool ConstArg = false;
10060
10061 // C++11 [class.copy]p12, p25: [DR1593]
10062 // A [special member] is trivial if [...] its parameter-type-list is
10063 // equivalent to the parameter-type-list of an implicit declaration [...]
10064 switch (CSM) {
10067 // Trivial default constructors and destructors cannot have parameters.
10068 break;
10069
10072 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10073 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10074
10075 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10076 // if they are not user-provided and their parameter-type-list is equivalent
10077 // to the parameter-type-list of an implicit declaration. This maintains the
10078 // behavior before dr2171 was implemented.
10079 //
10080 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10081 // trivial, if they are not user-provided, regardless of the qualifiers on
10082 // the reference type.
10083 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10085 if (!RT ||
10087 ClangABICompat14)) {
10088 if (Diagnose)
10089 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10090 << Param0->getSourceRange() << Param0->getType()
10093 return false;
10094 }
10095
10096 ConstArg = RT->getPointeeType().isConstQualified();
10097 break;
10098 }
10099
10102 // Trivial move operations always have non-cv-qualified parameters.
10103 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10104 const RValueReferenceType *RT =
10105 Param0->getType()->getAs<RValueReferenceType>();
10106 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10107 if (Diagnose)
10108 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10109 << Param0->getSourceRange() << Param0->getType()
10111 return false;
10112 }
10113 break;
10114 }
10115
10117 llvm_unreachable("not a special member");
10118 }
10119
10120 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10121 if (Diagnose)
10123 diag::note_nontrivial_default_arg)
10125 return false;
10126 }
10127 if (MD->isVariadic()) {
10128 if (Diagnose)
10129 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10130 return false;
10131 }
10132
10133 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10134 // A copy/move [constructor or assignment operator] is trivial if
10135 // -- the [member] selected to copy/move each direct base class subobject
10136 // is trivial
10137 //
10138 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10139 // A [default constructor or destructor] is trivial if
10140 // -- all the direct base classes have trivial [default constructors or
10141 // destructors]
10142 for (const auto &BI : RD->bases())
10143 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10144 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10145 return false;
10146
10147 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10148 // A copy/move [constructor or assignment operator] for a class X is
10149 // trivial if
10150 // -- for each non-static data member of X that is of class type (or array
10151 // thereof), the constructor selected to copy/move that member is
10152 // trivial
10153 //
10154 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10155 // A [default constructor or destructor] is trivial if
10156 // -- for all of the non-static data members of its class that are of class
10157 // type (or array thereof), each such class has a trivial [default
10158 // constructor or destructor]
10159 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10160 return false;
10161
10162 // C++11 [class.dtor]p5:
10163 // A destructor is trivial if [...]
10164 // -- the destructor is not virtual
10165 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10166 if (Diagnose)
10167 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10168 return false;
10169 }
10170
10171 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10172 // A [special member] for class X is trivial if [...]
10173 // -- class X has no virtual functions and no virtual base classes
10175 MD->getParent()->isDynamicClass()) {
10176 if (!Diagnose)
10177 return false;
10178
10179 if (RD->getNumVBases()) {
10180 // Check for virtual bases. We already know that the corresponding
10181 // member in all bases is trivial, so vbases must all be direct.
10182 CXXBaseSpecifier &BS = *RD->vbases_begin();
10183 assert(BS.isVirtual());
10184 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10185 return false;
10186 }
10187
10188 // Must have a virtual method.
10189 for (const auto *MI : RD->methods()) {
10190 if (MI->isVirtual()) {
10191 SourceLocation MLoc = MI->getBeginLoc();
10192 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10193 return false;
10194 }
10195 }
10196
10197 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10198 }
10199
10200 // Looks like it's trivial!
10201 return true;
10202}
10203
10204namespace {
10205struct FindHiddenVirtualMethod {
10206 Sema *S;
10207 CXXMethodDecl *Method;
10208 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10209 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10210
10211private:
10212 /// Check whether any most overridden method from MD in Methods
10213 static bool CheckMostOverridenMethods(
10214 const CXXMethodDecl *MD,
10215 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10216 if (MD->size_overridden_methods() == 0)
10217 return Methods.count(MD->getCanonicalDecl());
10218 for (const CXXMethodDecl *O : MD->overridden_methods())
10219 if (CheckMostOverridenMethods(O, Methods))
10220 return true;
10221 return false;
10222 }
10223
10224public:
10225 /// Member lookup function that determines whether a given C++
10226 /// method overloads virtual methods in a base class without overriding any,
10227 /// to be used with CXXRecordDecl::lookupInBases().
10228 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10229 RecordDecl *BaseRecord =
10230 Specifier->getType()->castAs<RecordType>()->getDecl();
10231
10232 DeclarationName Name = Method->getDeclName();
10233 assert(Name.getNameKind() == DeclarationName::Identifier);
10234
10235 bool foundSameNameMethod = false;
10236 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10237 for (Path.Decls = BaseRecord->lookup(Name).begin();
10238 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10239 NamedDecl *D = *Path.Decls;
10240 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10241 MD = MD->getCanonicalDecl();
10242 foundSameNameMethod = true;
10243 // Interested only in hidden virtual methods.
10244 if (!MD->isVirtual())
10245 continue;
10246 // If the method we are checking overrides a method from its base
10247 // don't warn about the other overloaded methods. Clang deviates from
10248 // GCC by only diagnosing overloads of inherited virtual functions that
10249 // do not override any other virtual functions in the base. GCC's
10250 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10251 // function from a base class. These cases may be better served by a
10252 // warning (not specific to virtual functions) on call sites when the
10253 // call would select a different function from the base class, were it
10254 // visible.
10255 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10256 if (!S->IsOverload(Method, MD, false))
10257 return true;
10258 // Collect the overload only if its hidden.
10259 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10260 overloadedMethods.push_back(MD);
10261 }
10262 }
10263
10264 if (foundSameNameMethod)
10265 OverloadedMethods.append(overloadedMethods.begin(),
10266 overloadedMethods.end());
10267 return foundSameNameMethod;
10268 }
10269};
10270} // end anonymous namespace
10271
10272/// Add the most overridden methods from MD to Methods
10274 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10275 if (MD->size_overridden_methods() == 0)
10276 Methods.insert(MD->getCanonicalDecl());
10277 else
10278 for (const CXXMethodDecl *O : MD->overridden_methods())
10279 AddMostOverridenMethods(O, Methods);
10280}
10281
10283 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10284 if (!MD->getDeclName().isIdentifier())
10285 return;
10286
10287 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10288 /*bool RecordPaths=*/false,
10289 /*bool DetectVirtual=*/false);
10290 FindHiddenVirtualMethod FHVM;
10291 FHVM.Method = MD;
10292 FHVM.S = this;
10293
10294 // Keep the base methods that were overridden or introduced in the subclass
10295 // by 'using' in a set. A base method not in this set is hidden.
10296 CXXRecordDecl *DC = MD->getParent();
10298 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10299 NamedDecl *ND = *I;
10300 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10301 ND = shad->getTargetDecl();
10302 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10303 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10304 }
10305
10306 if (DC->lookupInBases(FHVM, Paths))
10307 OverloadedMethods = FHVM.OverloadedMethods;
10308}
10309
10311 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10312 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10313 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10315 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10316 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10317 Diag(overloadedMD->getLocation(), PD);
10318 }
10319}
10320
10322 if (MD->isInvalidDecl())
10323 return;
10324
10325 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10326 return;
10327
10328 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10329 FindHiddenVirtualMethods(MD, OverloadedMethods);
10330 if (!OverloadedMethods.empty()) {
10331 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10332 << MD << (OverloadedMethods.size() > 1);
10333
10334 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10335 }
10336}
10337
10339 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10340 // No diagnostics if this is a template instantiation.
10342 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10343 diag::ext_cannot_use_trivial_abi) << &RD;
10344 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10345 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10346 }
10347 RD.dropAttr<TrivialABIAttr>();
10348 };
10349
10350 // Ill-formed if the copy and move constructors are deleted.
10351 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10352 // If the type is dependent, then assume it might have
10353 // implicit copy or move ctor because we won't know yet at this point.
10354 if (RD.isDependentType())
10355 return true;
10358 return true;
10361 return true;
10362 for (const CXXConstructorDecl *CD : RD.ctors())
10363 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10364 return true;
10365 return false;
10366 };
10367
10368 if (!HasNonDeletedCopyOrMoveConstructor()) {
10369 PrintDiagAndRemoveAttr(0);
10370 return;
10371 }
10372
10373 // Ill-formed if the struct has virtual functions.
10374 if (RD.isPolymorphic()) {
10375 PrintDiagAndRemoveAttr(1);
10376 return;
10377 }
10378
10379 for (const auto &B : RD.bases()) {
10380 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10381 // virtual base.
10382 if (!B.getType()->isDependentType() &&
10383 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10384 PrintDiagAndRemoveAttr(2);
10385 return;
10386 }
10387
10388 if (B.isVirtual()) {
10389 PrintDiagAndRemoveAttr(3);
10390 return;
10391 }
10392 }
10393
10394 for (const auto *FD : RD.fields()) {
10395 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10396 // non-trivial for the purpose of calls.
10397 QualType FT = FD->getType();
10399 PrintDiagAndRemoveAttr(4);
10400 return;
10401 }
10402
10403 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10404 if (!RT->isDependentType() &&
10405 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10406 PrintDiagAndRemoveAttr(5);
10407 return;
10408 }
10409 }
10410}
10411
10413 CXXRecordDecl &RD) {
10415 diag::err_incomplete_type_vtable_pointer_auth))
10416 return;
10417
10418 const CXXRecordDecl *PrimaryBase = &RD;
10419 if (PrimaryBase->hasAnyDependentBases())
10420 return;
10421
10422 while (1) {
10423 assert(PrimaryBase);
10424 const CXXRecordDecl *Base = nullptr;
10425 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10426 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10427 continue;
10428 Base = BasePtr.getType()->getAsCXXRecordDecl();
10429 break;
10430 }
10431 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10432 break;
10433 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10434 diag::err_non_top_level_vtable_pointer_auth)
10435 << &RD << Base;
10436 PrimaryBase = Base;
10437 }
10438
10439 if (!RD.isPolymorphic())
10440 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10441 diag::err_non_polymorphic_vtable_pointer_auth)
10442 << &RD;
10443}
10444
10447 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10448 if (!TagDecl)
10449 return;
10450
10452
10453 for (const ParsedAttr &AL : AttrList) {
10454 if (AL.getKind() != ParsedAttr::AT_Visibility)
10455 continue;
10456 AL.setInvalid();
10457 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10458 }
10459
10460 ActOnFields(S, RLoc, TagDecl,
10462 // strict aliasing violation!
10463 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10464 FieldCollector->getCurNumFields()),
10465 LBrac, RBrac, AttrList);
10466
10467 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10468}
10469
10470/// Find the equality comparison functions that should be implicitly declared
10471/// in a given class definition, per C++2a [class.compare.default]p3.
10473 ASTContext &Ctx, CXXRecordDecl *RD,
10475 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10476 if (!RD->lookup(EqEq).empty())
10477 // Member operator== explicitly declared: no implicit operator==s.
10478 return;
10479
10480 // Traverse friends looking for an '==' or a '<=>'.
10481 for (FriendDecl *Friend : RD->friends()) {
10482 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10483 if (!FD) continue;
10484
10485 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10486 // Friend operator== explicitly declared: no implicit operator==s.
10487 Spaceships.clear();
10488 return;
10489 }
10490
10491 if (FD->getOverloadedOperator() == OO_Spaceship &&
10493 Spaceships.push_back(FD);
10494 }
10495
10496 // Look for members named 'operator<=>'.
10497 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10498 for (NamedDecl *ND : RD->lookup(Cmp)) {
10499 // Note that we could find a non-function here (either a function template
10500 // or a using-declaration). Neither case results in an implicit
10501 // 'operator=='.
10502 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10503 if (FD->isExplicitlyDefaulted())
10504 Spaceships.push_back(FD);
10505 }
10506}
10507
10509 // Don't add implicit special members to templated classes.
10510 // FIXME: This means unqualified lookups for 'operator=' within a class
10511 // template don't work properly.
10512 if (!ClassDecl->isDependentType()) {
10513 if (ClassDecl->needsImplicitDefaultConstructor()) {
10515
10516 if (ClassDecl->hasInheritedConstructor())
10518 }
10519
10520 if (ClassDecl->needsImplicitCopyConstructor()) {
10522
10523 // If the properties or semantics of the copy constructor couldn't be
10524 // determined while the class was being declared, force a declaration
10525 // of it now.
10527 ClassDecl->hasInheritedConstructor())
10529 // For the MS ABI we need to know whether the copy ctor is deleted. A
10530 // prerequisite for deleting the implicit copy ctor is that the class has
10531 // a move ctor or move assignment that is either user-declared or whose
10532 // semantics are inherited from a subobject. FIXME: We should provide a
10533 // more direct way for CodeGen to ask whether the constructor was deleted.
10534 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10535 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10537 ClassDecl->hasUserDeclaredMoveAssignment() ||
10540 }
10541
10542 if (getLangOpts().CPlusPlus11 &&
10543 ClassDecl->needsImplicitMoveConstructor()) {
10545
10547 ClassDecl->hasInheritedConstructor())
10549 }
10550
10551 if (ClassDecl->needsImplicitCopyAssignment()) {
10553
10554 // If we have a dynamic class, then the copy assignment operator may be
10555 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10556 // it shows up in the right place in the vtable and that we diagnose
10557 // problems with the implicit exception specification.
10558 if (ClassDecl->isDynamicClass() ||
10560 ClassDecl->hasInheritedAssignment())
10562 }
10563
10564 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10566
10567 // Likewise for the move assignment operator.
10568 if (ClassDecl->isDynamicClass() ||
10570 ClassDecl->hasInheritedAssignment())
10572 }
10573
10574 if (ClassDecl->needsImplicitDestructor()) {
10576
10577 // If we have a dynamic class, then the destructor may be virtual, so we
10578 // have to declare the destructor immediately. This ensures that, e.g., it
10579 // shows up in the right place in the vtable and that we diagnose problems
10580 // with the implicit exception specification.
10581 if (ClassDecl->isDynamicClass() ||
10583 DeclareImplicitDestructor(ClassDecl);
10584 }
10585 }
10586
10587 // C++2a [class.compare.default]p3:
10588 // If the member-specification does not explicitly declare any member or
10589 // friend named operator==, an == operator function is declared implicitly
10590 // for each defaulted three-way comparison operator function defined in
10591 // the member-specification
10592 // FIXME: Consider doing this lazily.
10593 // We do this during the initial parse for a class template, not during
10594 // instantiation, so that we can handle unqualified lookups for 'operator=='
10595 // when parsing the template.
10597 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10599 DefaultedSpaceships);
10600 for (auto *FD : DefaultedSpaceships)
10601 DeclareImplicitEqualityComparison(ClassDecl, FD);
10602 }
10603}
10604
10605unsigned
10607 llvm::function_ref<Scope *()> EnterScope) {
10608 if (!D)
10609 return 0;
10611
10612 // In order to get name lookup right, reenter template scopes in order from
10613 // outermost to innermost.
10615 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10616
10617 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10618 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10619 ParameterLists.push_back(DD->getTemplateParameterList(i));
10620
10621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10622 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10623 ParameterLists.push_back(FTD->getTemplateParameters());
10624 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10625 LookupDC = VD->getDeclContext();
10626
10628 ParameterLists.push_back(VTD->getTemplateParameters());
10629 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10630 ParameterLists.push_back(PSD->getTemplateParameters());
10631 }
10632 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10633 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10634 ParameterLists.push_back(TD->getTemplateParameterList(i));
10635
10636 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10638 ParameterLists.push_back(CTD->getTemplateParameters());
10639 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10640 ParameterLists.push_back(PSD->getTemplateParameters());
10641 }
10642 }
10643 // FIXME: Alias declarations and concepts.
10644
10645 unsigned Count = 0;
10646 Scope *InnermostTemplateScope = nullptr;
10647 for (TemplateParameterList *Params : ParameterLists) {
10648 // Ignore explicit specializations; they don't contribute to the template
10649 // depth.
10650 if (Params->size() == 0)
10651 continue;
10652
10653 InnermostTemplateScope = EnterScope();
10654 for (NamedDecl *Param : *Params) {
10655 if (Param->getDeclName()) {
10656 InnermostTemplateScope->AddDecl(Param);
10657 IdResolver.AddDecl(Param);
10658 }
10659 }
10660 ++Count;
10661 }
10662
10663 // Associate the new template scopes with the corresponding entities.
10664 if (InnermostTemplateScope) {
10665 assert(LookupDC && "no enclosing DeclContext for template lookup");
10666 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10667 }
10668
10669 return Count;
10670}
10671
10673 if (!RecordD) return;
10674 AdjustDeclIfTemplate(RecordD);
10675 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10677}
10678
10680 if (!RecordD) return;
10682}
10683
10685 if (!Param)
10686 return;
10687
10688 S->AddDecl(Param);
10689 if (Param->getDeclName())
10690 IdResolver.AddDecl(Param);
10691}
10692
10694}
10695
10696/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10697/// C++ method declaration. We're (re-)introducing the given
10698/// function parameter into scope for use in parsing later parts of
10699/// the method declaration. For example, we could see an
10700/// ActOnParamDefaultArgument event for this parameter.
10702 if (!ParamD)
10703 return;
10704
10705 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10706
10707 S->AddDecl(Param);
10708 if (Param->getDeclName())
10709 IdResolver.AddDecl(Param);
10710}
10711
10713 if (!MethodD)
10714 return;
10715
10716 AdjustDeclIfTemplate(MethodD);
10717
10718 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10719
10720 // Now that we have our default arguments, check the constructor
10721 // again. It could produce additional diagnostics or affect whether
10722 // the class has implicitly-declared destructors, among other
10723 // things.
10724 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10725 CheckConstructor(Constructor);
10726
10727 // Check the default arguments, which we may have added.
10728 if (!Method->isInvalidDecl())
10730}
10731
10732// Emit the given diagnostic for each non-address-space qualifier.
10733// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10734static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10735 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10736 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10737 bool DiagOccured = false;
10739 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10740 SourceLocation SL) {
10741 // This diagnostic should be emitted on any qualifier except an addr
10742 // space qualifier. However, forEachQualifier currently doesn't visit
10743 // addr space qualifiers, so there's no way to write this condition
10744 // right now; we just diagnose on everything.
10745 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10746 DiagOccured = true;
10747 });
10748 if (DiagOccured)
10749 D.setInvalidType();
10750 }
10751}
10752
10754 StorageClass &SC) {
10755 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10756
10757 // C++ [class.ctor]p3:
10758 // A constructor shall not be virtual (10.3) or static (9.4). A
10759 // constructor can be invoked for a const, volatile or const
10760 // volatile object. A constructor shall not be declared const,
10761 // volatile, or const volatile (9.3.2).
10762 if (isVirtual) {
10763 if (!D.isInvalidType())
10764 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10765 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10766 << SourceRange(D.getIdentifierLoc());
10767 D.setInvalidType();
10768 }
10769 if (SC == SC_Static) {
10770 if (!D.isInvalidType())
10771 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10772 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10773 << SourceRange(D.getIdentifierLoc());
10774 D.setInvalidType();
10775 SC = SC_None;
10776 }
10777
10778 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10780 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10781 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10782 D.getDeclSpec().getRestrictSpecLoc(),
10783 D.getDeclSpec().getAtomicSpecLoc());
10784 D.setInvalidType();
10785 }
10786
10787 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10788
10789 // C++0x [class.ctor]p4:
10790 // A constructor shall not be declared with a ref-qualifier.
10791 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10792 if (FTI.hasRefQualifier()) {
10793 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10796 D.setInvalidType();
10797 }
10798
10799 // Rebuild the function type "R" without any type qualifiers (in
10800 // case any of the errors above fired) and with "void" as the
10801 // return type, since constructors don't have return types.
10802 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10803 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10804 return R;
10805
10807 EPI.TypeQuals = Qualifiers();
10808 EPI.RefQualifier = RQ_None;
10809
10810 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10811}
10812
10814 CXXRecordDecl *ClassDecl
10815 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10816 if (!ClassDecl)
10817 return Constructor->setInvalidDecl();
10818
10819 // C++ [class.copy]p3:
10820 // A declaration of a constructor for a class X is ill-formed if
10821 // its first parameter is of type (optionally cv-qualified) X and
10822 // either there are no other parameters or else all other
10823 // parameters have default arguments.
10824 if (!Constructor->isInvalidDecl() &&
10825 Constructor->hasOneParamOrDefaultArgs() &&
10826 Constructor->getTemplateSpecializationKind() !=
10828 QualType ParamType = Constructor->getParamDecl(0)->getType();
10829 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10830 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10831 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10832 const char *ConstRef
10833 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10834 : " const &";
10835 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10836 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10837
10838 // FIXME: Rather that making the constructor invalid, we should endeavor
10839 // to fix the type.
10840 Constructor->setInvalidDecl();
10841 }
10842 }
10843}
10844
10846 CXXRecordDecl *RD = Destructor->getParent();
10847
10848 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10850
10851 if (!Destructor->isImplicit())
10852 Loc = Destructor->getLocation();
10853 else
10854 Loc = RD->getLocation();
10855
10856 // If we have a virtual destructor, look up the deallocation function
10857 if (FunctionDecl *OperatorDelete =
10859 Expr *ThisArg = nullptr;
10860
10861 // If the notional 'delete this' expression requires a non-trivial
10862 // conversion from 'this' to the type of a destroying operator delete's
10863 // first parameter, perform that conversion now.
10864 if (OperatorDelete->isDestroyingOperatorDelete()) {
10865 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10866 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10867 // C++ [class.dtor]p13:
10868 // ... as if for the expression 'delete this' appearing in a
10869 // non-virtual destructor of the destructor's class.
10870 ContextRAII SwitchContext(*this, Destructor);
10871 ExprResult This =
10872 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10873 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10874 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10875 if (This.isInvalid()) {
10876 // FIXME: Register this as a context note so that it comes out
10877 // in the right order.
10878 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10879 return true;
10880 }
10881 ThisArg = This.get();
10882 }
10883 }
10884
10885 DiagnoseUseOfDecl(OperatorDelete, Loc);
10886 MarkFunctionReferenced(Loc, OperatorDelete);
10887 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10888 }
10889 }
10890
10891 return false;
10892}
10893
10895 StorageClass& SC) {
10896 // C++ [class.dtor]p1:
10897 // [...] A typedef-name that names a class is a class-name
10898 // (7.1.3); however, a typedef-name that names a class shall not
10899 // be used as the identifier in the declarator for a destructor
10900 // declaration.
10901 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10902 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10903 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10904 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10905 else if (const TemplateSpecializationType *TST =
10906 DeclaratorType->getAs<TemplateSpecializationType>())
10907 if (TST->isTypeAlias())
10908 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10909 << DeclaratorType << 1;
10910
10911 // C++ [class.dtor]p2:
10912 // A destructor is used to destroy objects of its class type. A
10913 // destructor takes no parameters, and no return type can be
10914 // specified for it (not even void). The address of a destructor
10915 // shall not be taken. A destructor shall not be static. A
10916 // destructor can be invoked for a const, volatile or const
10917 // volatile object. A destructor shall not be declared const,
10918 // volatile or const volatile (9.3.2).
10919 if (SC == SC_Static) {
10920 if (!D.isInvalidType())
10921 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10922 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10923 << SourceRange(D.getIdentifierLoc())
10924 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10925
10926 SC = SC_None;
10927 }
10928 if (!D.isInvalidType()) {
10929 // Destructors don't have return types, but the parser will
10930 // happily parse something like:
10931 //
10932 // class X {
10933 // float ~X();
10934 // };
10935 //
10936 // The return type will be eliminated later.
10937 if (D.getDeclSpec().hasTypeSpecifier())
10938 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10939 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10940 << SourceRange(D.getIdentifierLoc());
10941 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10942 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10944 D.getDeclSpec().getConstSpecLoc(),
10945 D.getDeclSpec().getVolatileSpecLoc(),
10946 D.getDeclSpec().getRestrictSpecLoc(),
10947 D.getDeclSpec().getAtomicSpecLoc());
10948 D.setInvalidType();
10949 }
10950 }
10951
10952 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10953
10954 // C++0x [class.dtor]p2:
10955 // A destructor shall not be declared with a ref-qualifier.
10956 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10957 if (FTI.hasRefQualifier()) {
10958 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10961 D.setInvalidType();
10962 }
10963
10964 // Make sure we don't have any parameters.
10965 if (FTIHasNonVoidParameters(FTI)) {
10966 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10967
10968 // Delete the parameters.
10969 FTI.freeParams();
10970 D.setInvalidType();
10971 }
10972
10973 // Make sure the destructor isn't variadic.
10974 if (FTI.isVariadic) {
10975 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10976 D.setInvalidType();
10977 }
10978
10979 // Rebuild the function type "R" without any type qualifiers or
10980 // parameters (in case any of the errors above fired) and with
10981 // "void" as the return type, since destructors don't have return
10982 // types.
10983 if (!D.isInvalidType())
10984 return R;
10985
10986 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10988 EPI.Variadic = false;
10989 EPI.TypeQuals = Qualifiers();
10990 EPI.RefQualifier = RQ_None;
10991 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10992}
10993
10994static void extendLeft(SourceRange &R, SourceRange Before) {
10995 if (Before.isInvalid())
10996 return;
10997 R.setBegin(Before.getBegin());
10998 if (R.getEnd().isInvalid())
10999 R.setEnd(Before.getEnd());
11000}
11001
11002static void extendRight(SourceRange &R, SourceRange After) {
11003 if (After.isInvalid())
11004 return;
11005 if (R.getBegin().isInvalid())
11006 R.setBegin(After.getBegin());
11007 R.setEnd(After.getEnd());
11008}
11009
11011 StorageClass& SC) {
11012 // C++ [class.conv.fct]p1:
11013 // Neither parameter types nor return type can be specified. The
11014 // type of a conversion function (8.3.5) is "function taking no
11015 // parameter returning conversion-type-id."
11016 if (SC == SC_Static) {
11017 if (!D.isInvalidType())
11018 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11019 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11020 << D.getName().getSourceRange();
11021 D.setInvalidType();
11022 SC = SC_None;
11023 }
11024
11025 TypeSourceInfo *ConvTSI = nullptr;
11026 QualType ConvType =
11027 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11028
11029 const DeclSpec &DS = D.getDeclSpec();
11030 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11031 // Conversion functions don't have return types, but the parser will
11032 // happily parse something like:
11033 //
11034 // class X {
11035 // float operator bool();
11036 // };
11037 //
11038 // The return type will be changed later anyway.
11039 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11041 << SourceRange(D.getIdentifierLoc());
11042 D.setInvalidType();
11043 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11044 // It's also plausible that the user writes type qualifiers in the wrong
11045 // place, such as:
11046 // struct S { const operator int(); };
11047 // FIXME: we could provide a fixit to move the qualifiers onto the
11048 // conversion type.
11049 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11050 << SourceRange(D.getIdentifierLoc()) << 0;
11051 D.setInvalidType();
11052 }
11053 const auto *Proto = R->castAs<FunctionProtoType>();
11054 // Make sure we don't have any parameters.
11055 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11056 unsigned NumParam = Proto->getNumParams();
11057
11058 // [C++2b]
11059 // A conversion function shall have no non-object parameters.
11060 if (NumParam == 1) {
11061 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11062 if (const auto *First =
11063 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11064 First && First->isExplicitObjectParameter())
11065 NumParam--;
11066 }
11067
11068 if (NumParam != 0) {
11069 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11070 // Delete the parameters.
11071 FTI.freeParams();
11072 D.setInvalidType();
11073 } else if (Proto->isVariadic()) {
11074 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11075 D.setInvalidType();
11076 }
11077
11078 // Diagnose "&operator bool()" and other such nonsense. This
11079 // is actually a gcc extension which we don't support.
11080 if (Proto->getReturnType() != ConvType) {
11081 bool NeedsTypedef = false;
11082 SourceRange Before, After;
11083
11084 // Walk the chunks and extract information on them for our diagnostic.
11085 bool PastFunctionChunk = false;
11086 for (auto &Chunk : D.type_objects()) {
11087 switch (Chunk.Kind) {
11089 if (!PastFunctionChunk) {
11090 if (Chunk.Fun.HasTrailingReturnType) {
11091 TypeSourceInfo *TRT = nullptr;
11092 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11093 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11094 }
11095 PastFunctionChunk = true;
11096 break;
11097 }
11098 [[fallthrough]];
11100 NeedsTypedef = true;
11101 extendRight(After, Chunk.getSourceRange());
11102 break;
11103
11109 extendLeft(Before, Chunk.getSourceRange());
11110 break;
11111
11113 extendLeft(Before, Chunk.Loc);
11114 extendRight(After, Chunk.EndLoc);
11115 break;
11116 }
11117 }
11118
11119 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11120 After.isValid() ? After.getBegin() :
11121 D.getIdentifierLoc();
11122 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11123 DB << Before << After;
11124
11125 if (!NeedsTypedef) {
11126 DB << /*don't need a typedef*/0;
11127
11128 // If we can provide a correct fix-it hint, do so.
11129 if (After.isInvalid() && ConvTSI) {
11130 SourceLocation InsertLoc =
11132 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11134 InsertLoc, CharSourceRange::getTokenRange(Before))
11135 << FixItHint::CreateRemoval(Before);
11136 }
11137 } else if (!Proto->getReturnType()->isDependentType()) {
11138 DB << /*typedef*/1 << Proto->getReturnType();
11139 } else if (getLangOpts().CPlusPlus11) {
11140 DB << /*alias template*/2 << Proto->getReturnType();
11141 } else {
11142 DB << /*might not be fixable*/3;
11143 }
11144
11145 // Recover by incorporating the other type chunks into the result type.
11146 // Note, this does *not* change the name of the function. This is compatible
11147 // with the GCC extension:
11148 // struct S { &operator int(); } s;
11149 // int &r = s.operator int(); // ok in GCC
11150 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11151 ConvType = Proto->getReturnType();
11152 }
11153
11154 // C++ [class.conv.fct]p4:
11155 // The conversion-type-id shall not represent a function type nor
11156 // an array type.
11157 if (ConvType->isArrayType()) {
11158 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11159 ConvType = Context.getPointerType(ConvType);
11160 D.setInvalidType();
11161 } else if (ConvType->isFunctionType()) {
11162 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11163 ConvType = Context.getPointerType(ConvType);
11164 D.setInvalidType();
11165 }
11166
11167 // Rebuild the function type "R" without any parameters (in case any
11168 // of the errors above fired) and with the conversion type as the
11169 // return type.
11170 if (D.isInvalidType())
11171 R = Context.getFunctionType(ConvType, std::nullopt,
11172 Proto->getExtProtoInfo());
11173
11174 // C++0x explicit conversion operators.
11178 ? diag::warn_cxx98_compat_explicit_conversion_functions
11179 : diag::ext_explicit_conversion_functions)
11181}
11182
11184 assert(Conversion && "Expected to receive a conversion function declaration");
11185
11186 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11187
11188 // Make sure we aren't redeclaring the conversion function.
11189 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11190 // C++ [class.conv.fct]p1:
11191 // [...] A conversion function is never used to convert a
11192 // (possibly cv-qualified) object to the (possibly cv-qualified)
11193 // same object type (or a reference to it), to a (possibly
11194 // cv-qualified) base class of that type (or a reference to it),
11195 // or to (possibly cv-qualified) void.
11196 QualType ClassType
11198 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11199 ConvType = ConvTypeRef->getPointeeType();
11200 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11202 /* Suppress diagnostics for instantiations. */;
11203 else if (Conversion->size_overridden_methods() != 0)
11204 /* Suppress diagnostics for overriding virtual function in a base class. */;
11205 else if (ConvType->isRecordType()) {
11206 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11207 if (ConvType == ClassType)
11208 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11209 << ClassType;
11210 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11211 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11212 << ClassType << ConvType;
11213 } else if (ConvType->isVoidType()) {
11214 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11215 << ClassType << ConvType;
11216 }
11217
11218 if (FunctionTemplateDecl *ConversionTemplate =
11219 Conversion->getDescribedFunctionTemplate()) {
11220 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11221 ConvType = ConvTypePtr->getPointeeType();
11222 }
11223 if (ConvType->isUndeducedAutoType()) {
11224 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11225 << getReturnTypeLoc(Conversion).getSourceRange()
11226 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11227 << /* in declaration of conversion function template= */ 24;
11228 }
11229
11230 return ConversionTemplate;
11231 }
11232
11233 return Conversion;
11234}
11235
11237 DeclarationName Name, QualType R) {
11238 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11239}
11240
11242 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11243}
11244
11246 DeclarationName Name, QualType R,
11247 bool IsLambda, DeclContext *DC) {
11248 if (!D.isFunctionDeclarator())
11249 return;
11250
11251 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11252 if (FTI.NumParams == 0)
11253 return;
11254 ParmVarDecl *ExplicitObjectParam = nullptr;
11255 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11256 const auto &ParamInfo = FTI.Params[Idx];
11257 if (!ParamInfo.Param)
11258 continue;
11259 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11260 if (!Param->isExplicitObjectParameter())
11261 continue;
11262 if (Idx == 0) {
11263 ExplicitObjectParam = Param;
11264 continue;
11265 } else {
11266 Diag(Param->getLocation(),
11267 diag::err_explicit_object_parameter_must_be_first)
11268 << IsLambda << Param->getSourceRange();
11269 }
11270 }
11271 if (!ExplicitObjectParam)
11272 return;
11273
11274 if (ExplicitObjectParam->hasDefaultArg()) {
11275 Diag(ExplicitObjectParam->getLocation(),
11276 diag::err_explicit_object_default_arg)
11277 << ExplicitObjectParam->getSourceRange();
11278 }
11279
11280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11281 (D.getContext() == clang::DeclaratorContext::Member &&
11282 D.isStaticMember())) {
11283 Diag(ExplicitObjectParam->getBeginLoc(),
11284 diag::err_explicit_object_parameter_nonmember)
11285 << D.getSourceRange() << /*static=*/0 << IsLambda;
11286 D.setInvalidType();
11287 }
11288
11289 if (D.getDeclSpec().isVirtualSpecified()) {
11290 Diag(ExplicitObjectParam->getBeginLoc(),
11291 diag::err_explicit_object_parameter_nonmember)
11292 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11293 D.setInvalidType();
11294 }
11295
11296 // Friend declarations require some care. Consider:
11297 //
11298 // namespace N {
11299 // struct A{};
11300 // int f(A);
11301 // }
11302 //
11303 // struct S {
11304 // struct T {
11305 // int f(this T);
11306 // };
11307 //
11308 // friend int T::f(this T); // Allow this.
11309 // friend int f(this S); // But disallow this.
11310 // friend int N::f(this A); // And disallow this.
11311 // };
11312 //
11313 // Here, it seems to suffice to check whether the scope
11314 // specifier designates a class type.
11315 if (D.getDeclSpec().isFriendSpecified() &&
11316 !isa_and_present<CXXRecordDecl>(
11317 computeDeclContext(D.getCXXScopeSpec()))) {
11318 Diag(ExplicitObjectParam->getBeginLoc(),
11319 diag::err_explicit_object_parameter_nonmember)
11320 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11321 D.setInvalidType();
11322 }
11323
11324 if (IsLambda && FTI.hasMutableQualifier()) {
11325 Diag(ExplicitObjectParam->getBeginLoc(),
11326 diag::err_explicit_object_parameter_mutable)
11327 << D.getSourceRange();
11328 }
11329
11330 if (IsLambda)
11331 return;
11332
11333 if (!DC || !DC->isRecord()) {
11334 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11335 "should have been diagnosed already");
11336 return;
11337 }
11338
11339 // CWG2674: constructors and destructors cannot have explicit parameters.
11340 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11341 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11342 Diag(ExplicitObjectParam->getBeginLoc(),
11343 diag::err_explicit_object_parameter_constructor)
11344 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11345 << D.getSourceRange();
11346 D.setInvalidType();
11347 }
11348}
11349
11350namespace {
11351/// Utility class to accumulate and print a diagnostic listing the invalid
11352/// specifier(s) on a declaration.
11353struct BadSpecifierDiagnoser {
11354 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11355 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11356 ~BadSpecifierDiagnoser() {
11357 Diagnostic << Specifiers;
11358 }
11359
11360 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11361 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11362 }
11363 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11364 return check(SpecLoc,
11366 }
11367 void check(SourceLocation SpecLoc, const char *Spec) {
11368 if (SpecLoc.isInvalid()) return;
11369 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11370 if (!Specifiers.empty()) Specifiers += " ";
11371 Specifiers += Spec;
11372 }
11373
11374 Sema &S;
11376 std::string Specifiers;
11377};
11378}
11379
11381 StorageClass &SC) {
11382 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11383 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11384 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11385
11386 // C++ [temp.deduct.guide]p3:
11387 // A deduction-gide shall be declared in the same scope as the
11388 // corresponding class template.
11390 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11391 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11392 << GuidedTemplateDecl;
11393 NoteTemplateLocation(*GuidedTemplateDecl);
11394 }
11395
11396 auto &DS = D.getMutableDeclSpec();
11397 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11398 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11399 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11400 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11401 BadSpecifierDiagnoser Diagnoser(
11402 *this, D.getIdentifierLoc(),
11403 diag::err_deduction_guide_invalid_specifier);
11404
11405 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11406 DS.ClearStorageClassSpecs();
11407 SC = SC_None;
11408
11409 // 'explicit' is permitted.
11410 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11411 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11412 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11413 DS.ClearConstexprSpec();
11414
11415 Diagnoser.check(DS.getConstSpecLoc(), "const");
11416 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11417 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11418 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11419 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11420 DS.ClearTypeQualifiers();
11421
11422 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11423 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11424 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11425 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11426 DS.ClearTypeSpecType();
11427 }
11428
11429 if (D.isInvalidType())
11430 return true;
11431
11432 // Check the declarator is simple enough.
11433 bool FoundFunction = false;
11434 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11435 if (Chunk.Kind == DeclaratorChunk::Paren)
11436 continue;
11437 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11438 Diag(D.getDeclSpec().getBeginLoc(),
11439 diag::err_deduction_guide_with_complex_decl)
11440 << D.getSourceRange();
11441 break;
11442 }
11443 if (!Chunk.Fun.hasTrailingReturnType())
11444 return Diag(D.getName().getBeginLoc(),
11445 diag::err_deduction_guide_no_trailing_return_type);
11446
11447 // Check that the return type is written as a specialization of
11448 // the template specified as the deduction-guide's name.
11449 // The template name may not be qualified. [temp.deduct.guide]
11450 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11451 TypeSourceInfo *TSI = nullptr;
11452 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11453 assert(TSI && "deduction guide has valid type but invalid return type?");
11454 bool AcceptableReturnType = false;
11455 bool MightInstantiateToSpecialization = false;
11456 if (auto RetTST =
11458 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11459 bool TemplateMatches =
11460 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11461
11463 SpecifiedName.getAsQualifiedTemplateName();
11464 assert(Qualifiers && "expected QualifiedTemplate");
11465 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11466 Qualifiers->getQualifier() == nullptr;
11467 if (SimplyWritten && TemplateMatches)
11468 AcceptableReturnType = true;
11469 else {
11470 // This could still instantiate to the right type, unless we know it
11471 // names the wrong class template.
11472 auto *TD = SpecifiedName.getAsTemplateDecl();
11473 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11474 !TemplateMatches);
11475 }
11476 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11477 MightInstantiateToSpecialization = true;
11478 }
11479
11480 if (!AcceptableReturnType)
11481 return Diag(TSI->getTypeLoc().getBeginLoc(),
11482 diag::err_deduction_guide_bad_trailing_return_type)
11483 << GuidedTemplate << TSI->getType()
11484 << MightInstantiateToSpecialization
11485 << TSI->getTypeLoc().getSourceRange();
11486
11487 // Keep going to check that we don't have any inner declarator pieces (we
11488 // could still have a function returning a pointer to a function).
11489 FoundFunction = true;
11490 }
11491
11492 if (D.isFunctionDefinition())
11493 // we can still create a valid deduction guide here.
11494 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11495 return false;
11496}
11497
11498//===----------------------------------------------------------------------===//
11499// Namespace Handling
11500//===----------------------------------------------------------------------===//
11501
11502/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11503/// reopened.
11506 IdentifierInfo *II, bool *IsInline,
11507 NamespaceDecl *PrevNS) {
11508 assert(*IsInline != PrevNS->isInline());
11509
11510 // 'inline' must appear on the original definition, but not necessarily
11511 // on all extension definitions, so the note should point to the first
11512 // definition to avoid confusion.
11513 PrevNS = PrevNS->getFirstDecl();
11514
11515 if (PrevNS->isInline())
11516 // The user probably just forgot the 'inline', so suggest that it
11517 // be added back.
11518 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11519 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11520 else
11521 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11522
11523 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11524 *IsInline = PrevNS->isInline();
11525}
11526
11527/// ActOnStartNamespaceDef - This is called at the start of a namespace
11528/// definition.
11530 SourceLocation InlineLoc,
11531 SourceLocation NamespaceLoc,
11532 SourceLocation IdentLoc, IdentifierInfo *II,
11533 SourceLocation LBrace,
11534 const ParsedAttributesView &AttrList,
11535 UsingDirectiveDecl *&UD, bool IsNested) {
11536 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11537 // For anonymous namespace, take the location of the left brace.
11538 SourceLocation Loc = II ? IdentLoc : LBrace;
11539 bool IsInline = InlineLoc.isValid();
11540 bool IsInvalid = false;
11541 bool IsStd = false;
11542 bool AddToKnown = false;
11543 Scope *DeclRegionScope = NamespcScope->getParent();
11544
11545 NamespaceDecl *PrevNS = nullptr;
11546 if (II) {
11547 // C++ [namespace.std]p7:
11548 // A translation unit shall not declare namespace std to be an inline
11549 // namespace (9.8.2).
11550 //
11551 // Precondition: the std namespace is in the file scope and is declared to
11552 // be inline
11553 auto DiagnoseInlineStdNS = [&]() {
11554 assert(IsInline && II->isStr("std") &&
11556 "Precondition of DiagnoseInlineStdNS not met");
11557 Diag(InlineLoc, diag::err_inline_namespace_std)
11558 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11559 IsInline = false;
11560 };
11561 // C++ [namespace.def]p2:
11562 // The identifier in an original-namespace-definition shall not
11563 // have been previously defined in the declarative region in
11564 // which the original-namespace-definition appears. The
11565 // identifier in an original-namespace-definition is the name of
11566 // the namespace. Subsequently in that declarative region, it is
11567 // treated as an original-namespace-name.
11568 //
11569 // Since namespace names are unique in their scope, and we don't
11570 // look through using directives, just look for any ordinary names
11571 // as if by qualified name lookup.
11572 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11573 RedeclarationKind::ForExternalRedeclaration);
11575 NamedDecl *PrevDecl =
11576 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11577 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11578
11579 if (PrevNS) {
11580 // This is an extended namespace definition.
11581 if (IsInline && II->isStr("std") &&
11583 DiagnoseInlineStdNS();
11584 else if (IsInline != PrevNS->isInline())
11585 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11586 &IsInline, PrevNS);
11587 } else if (PrevDecl) {
11588 // This is an invalid name redefinition.
11589 Diag(Loc, diag::err_redefinition_different_kind)
11590 << II;
11591 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11592 IsInvalid = true;
11593 // Continue on to push Namespc as current DeclContext and return it.
11594 } else if (II->isStr("std") &&
11596 if (IsInline)
11597 DiagnoseInlineStdNS();
11598 // This is the first "real" definition of the namespace "std", so update
11599 // our cache of the "std" namespace to point at this definition.
11600 PrevNS = getStdNamespace();
11601 IsStd = true;
11602 AddToKnown = !IsInline;
11603 } else {
11604 // We've seen this namespace for the first time.
11605 AddToKnown = !IsInline;
11606 }
11607 } else {
11608 // Anonymous namespaces.
11609
11610 // Determine whether the parent already has an anonymous namespace.
11612 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11613 PrevNS = TU->getAnonymousNamespace();
11614 } else {
11615 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11616 PrevNS = ND->getAnonymousNamespace();
11617 }
11618
11619 if (PrevNS && IsInline != PrevNS->isInline())
11620 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11621 &IsInline, PrevNS);
11622 }
11623
11625 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11626 if (IsInvalid)
11627 Namespc->setInvalidDecl();
11628
11629 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11630 AddPragmaAttributes(DeclRegionScope, Namespc);
11631 ProcessAPINotes(Namespc);
11632
11633 // FIXME: Should we be merging attributes?
11634 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11636
11637 if (IsStd)
11638 StdNamespace = Namespc;
11639 if (AddToKnown)
11640 KnownNamespaces[Namespc] = false;
11641
11642 if (II) {
11643 PushOnScopeChains(Namespc, DeclRegionScope);
11644 } else {
11645 // Link the anonymous namespace into its parent.
11647 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11648 TU->setAnonymousNamespace(Namespc);
11649 } else {
11650 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11651 }
11652
11653 CurContext->addDecl(Namespc);
11654
11655 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11656 // behaves as if it were replaced by
11657 // namespace unique { /* empty body */ }
11658 // using namespace unique;
11659 // namespace unique { namespace-body }
11660 // where all occurrences of 'unique' in a translation unit are
11661 // replaced by the same identifier and this identifier differs
11662 // from all other identifiers in the entire program.
11663
11664 // We just create the namespace with an empty name and then add an
11665 // implicit using declaration, just like the standard suggests.
11666 //
11667 // CodeGen enforces the "universally unique" aspect by giving all
11668 // declarations semantically contained within an anonymous
11669 // namespace internal linkage.
11670
11671 if (!PrevNS) {
11673 /* 'using' */ LBrace,
11674 /* 'namespace' */ SourceLocation(),
11675 /* qualifier */ NestedNameSpecifierLoc(),
11676 /* identifier */ SourceLocation(),
11677 Namespc,
11678 /* Ancestor */ Parent);
11679 UD->setImplicit();
11680 Parent->addDecl(UD);
11681 }
11682 }
11683
11684 ActOnDocumentableDecl(Namespc);
11685
11686 // Although we could have an invalid decl (i.e. the namespace name is a
11687 // redefinition), push it as current DeclContext and try to continue parsing.
11688 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11689 // for the namespace has the declarations that showed up in that particular
11690 // namespace definition.
11691 PushDeclContext(NamespcScope, Namespc);
11692 return Namespc;
11693}
11694
11695/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11696/// is a namespace alias, returns the namespace it points to.
11698 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11699 return AD->getNamespace();
11700 return dyn_cast_or_null<NamespaceDecl>(D);
11701}
11702
11704 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11705 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11706 Namespc->setRBraceLoc(RBrace);
11708 if (Namespc->hasAttr<VisibilityAttr>())
11709 PopPragmaVisibility(true, RBrace);
11710 // If this namespace contains an export-declaration, export it now.
11711 if (DeferredExportedNamespaces.erase(Namespc))
11713}
11714
11716 return cast_or_null<CXXRecordDecl>(
11718}
11719
11721 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11722}
11723
11725 return cast_or_null<NamespaceDecl>(
11727}
11728namespace {
11729
11730enum UnsupportedSTLSelect {
11731 USS_InvalidMember,
11732 USS_MissingMember,
11733 USS_NonTrivial,
11734 USS_Other
11735};
11736
11737struct InvalidSTLDiagnoser {
11738 Sema &S;
11740 QualType TyForDiags;
11741
11742 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11743 const VarDecl *VD = nullptr) {
11744 {
11745 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11746 << TyForDiags << ((int)Sel);
11747 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11748 assert(!Name.empty());
11749 D << Name;
11750 }
11751 }
11752 if (Sel == USS_InvalidMember) {
11753 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11754 << VD << VD->getSourceRange();
11755 }
11756 return QualType();
11757 }
11758};
11759} // namespace
11760
11764 assert(getLangOpts().CPlusPlus &&
11765 "Looking for comparison category type outside of C++.");
11766
11767 // Use an elaborated type for diagnostics which has a name containing the
11768 // prepended 'std' namespace but not any inline namespace names.
11769 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11770 auto *NNS =
11773 Info->getType());
11774 };
11775
11776 // Check if we've already successfully checked the comparison category type
11777 // before. If so, skip checking it again.
11779 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11780 // The only thing we need to check is that the type has a reachable
11781 // definition in the current context.
11782 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11783 return QualType();
11784
11785 return Info->getType();
11786 }
11787
11788 // If lookup failed
11789 if (!Info) {
11790 std::string NameForDiags = "std::";
11791 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11792 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11793 << NameForDiags << (int)Usage;
11794 return QualType();
11795 }
11796
11797 assert(Info->Kind == Kind);
11798 assert(Info->Record);
11799
11800 // Update the Record decl in case we encountered a forward declaration on our
11801 // first pass. FIXME: This is a bit of a hack.
11802 if (Info->Record->hasDefinition())
11803 Info->Record = Info->Record->getDefinition();
11804
11805 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11806 return QualType();
11807
11808 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11809
11810 if (!Info->Record->isTriviallyCopyable())
11811 return UnsupportedSTLError(USS_NonTrivial);
11812
11813 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11814 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11815 // Tolerate empty base classes.
11816 if (Base->isEmpty())
11817 continue;
11818 // Reject STL implementations which have at least one non-empty base.
11819 return UnsupportedSTLError();
11820 }
11821
11822 // Check that the STL has implemented the types using a single integer field.
11823 // This expectation allows better codegen for builtin operators. We require:
11824 // (1) The class has exactly one field.
11825 // (2) The field is an integral or enumeration type.
11826 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11827 if (std::distance(FIt, FEnd) != 1 ||
11828 !FIt->getType()->isIntegralOrEnumerationType()) {
11829 return UnsupportedSTLError();
11830 }
11831
11832 // Build each of the require values and store them in Info.
11833 for (ComparisonCategoryResult CCR :
11835 StringRef MemName = ComparisonCategories::getResultString(CCR);
11836 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11837
11838 if (!ValInfo)
11839 return UnsupportedSTLError(USS_MissingMember, MemName);
11840
11841 VarDecl *VD = ValInfo->VD;
11842 assert(VD && "should not be null!");
11843
11844 // Attempt to diagnose reasons why the STL definition of this type
11845 // might be foobar, including it failing to be a constant expression.
11846 // TODO Handle more ways the lookup or result can be invalid.
11847 if (!VD->isStaticDataMember() ||
11849 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11850
11851 // Attempt to evaluate the var decl as a constant expression and extract
11852 // the value of its first field as a ICE. If this fails, the STL
11853 // implementation is not supported.
11854 if (!ValInfo->hasValidIntValue())
11855 return UnsupportedSTLError();
11856
11858 }
11859
11860 // We've successfully built the required types and expressions. Update
11861 // the cache and return the newly cached value.
11862 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11863 return Info->getType();
11864}
11865
11867 if (!StdNamespace) {
11868 // The "std" namespace has not yet been defined, so build one implicitly.
11871 /*Inline=*/false, SourceLocation(), SourceLocation(),
11872 &PP.getIdentifierTable().get("std"),
11873 /*PrevDecl=*/nullptr, /*Nested=*/false);
11875 // We want the created NamespaceDecl to be available for redeclaration
11876 // lookups, but not for regular name lookups.
11879 }
11880
11881 return getStdNamespace();
11882}
11883
11885 assert(getLangOpts().CPlusPlus &&
11886 "Looking for std::initializer_list outside of C++.");
11887
11888 // We're looking for implicit instantiations of
11889 // template <typename E> class std::initializer_list.
11890
11891 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11892 return false;
11893
11894 ClassTemplateDecl *Template = nullptr;
11895 const TemplateArgument *Arguments = nullptr;
11896
11897 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11898
11900 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11901 if (!Specialization)
11902 return false;
11903
11904 Template = Specialization->getSpecializedTemplate();
11905 Arguments = Specialization->getTemplateArgs().data();
11906 } else {
11907 const TemplateSpecializationType *TST = nullptr;
11908 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
11909 TST = ICN->getInjectedTST();
11910 else
11911 TST = Ty->getAs<TemplateSpecializationType>();
11912 if (TST) {
11913 Template = dyn_cast_or_null<ClassTemplateDecl>(
11915 Arguments = TST->template_arguments().begin();
11916 }
11917 }
11918 if (!Template)
11919 return false;
11920
11921 if (!StdInitializerList) {
11922 // Haven't recognized std::initializer_list yet, maybe this is it.
11923 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11924 if (TemplateClass->getIdentifier() !=
11925 &PP.getIdentifierTable().get("initializer_list") ||
11926 !getStdNamespace()->InEnclosingNamespaceSetOf(
11927 TemplateClass->getDeclContext()))
11928 return false;
11929 // This is a template called std::initializer_list, but is it the right
11930 // template?
11931 TemplateParameterList *Params = Template->getTemplateParameters();
11932 if (Params->getMinRequiredArguments() != 1)
11933 return false;
11934 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11935 return false;
11936
11937 // It's the right template.
11938 StdInitializerList = Template;
11939 }
11940
11942 return false;
11943
11944 // This is an instance of std::initializer_list. Find the argument type.
11945 if (Element)
11946 *Element = Arguments[0].getAsType();
11947 return true;
11948}
11949
11952 if (!Std) {
11953 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11954 return nullptr;
11955 }
11956
11957 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11959 if (!S.LookupQualifiedName(Result, Std)) {
11960 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11961 return nullptr;
11962 }
11963 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11964 if (!Template) {
11965 Result.suppressDiagnostics();
11966 // We found something weird. Complain about the first thing we found.
11967 NamedDecl *Found = *Result.begin();
11968 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11969 return nullptr;
11970 }
11971
11972 // We found some template called std::initializer_list. Now verify that it's
11973 // correct.
11974 TemplateParameterList *Params = Template->getTemplateParameters();
11975 if (Params->getMinRequiredArguments() != 1 ||
11976 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11977 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11978 return nullptr;
11979 }
11980
11981 return Template;
11982}
11983
11985 if (!StdInitializerList) {
11987 if (!StdInitializerList)
11988 return QualType();
11989 }
11990
11994 Loc)));
11999}
12000
12002 // C++ [dcl.init.list]p2:
12003 // A constructor is an initializer-list constructor if its first parameter
12004 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12005 // std::initializer_list<E> for some type E, and either there are no other
12006 // parameters or else all other parameters have default arguments.
12007 if (!Ctor->hasOneParamOrDefaultArgs())
12008 return false;
12009
12010 QualType ArgType = Ctor->getParamDecl(0)->getType();
12011 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12012 ArgType = RT->getPointeeType().getUnqualifiedType();
12013
12014 return isStdInitializerList(ArgType, nullptr);
12015}
12016
12017/// Determine whether a using statement is in a context where it will be
12018/// apply in all contexts.
12020 switch (CurContext->getDeclKind()) {
12021 case Decl::TranslationUnit:
12022 return true;
12023 case Decl::LinkageSpec:
12025 default:
12026 return false;
12027 }
12028}
12029
12030namespace {
12031
12032// Callback to only accept typo corrections that are namespaces.
12033class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12034public:
12035 bool ValidateCandidate(const TypoCorrection &candidate) override {
12036 if (NamedDecl *ND = candidate.getCorrectionDecl())
12037 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12038 return false;
12039 }
12040
12041 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12042 return std::make_unique<NamespaceValidatorCCC>(*this);
12043 }
12044};
12045
12046}
12047
12048static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12049 Sema &S) {
12050 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12051 Module *M = ND->getOwningModule();
12052 assert(M && "hidden namespace definition not in a module?");
12053
12054 if (M->isExplicitGlobalModule())
12055 S.Diag(Corrected.getCorrectionRange().getBegin(),
12056 diag::err_module_unimported_use_header)
12058 << /*Header Name*/ false;
12059 else
12060 S.Diag(Corrected.getCorrectionRange().getBegin(),
12061 diag::err_module_unimported_use)
12063 << M->getTopLevelModuleName();
12064}
12065
12067 CXXScopeSpec &SS,
12068 SourceLocation IdentLoc,
12069 IdentifierInfo *Ident) {
12070 R.clear();
12071 NamespaceValidatorCCC CCC{};
12072 if (TypoCorrection Corrected =
12073 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12075 // Generally we find it is confusing more than helpful to diagnose the
12076 // invisible namespace.
12077 // See https://github.com/llvm/llvm-project/issues/73893.
12078 //
12079 // However, we should diagnose when the users are trying to using an
12080 // invisible namespace. So we handle the case specially here.
12081 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12082 Corrected.requiresImport()) {
12083 DiagnoseInvisibleNamespace(Corrected, S);
12084 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12085 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12086 bool DroppedSpecifier =
12087 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12088 S.diagnoseTypo(Corrected,
12089 S.PDiag(diag::err_using_directive_member_suggest)
12090 << Ident << DC << DroppedSpecifier << SS.getRange(),
12091 S.PDiag(diag::note_namespace_defined_here));
12092 } else {
12093 S.diagnoseTypo(Corrected,
12094 S.PDiag(diag::err_using_directive_suggest) << Ident,
12095 S.PDiag(diag::note_namespace_defined_here));
12096 }
12097 R.addDecl(Corrected.getFoundDecl());
12098 return true;
12099 }
12100 return false;
12101}
12102
12104 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12105 SourceLocation IdentLoc,
12106 IdentifierInfo *NamespcName,
12107 const ParsedAttributesView &AttrList) {
12108 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12109 assert(NamespcName && "Invalid NamespcName.");
12110 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12111
12112 // Get the innermost enclosing declaration scope.
12113 S = S->getDeclParent();
12114
12115 UsingDirectiveDecl *UDir = nullptr;
12116 NestedNameSpecifier *Qualifier = nullptr;
12117 if (SS.isSet())
12118 Qualifier = SS.getScopeRep();
12119
12120 // Lookup namespace name.
12121 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12122 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12123 if (R.isAmbiguous())
12124 return nullptr;
12125
12126 if (R.empty()) {
12127 R.clear();
12128 // Allow "using namespace std;" or "using namespace ::std;" even if
12129 // "std" hasn't been defined yet, for GCC compatibility.
12130 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12131 NamespcName->isStr("std")) {
12132 Diag(IdentLoc, diag::ext_using_undefined_std);
12134 R.resolveKind();
12135 }
12136 // Otherwise, attempt typo correction.
12137 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12138 }
12139
12140 if (!R.empty()) {
12141 NamedDecl *Named = R.getRepresentativeDecl();
12143 assert(NS && "expected namespace decl");
12144
12145 // The use of a nested name specifier may trigger deprecation warnings.
12146 DiagnoseUseOfDecl(Named, IdentLoc);
12147
12148 // C++ [namespace.udir]p1:
12149 // A using-directive specifies that the names in the nominated
12150 // namespace can be used in the scope in which the
12151 // using-directive appears after the using-directive. During
12152 // unqualified name lookup (3.4.1), the names appear as if they
12153 // were declared in the nearest enclosing namespace which
12154 // contains both the using-directive and the nominated
12155 // namespace. [Note: in this context, "contains" means "contains
12156 // directly or indirectly". ]
12157
12158 // Find enclosing context containing both using-directive and
12159 // nominated namespace.
12160 DeclContext *CommonAncestor = NS;
12161 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12162 CommonAncestor = CommonAncestor->getParent();
12163
12164 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12166 IdentLoc, Named, CommonAncestor);
12167
12170 Diag(IdentLoc, diag::warn_using_directive_in_header);
12171 }
12172
12173 PushUsingDirective(S, UDir);
12174 } else {
12175 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12176 }
12177
12178 if (UDir) {
12179 ProcessDeclAttributeList(S, UDir, AttrList);
12180 ProcessAPINotes(UDir);
12181 }
12182
12183 return UDir;
12184}
12185
12187 // If the scope has an associated entity and the using directive is at
12188 // namespace or translation unit scope, add the UsingDirectiveDecl into
12189 // its lookup structure so qualified name lookup can find it.
12190 DeclContext *Ctx = S->getEntity();
12191 if (Ctx && !Ctx->isFunctionOrMethod())
12192 Ctx->addDecl(UDir);
12193 else
12194 // Otherwise, it is at block scope. The using-directives will affect lookup
12195 // only to the end of the scope.
12196 S->PushUsingDirective(UDir);
12197}
12198
12200 SourceLocation UsingLoc,
12201 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12202 UnqualifiedId &Name,
12203 SourceLocation EllipsisLoc,
12204 const ParsedAttributesView &AttrList) {
12205 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12206
12207 if (SS.isEmpty()) {
12208 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12209 return nullptr;
12210 }
12211
12212 switch (Name.getKind()) {
12218 break;
12219
12222 // C++11 inheriting constructors.
12223 Diag(Name.getBeginLoc(),
12225 ? diag::warn_cxx98_compat_using_decl_constructor
12226 : diag::err_using_decl_constructor)
12227 << SS.getRange();
12228
12229 if (getLangOpts().CPlusPlus11) break;
12230
12231 return nullptr;
12232
12234 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12235 return nullptr;
12236
12238 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12239 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12240 return nullptr;
12241
12243 llvm_unreachable("cannot parse qualified deduction guide name");
12244 }
12245
12246 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12247 DeclarationName TargetName = TargetNameInfo.getName();
12248 if (!TargetName)
12249 return nullptr;
12250
12251 // Warn about access declarations.
12252 if (UsingLoc.isInvalid()) {
12253 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12254 ? diag::err_access_decl
12255 : diag::warn_access_decl_deprecated)
12256 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12257 }
12258
12259 if (EllipsisLoc.isInvalid()) {
12262 return nullptr;
12263 } else {
12265 !TargetNameInfo.containsUnexpandedParameterPack()) {
12266 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12267 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12268 EllipsisLoc = SourceLocation();
12269 }
12270 }
12271
12272 NamedDecl *UD =
12273 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12274 SS, TargetNameInfo, EllipsisLoc, AttrList,
12275 /*IsInstantiation*/ false,
12276 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12277 if (UD)
12278 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12279
12280 return UD;
12281}
12282
12284 SourceLocation UsingLoc,
12285 SourceLocation EnumLoc, SourceRange TyLoc,
12286 const IdentifierInfo &II, ParsedType Ty,
12287 CXXScopeSpec *SS) {
12288 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12289 TypeSourceInfo *TSI = nullptr;
12290 SourceLocation IdentLoc = TyLoc.getBegin();
12291 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12292 if (EnumTy.isNull()) {
12293 Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12294 ? diag::err_using_enum_is_dependent
12295 : diag::err_unknown_typename)
12296 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12297 return nullptr;
12298 }
12299
12300 if (EnumTy->isDependentType()) {
12301 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12302 return nullptr;
12303 }
12304
12305 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12306 if (!Enum) {
12307 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12308 return nullptr;
12309 }
12310
12311 if (auto *Def = Enum->getDefinition())
12312 Enum = Def;
12313
12314 if (TSI == nullptr)
12315 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12316
12317 auto *UD =
12318 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12319
12320 if (UD)
12321 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12322
12323 return UD;
12324}
12325
12326/// Determine whether a using declaration considers the given
12327/// declarations as "equivalent", e.g., if they are redeclarations of
12328/// the same entity or are both typedefs of the same type.
12329static bool
12331 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12332 return true;
12333
12334 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12335 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12336 return Context.hasSameType(TD1->getUnderlyingType(),
12337 TD2->getUnderlyingType());
12338
12339 // Two using_if_exists using-declarations are equivalent if both are
12340 // unresolved.
12341 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12342 isa<UnresolvedUsingIfExistsDecl>(D2))
12343 return true;
12344
12345 return false;
12346}
12347
12349 const LookupResult &Previous,
12350 UsingShadowDecl *&PrevShadow) {
12351 // Diagnose finding a decl which is not from a base class of the
12352 // current class. We do this now because there are cases where this
12353 // function will silently decide not to build a shadow decl, which
12354 // will pre-empt further diagnostics.
12355 //
12356 // We don't need to do this in C++11 because we do the check once on
12357 // the qualifier.
12358 //
12359 // FIXME: diagnose the following if we care enough:
12360 // struct A { int foo; };
12361 // struct B : A { using A::foo; };
12362 // template <class T> struct C : A {};
12363 // template <class T> struct D : C<T> { using B::foo; } // <---
12364 // This is invalid (during instantiation) in C++03 because B::foo
12365 // resolves to the using decl in B, which is not a base class of D<T>.
12366 // We can't diagnose it immediately because C<T> is an unknown
12367 // specialization. The UsingShadowDecl in D<T> then points directly
12368 // to A::foo, which will look well-formed when we instantiate.
12369 // The right solution is to not collapse the shadow-decl chain.
12371 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12372 DeclContext *OrigDC = Orig->getDeclContext();
12373
12374 // Handle enums and anonymous structs.
12375 if (isa<EnumDecl>(OrigDC))
12376 OrigDC = OrigDC->getParent();
12377 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12378 while (OrigRec->isAnonymousStructOrUnion())
12379 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12380
12381 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12382 if (OrigDC == CurContext) {
12383 Diag(Using->getLocation(),
12384 diag::err_using_decl_nested_name_specifier_is_current_class)
12385 << Using->getQualifierLoc().getSourceRange();
12386 Diag(Orig->getLocation(), diag::note_using_decl_target);
12387 Using->setInvalidDecl();
12388 return true;
12389 }
12390
12391 Diag(Using->getQualifierLoc().getBeginLoc(),
12392 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12393 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12394 << Using->getQualifierLoc().getSourceRange();
12395 Diag(Orig->getLocation(), diag::note_using_decl_target);
12396 Using->setInvalidDecl();
12397 return true;
12398 }
12399 }
12400
12401 if (Previous.empty()) return false;
12402
12403 NamedDecl *Target = Orig;
12404 if (isa<UsingShadowDecl>(Target))
12405 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12406
12407 // If the target happens to be one of the previous declarations, we
12408 // don't have a conflict.
12409 //
12410 // FIXME: but we might be increasing its access, in which case we
12411 // should redeclare it.
12412 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12413 bool FoundEquivalentDecl = false;
12414 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12415 I != E; ++I) {
12416 NamedDecl *D = (*I)->getUnderlyingDecl();
12417 // We can have UsingDecls in our Previous results because we use the same
12418 // LookupResult for checking whether the UsingDecl itself is a valid
12419 // redeclaration.
12420 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12421 continue;
12422
12423 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12424 // C++ [class.mem]p19:
12425 // If T is the name of a class, then [every named member other than
12426 // a non-static data member] shall have a name different from T
12427 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12428 !isa<IndirectFieldDecl>(Target) &&
12429 !isa<UnresolvedUsingValueDecl>(Target) &&
12431 CurContext,
12433 return true;
12434 }
12435
12437 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12438 PrevShadow = Shadow;
12439 FoundEquivalentDecl = true;
12441 // We don't conflict with an existing using shadow decl of an equivalent
12442 // declaration, but we're not a redeclaration of it.
12443 FoundEquivalentDecl = true;
12444 }
12445
12446 if (isVisible(D))
12447 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12448 }
12449
12450 if (FoundEquivalentDecl)
12451 return false;
12452
12453 // Always emit a diagnostic for a mismatch between an unresolved
12454 // using_if_exists and a resolved using declaration in either direction.
12455 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12456 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12457 if (!NonTag && !Tag)
12458 return false;
12459 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12460 Diag(Target->getLocation(), diag::note_using_decl_target);
12461 Diag((NonTag ? NonTag : Tag)->getLocation(),
12462 diag::note_using_decl_conflict);
12463 BUD->setInvalidDecl();
12464 return true;
12465 }
12466
12467 if (FunctionDecl *FD = Target->getAsFunction()) {
12468 NamedDecl *OldDecl = nullptr;
12469 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12470 /*IsForUsingDecl*/ true)) {
12471 case Ovl_Overload:
12472 return false;
12473
12474 case Ovl_NonFunction:
12475 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12476 break;
12477
12478 // We found a decl with the exact signature.
12479 case Ovl_Match:
12480 // If we're in a record, we want to hide the target, so we
12481 // return true (without a diagnostic) to tell the caller not to
12482 // build a shadow decl.
12483 if (CurContext->isRecord())
12484 return true;
12485
12486 // If we're not in a record, this is an error.
12487 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12488 break;
12489 }
12490
12491 Diag(Target->getLocation(), diag::note_using_decl_target);
12492 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12493 BUD->setInvalidDecl();
12494 return true;
12495 }
12496
12497 // Target is not a function.
12498
12499 if (isa<TagDecl>(Target)) {
12500 // No conflict between a tag and a non-tag.
12501 if (!Tag) return false;
12502
12503 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12504 Diag(Target->getLocation(), diag::note_using_decl_target);
12505 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12506 BUD->setInvalidDecl();
12507 return true;
12508 }
12509
12510 // No conflict between a tag and a non-tag.
12511 if (!NonTag) return false;
12512
12513 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12514 Diag(Target->getLocation(), diag::note_using_decl_target);
12515 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12516 BUD->setInvalidDecl();
12517 return true;
12518}
12519
12520/// Determine whether a direct base class is a virtual base class.
12522 if (!Derived->getNumVBases())
12523 return false;
12524 for (auto &B : Derived->bases())
12525 if (B.getType()->getAsCXXRecordDecl() == Base)
12526 return B.isVirtual();
12527 llvm_unreachable("not a direct base class");
12528}
12529
12531 NamedDecl *Orig,
12532 UsingShadowDecl *PrevDecl) {
12533 // If we resolved to another shadow declaration, just coalesce them.
12534 NamedDecl *Target = Orig;
12535 if (isa<UsingShadowDecl>(Target)) {
12536 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12537 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12538 }
12539
12540 NamedDecl *NonTemplateTarget = Target;
12541 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12542 NonTemplateTarget = TargetTD->getTemplatedDecl();
12543
12544 UsingShadowDecl *Shadow;
12545 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12546 UsingDecl *Using = cast<UsingDecl>(BUD);
12547 bool IsVirtualBase =
12548 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12549 Using->getQualifier()->getAsRecordDecl());
12551 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12552 } else {
12554 Target->getDeclName(), BUD, Target);
12555 }
12556 BUD->addShadowDecl(Shadow);
12557
12558 Shadow->setAccess(BUD->getAccess());
12559 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12560 Shadow->setInvalidDecl();
12561
12562 Shadow->setPreviousDecl(PrevDecl);
12563
12564 if (S)
12565 PushOnScopeChains(Shadow, S);
12566 else
12567 CurContext->addDecl(Shadow);
12568
12569
12570 return Shadow;
12571}
12572
12574 if (Shadow->getDeclName().getNameKind() ==
12576 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12577
12578 // Remove it from the DeclContext...
12579 Shadow->getDeclContext()->removeDecl(Shadow);
12580
12581 // ...and the scope, if applicable...
12582 if (S) {
12583 S->RemoveDecl(Shadow);
12584 IdResolver.RemoveDecl(Shadow);
12585 }
12586
12587 // ...and the using decl.
12588 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12589
12590 // TODO: complain somehow if Shadow was used. It shouldn't
12591 // be possible for this to happen, because...?
12592}
12593
12594/// Find the base specifier for a base class with the given type.
12596 QualType DesiredBase,
12597 bool &AnyDependentBases) {
12598 // Check whether the named type is a direct base class.
12599 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12601 for (auto &Base : Derived->bases()) {
12602 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12603 if (CanonicalDesiredBase == BaseType)
12604 return &Base;
12605 if (BaseType->isDependentType())
12606 AnyDependentBases = true;
12607 }
12608 return nullptr;
12609}
12610
12611namespace {
12612class UsingValidatorCCC final : public CorrectionCandidateCallback {
12613public:
12614 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12615 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12616 : HasTypenameKeyword(HasTypenameKeyword),
12617 IsInstantiation(IsInstantiation), OldNNS(NNS),
12618 RequireMemberOf(RequireMemberOf) {}
12619
12620 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12621 NamedDecl *ND = Candidate.getCorrectionDecl();
12622
12623 // Keywords are not valid here.
12624 if (!ND || isa<NamespaceDecl>(ND))
12625 return false;
12626
12627 // Completely unqualified names are invalid for a 'using' declaration.
12628 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12629 return false;
12630
12631 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12632 // reject.
12633
12634 if (RequireMemberOf) {
12635 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12636 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12637 // No-one ever wants a using-declaration to name an injected-class-name
12638 // of a base class, unless they're declaring an inheriting constructor.
12639 ASTContext &Ctx = ND->getASTContext();
12640 if (!Ctx.getLangOpts().CPlusPlus11)
12641 return false;
12642 QualType FoundType = Ctx.getRecordType(FoundRecord);
12643
12644 // Check that the injected-class-name is named as a member of its own
12645 // type; we don't want to suggest 'using Derived::Base;', since that
12646 // means something else.
12648 Candidate.WillReplaceSpecifier()
12649 ? Candidate.getCorrectionSpecifier()
12650 : OldNNS;
12651 if (!Specifier->getAsType() ||
12652 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12653 return false;
12654
12655 // Check that this inheriting constructor declaration actually names a
12656 // direct base class of the current class.
12657 bool AnyDependentBases = false;
12658 if (!findDirectBaseWithType(RequireMemberOf,
12659 Ctx.getRecordType(FoundRecord),
12660 AnyDependentBases) &&
12661 !AnyDependentBases)
12662 return false;
12663 } else {
12664 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12665 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12666 return false;
12667
12668 // FIXME: Check that the base class member is accessible?
12669 }
12670 } else {
12671 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12672 if (FoundRecord && FoundRecord->isInjectedClassName())
12673 return false;
12674 }
12675
12676 if (isa<TypeDecl>(ND))
12677 return HasTypenameKeyword || !IsInstantiation;
12678
12679 return !HasTypenameKeyword;
12680 }
12681
12682 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12683 return std::make_unique<UsingValidatorCCC>(*this);
12684 }
12685
12686private:
12687 bool HasTypenameKeyword;
12688 bool IsInstantiation;
12689 NestedNameSpecifier *OldNNS;
12690 CXXRecordDecl *RequireMemberOf;
12691};
12692} // end anonymous namespace
12693
12695 // It is really dumb that we have to do this.
12696 LookupResult::Filter F = Previous.makeFilter();
12697 while (F.hasNext()) {
12698 NamedDecl *D = F.next();
12699 if (!isDeclInScope(D, CurContext, S))
12700 F.erase();
12701 // If we found a local extern declaration that's not ordinarily visible,
12702 // and this declaration is being added to a non-block scope, ignore it.
12703 // We're only checking for scope conflicts here, not also for violations
12704 // of the linkage rules.
12705 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12707 F.erase();
12708 }
12709 F.done();
12710}
12711
12713 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12714 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12715 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12716 const ParsedAttributesView &AttrList, bool IsInstantiation,
12717 bool IsUsingIfExists) {
12718 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12719 SourceLocation IdentLoc = NameInfo.getLoc();
12720 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12721
12722 // FIXME: We ignore attributes for now.
12723
12724 // For an inheriting constructor declaration, the name of the using
12725 // declaration is the name of a constructor in this class, not in the
12726 // base class.
12727 DeclarationNameInfo UsingName = NameInfo;
12729 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12732
12733 // Do the redeclaration lookup in the current scope.
12734 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12735 RedeclarationKind::ForVisibleRedeclaration);
12736 Previous.setHideTags(false);
12737 if (S) {
12738 LookupName(Previous, S);
12739
12741 } else {
12742 assert(IsInstantiation && "no scope in non-instantiation");
12743 if (CurContext->isRecord())
12745 else {
12746 // No redeclaration check is needed here; in non-member contexts we
12747 // diagnosed all possible conflicts with other using-declarations when
12748 // building the template:
12749 //
12750 // For a dependent non-type using declaration, the only valid case is
12751 // if we instantiate to a single enumerator. We check for conflicts
12752 // between shadow declarations we introduce, and we check in the template
12753 // definition for conflicts between a non-type using declaration and any
12754 // other declaration, which together covers all cases.
12755 //
12756 // A dependent typename using declaration will never successfully
12757 // instantiate, since it will always name a class member, so we reject
12758 // that in the template definition.
12759 }
12760 }
12761
12762 // Check for invalid redeclarations.
12763 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12764 SS, IdentLoc, Previous))
12765 return nullptr;
12766
12767 // 'using_if_exists' doesn't make sense on an inherited constructor.
12768 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12770 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12771 return nullptr;
12772 }
12773
12774 DeclContext *LookupContext = computeDeclContext(SS);
12776 if (!LookupContext || EllipsisLoc.isValid()) {
12777 NamedDecl *D;
12778 // Dependent scope, or an unexpanded pack
12779 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12780 SS, NameInfo, IdentLoc))
12781 return nullptr;
12782
12783 if (HasTypenameKeyword) {
12784 // FIXME: not all declaration name kinds are legal here
12786 UsingLoc, TypenameLoc,
12787 QualifierLoc,
12788 IdentLoc, NameInfo.getName(),
12789 EllipsisLoc);
12790 } else {
12792 QualifierLoc, NameInfo, EllipsisLoc);
12793 }
12794 D->setAccess(AS);
12796 ProcessDeclAttributeList(S, D, AttrList);
12797 return D;
12798 }
12799
12800 auto Build = [&](bool Invalid) {
12801 UsingDecl *UD =
12802 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12803 UsingName, HasTypenameKeyword);
12804 UD->setAccess(AS);
12805 CurContext->addDecl(UD);
12806 ProcessDeclAttributeList(S, UD, AttrList);
12808 return UD;
12809 };
12810 auto BuildInvalid = [&]{ return Build(true); };
12811 auto BuildValid = [&]{ return Build(false); };
12812
12813 if (RequireCompleteDeclContext(SS, LookupContext))
12814 return BuildInvalid();
12815
12816 // Look up the target name.
12817 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12818
12819 // Unlike most lookups, we don't always want to hide tag
12820 // declarations: tag names are visible through the using declaration
12821 // even if hidden by ordinary names, *except* in a dependent context
12822 // where they may be used by two-phase lookup.
12823 if (!IsInstantiation)
12824 R.setHideTags(false);
12825
12826 // For the purposes of this lookup, we have a base object type
12827 // equal to that of the current context.
12828 if (CurContext->isRecord()) {
12830 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12831 }
12832
12833 LookupQualifiedName(R, LookupContext);
12834
12835 // Validate the context, now we have a lookup
12836 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12837 IdentLoc, &R))
12838 return nullptr;
12839
12840 if (R.empty() && IsUsingIfExists)
12842 UsingName.getName()),
12843 AS_public);
12844
12845 // Try to correct typos if possible. If constructor name lookup finds no
12846 // results, that means the named class has no explicit constructors, and we
12847 // suppressed declaring implicit ones (probably because it's dependent or
12848 // invalid).
12849 if (R.empty() &&
12851 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12852 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12853 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12854 auto *II = NameInfo.getName().getAsIdentifierInfo();
12855 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12857 isa<TranslationUnitDecl>(LookupContext) &&
12858 getSourceManager().isInSystemHeader(UsingLoc))
12859 return nullptr;
12860 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12861 dyn_cast<CXXRecordDecl>(CurContext));
12862 if (TypoCorrection Corrected =
12863 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12865 // We reject candidates where DroppedSpecifier == true, hence the
12866 // literal '0' below.
12867 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12868 << NameInfo.getName() << LookupContext << 0
12869 << SS.getRange());
12870
12871 // If we picked a correction with no attached Decl we can't do anything
12872 // useful with it, bail out.
12873 NamedDecl *ND = Corrected.getCorrectionDecl();
12874 if (!ND)
12875 return BuildInvalid();
12876
12877 // If we corrected to an inheriting constructor, handle it as one.
12878 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12879 if (RD && RD->isInjectedClassName()) {
12880 // The parent of the injected class name is the class itself.
12881 RD = cast<CXXRecordDecl>(RD->getParent());
12882
12883 // Fix up the information we'll use to build the using declaration.
12884 if (Corrected.WillReplaceSpecifier()) {
12886 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12887 QualifierLoc.getSourceRange());
12888 QualifierLoc = Builder.getWithLocInContext(Context);
12889 }
12890
12891 // In this case, the name we introduce is the name of a derived class
12892 // constructor.
12893 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12896 UsingName.setNamedTypeInfo(nullptr);
12897 for (auto *Ctor : LookupConstructors(RD))
12898 R.addDecl(Ctor);
12899 R.resolveKind();
12900 } else {
12901 // FIXME: Pick up all the declarations if we found an overloaded
12902 // function.
12903 UsingName.setName(ND->getDeclName());
12904 R.addDecl(ND);
12905 }
12906 } else {
12907 Diag(IdentLoc, diag::err_no_member)
12908 << NameInfo.getName() << LookupContext << SS.getRange();
12909 return BuildInvalid();
12910 }
12911 }
12912
12913 if (R.isAmbiguous())
12914 return BuildInvalid();
12915
12916 if (HasTypenameKeyword) {
12917 // If we asked for a typename and got a non-type decl, error out.
12918 if (!R.getAsSingle<TypeDecl>() &&
12920 Diag(IdentLoc, diag::err_using_typename_non_type);
12921 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12922 Diag((*I)->getUnderlyingDecl()->getLocation(),
12923 diag::note_using_decl_target);
12924 return BuildInvalid();
12925 }
12926 } else {
12927 // If we asked for a non-typename and we got a type, error out,
12928 // but only if this is an instantiation of an unresolved using
12929 // decl. Otherwise just silently find the type name.
12930 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12931 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12932 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12933 return BuildInvalid();
12934 }
12935 }
12936
12937 // C++14 [namespace.udecl]p6:
12938 // A using-declaration shall not name a namespace.
12939 if (R.getAsSingle<NamespaceDecl>()) {
12940 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12941 << SS.getRange();
12942 // Suggest using 'using namespace ...' instead.
12943 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
12944 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
12945 return BuildInvalid();
12946 }
12947
12948 UsingDecl *UD = BuildValid();
12949
12950 // Some additional rules apply to inheriting constructors.
12951 if (UsingName.getName().getNameKind() ==
12953 // Suppress access diagnostics; the access check is instead performed at the
12954 // point of use for an inheriting constructor.
12957 return UD;
12958 }
12959
12960 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12961 UsingShadowDecl *PrevDecl = nullptr;
12962 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12963 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12964 }
12965
12966 return UD;
12967}
12968
12970 SourceLocation UsingLoc,
12971 SourceLocation EnumLoc,
12972 SourceLocation NameLoc,
12974 EnumDecl *ED) {
12975 bool Invalid = false;
12976
12978 /// In class scope, check if this is a duplicate, for better a diagnostic.
12979 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12980 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12981 RedeclarationKind::ForVisibleRedeclaration);
12982
12983 LookupName(Previous, S);
12984
12985 for (NamedDecl *D : Previous)
12986 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12987 if (UED->getEnumDecl() == ED) {
12988 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12989 << SourceRange(EnumLoc, NameLoc);
12990 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12991 Invalid = true;
12992 break;
12993 }
12994 }
12995
12996 if (RequireCompleteEnumDecl(ED, NameLoc))
12997 Invalid = true;
12998
13000 EnumLoc, NameLoc, EnumType);
13001 UD->setAccess(AS);
13002 CurContext->addDecl(UD);
13003
13004 if (Invalid) {
13005 UD->setInvalidDecl();
13006 return UD;
13007 }
13008
13009 // Create the shadow decls for each enumerator
13010 for (EnumConstantDecl *EC : ED->enumerators()) {
13011 UsingShadowDecl *PrevDecl = nullptr;
13012 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13014 RedeclarationKind::ForVisibleRedeclaration);
13015 LookupName(Previous, S);
13017
13018 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13019 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13020 }
13021
13022 return UD;
13023}
13024
13026 ArrayRef<NamedDecl *> Expansions) {
13027 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13028 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13029 isa<UsingPackDecl>(InstantiatedFrom));
13030
13031 auto *UPD =
13032 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13033 UPD->setAccess(InstantiatedFrom->getAccess());
13034 CurContext->addDecl(UPD);
13035 return UPD;
13036}
13037
13039 assert(!UD->hasTypename() && "expecting a constructor name");
13040
13041 const Type *SourceType = UD->getQualifier()->getAsType();
13042 assert(SourceType &&
13043 "Using decl naming constructor doesn't have type in scope spec.");
13044 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13045
13046 // Check whether the named type is a direct base class.
13047 bool AnyDependentBases = false;
13048 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13049 AnyDependentBases);
13050 if (!Base && !AnyDependentBases) {
13051 Diag(UD->getUsingLoc(),
13052 diag::err_using_decl_constructor_not_in_direct_base)
13053 << UD->getNameInfo().getSourceRange()
13054 << QualType(SourceType, 0) << TargetClass;
13055 UD->setInvalidDecl();
13056 return true;
13057 }
13058
13059 if (Base)
13060 Base->setInheritConstructors();
13061
13062 return false;
13063}
13064
13066 bool HasTypenameKeyword,
13067 const CXXScopeSpec &SS,
13068 SourceLocation NameLoc,
13069 const LookupResult &Prev) {
13070 NestedNameSpecifier *Qual = SS.getScopeRep();
13071
13072 // C++03 [namespace.udecl]p8:
13073 // C++0x [namespace.udecl]p10:
13074 // A using-declaration is a declaration and can therefore be used
13075 // repeatedly where (and only where) multiple declarations are
13076 // allowed.
13077 //
13078 // That's in non-member contexts.
13080 // A dependent qualifier outside a class can only ever resolve to an
13081 // enumeration type. Therefore it conflicts with any other non-type
13082 // declaration in the same scope.
13083 // FIXME: How should we check for dependent type-type conflicts at block
13084 // scope?
13085 if (Qual->isDependent() && !HasTypenameKeyword) {
13086 for (auto *D : Prev) {
13087 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13088 bool OldCouldBeEnumerator =
13089 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13090 Diag(NameLoc,
13091 OldCouldBeEnumerator ? diag::err_redefinition
13092 : diag::err_redefinition_different_kind)
13093 << Prev.getLookupName();
13094 Diag(D->getLocation(), diag::note_previous_definition);
13095 return true;
13096 }
13097 }
13098 }
13099 return false;
13100 }
13101
13102 const NestedNameSpecifier *CNNS =
13104 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13105 NamedDecl *D = *I;
13106
13107 bool DTypename;
13108 NestedNameSpecifier *DQual;
13109 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13110 DTypename = UD->hasTypename();
13111 DQual = UD->getQualifier();
13112 } else if (UnresolvedUsingValueDecl *UD
13113 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13114 DTypename = false;
13115 DQual = UD->getQualifier();
13116 } else if (UnresolvedUsingTypenameDecl *UD
13117 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13118 DTypename = true;
13119 DQual = UD->getQualifier();
13120 } else continue;
13121
13122 // using decls differ if one says 'typename' and the other doesn't.
13123 // FIXME: non-dependent using decls?
13124 if (HasTypenameKeyword != DTypename) continue;
13125
13126 // using decls differ if they name different scopes (but note that
13127 // template instantiation can cause this check to trigger when it
13128 // didn't before instantiation).
13129 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13130 continue;
13131
13132 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13133 Diag(D->getLocation(), diag::note_using_decl) << 1;
13134 return true;
13135 }
13136
13137 return false;
13138}
13139
13140bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13141 const CXXScopeSpec &SS,
13142 const DeclarationNameInfo &NameInfo,
13143 SourceLocation NameLoc,
13144 const LookupResult *R, const UsingDecl *UD) {
13145 DeclContext *NamedContext = computeDeclContext(SS);
13146 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13147 "resolvable context must have exactly one set of decls");
13148
13149 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13150 // relationship.
13151 bool Cxx20Enumerator = false;
13152 if (NamedContext) {
13153 EnumConstantDecl *EC = nullptr;
13154 if (R)
13155 EC = R->getAsSingle<EnumConstantDecl>();
13156 else if (UD && UD->shadow_size() == 1)
13157 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13158 if (EC)
13159 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13160
13161 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13162 // C++14 [namespace.udecl]p7:
13163 // A using-declaration shall not name a scoped enumerator.
13164 // C++20 p1099 permits enumerators.
13165 if (EC && R && ED->isScoped())
13166 Diag(SS.getBeginLoc(),
13168 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13169 : diag::ext_using_decl_scoped_enumerator)
13170 << SS.getRange();
13171
13172 // We want to consider the scope of the enumerator
13173 NamedContext = ED->getDeclContext();
13174 }
13175 }
13176
13177 if (!CurContext->isRecord()) {
13178 // C++03 [namespace.udecl]p3:
13179 // C++0x [namespace.udecl]p8:
13180 // A using-declaration for a class member shall be a member-declaration.
13181 // C++20 [namespace.udecl]p7
13182 // ... other than an enumerator ...
13183
13184 // If we weren't able to compute a valid scope, it might validly be a
13185 // dependent class or enumeration scope. If we have a 'typename' keyword,
13186 // the scope must resolve to a class type.
13187 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13188 : !HasTypename)
13189 return false; // OK
13190
13191 Diag(NameLoc,
13192 Cxx20Enumerator
13193 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13194 : diag::err_using_decl_can_not_refer_to_class_member)
13195 << SS.getRange();
13196
13197 if (Cxx20Enumerator)
13198 return false; // OK
13199
13200 auto *RD = NamedContext
13201 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13202 : nullptr;
13203 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13204 // See if there's a helpful fixit
13205
13206 if (!R) {
13207 // We will have already diagnosed the problem on the template
13208 // definition, Maybe we should do so again?
13209 } else if (R->getAsSingle<TypeDecl>()) {
13210 if (getLangOpts().CPlusPlus11) {
13211 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13212 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13213 << 0 // alias declaration
13215 NameInfo.getName().getAsString() +
13216 " = ");
13217 } else {
13218 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13219 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13220 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13221 << 1 // typedef declaration
13222 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13224 InsertLoc, " " + NameInfo.getName().getAsString());
13225 }
13226 } else if (R->getAsSingle<VarDecl>()) {
13227 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13228 // repeating the type of the static data member here.
13229 FixItHint FixIt;
13230 if (getLangOpts().CPlusPlus11) {
13231 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13233 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13234 }
13235
13236 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13237 << 2 // reference declaration
13238 << FixIt;
13239 } else if (R->getAsSingle<EnumConstantDecl>()) {
13240 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13241 // repeating the type of the enumeration here, and we can't do so if
13242 // the type is anonymous.
13243 FixItHint FixIt;
13244 if (getLangOpts().CPlusPlus11) {
13245 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13247 UsingLoc,
13248 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13249 }
13250
13251 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13252 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13253 << FixIt;
13254 }
13255 }
13256
13257 return true; // Fail
13258 }
13259
13260 // If the named context is dependent, we can't decide much.
13261 if (!NamedContext) {
13262 // FIXME: in C++0x, we can diagnose if we can prove that the
13263 // nested-name-specifier does not refer to a base class, which is
13264 // still possible in some cases.
13265
13266 // Otherwise we have to conservatively report that things might be
13267 // okay.
13268 return false;
13269 }
13270
13271 // The current scope is a record.
13272 if (!NamedContext->isRecord()) {
13273 // Ideally this would point at the last name in the specifier,
13274 // but we don't have that level of source info.
13275 Diag(SS.getBeginLoc(),
13276 Cxx20Enumerator
13277 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13278 : diag::err_using_decl_nested_name_specifier_is_not_class)
13279 << SS.getScopeRep() << SS.getRange();
13280
13281 if (Cxx20Enumerator)
13282 return false; // OK
13283
13284 return true;
13285 }
13286
13287 if (!NamedContext->isDependentContext() &&
13288 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13289 return true;
13290
13291 if (getLangOpts().CPlusPlus11) {
13292 // C++11 [namespace.udecl]p3:
13293 // In a using-declaration used as a member-declaration, the
13294 // nested-name-specifier shall name a base class of the class
13295 // being defined.
13296
13297 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13298 cast<CXXRecordDecl>(NamedContext))) {
13299
13300 if (Cxx20Enumerator) {
13301 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13302 << SS.getRange();
13303 return false;
13304 }
13305
13306 if (CurContext == NamedContext) {
13307 Diag(SS.getBeginLoc(),
13308 diag::err_using_decl_nested_name_specifier_is_current_class)
13309 << SS.getRange();
13310 return !getLangOpts().CPlusPlus20;
13311 }
13312
13313 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13314 Diag(SS.getBeginLoc(),
13315 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13316 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13317 << SS.getRange();
13318 }
13319 return true;
13320 }
13321
13322 return false;
13323 }
13324
13325 // C++03 [namespace.udecl]p4:
13326 // A using-declaration used as a member-declaration shall refer
13327 // to a member of a base class of the class being defined [etc.].
13328
13329 // Salient point: SS doesn't have to name a base class as long as
13330 // lookup only finds members from base classes. Therefore we can
13331 // diagnose here only if we can prove that can't happen,
13332 // i.e. if the class hierarchies provably don't intersect.
13333
13334 // TODO: it would be nice if "definitely valid" results were cached
13335 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13336 // need to be repeated.
13337
13339 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13340 Bases.insert(Base);
13341 return true;
13342 };
13343
13344 // Collect all bases. Return false if we find a dependent base.
13345 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13346 return false;
13347
13348 // Returns true if the base is dependent or is one of the accumulated base
13349 // classes.
13350 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13351 return !Bases.count(Base);
13352 };
13353
13354 // Return false if the class has a dependent base or if it or one
13355 // of its bases is present in the base set of the current context.
13356 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13357 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13358 return false;
13359
13360 Diag(SS.getRange().getBegin(),
13361 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13362 << SS.getScopeRep()
13363 << cast<CXXRecordDecl>(CurContext)
13364 << SS.getRange();
13365
13366 return true;
13367}
13368
13370 MultiTemplateParamsArg TemplateParamLists,
13371 SourceLocation UsingLoc, UnqualifiedId &Name,
13372 const ParsedAttributesView &AttrList,
13373 TypeResult Type, Decl *DeclFromDeclSpec) {
13374 // Get the innermost enclosing declaration scope.
13375 S = S->getDeclParent();
13376
13377 if (Type.isInvalid())
13378 return nullptr;
13379
13380 bool Invalid = false;
13382 TypeSourceInfo *TInfo = nullptr;
13383 GetTypeFromParser(Type.get(), &TInfo);
13384
13385 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13386 return nullptr;
13387
13388 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13390 Invalid = true;
13392 TInfo->getTypeLoc().getBeginLoc());
13393 }
13394
13395 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13396 TemplateParamLists.size()
13398 : RedeclarationKind::ForVisibleRedeclaration);
13399 LookupName(Previous, S);
13400
13401 // Warn about shadowing the name of a template parameter.
13402 if (Previous.isSingleResult() &&
13403 Previous.getFoundDecl()->isTemplateParameter()) {
13404 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13405 Previous.clear();
13406 }
13407
13408 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13409 "name in alias declaration must be an identifier");
13411 Name.StartLocation,
13412 Name.Identifier, TInfo);
13413
13414 NewTD->setAccess(AS);
13415
13416 if (Invalid)
13417 NewTD->setInvalidDecl();
13418
13419 ProcessDeclAttributeList(S, NewTD, AttrList);
13420 AddPragmaAttributes(S, NewTD);
13421 ProcessAPINotes(NewTD);
13422
13424 Invalid |= NewTD->isInvalidDecl();
13425
13426 bool Redeclaration = false;
13427
13428 NamedDecl *NewND;
13429 if (TemplateParamLists.size()) {
13430 TypeAliasTemplateDecl *OldDecl = nullptr;
13431 TemplateParameterList *OldTemplateParams = nullptr;
13432
13433 if (TemplateParamLists.size() != 1) {
13434 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13435 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13436 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13437 Invalid = true;
13438 }
13439 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13440
13441 // Check that we can declare a template here.
13442 if (CheckTemplateDeclScope(S, TemplateParams))
13443 return nullptr;
13444
13445 // Only consider previous declarations in the same scope.
13446 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13447 /*ExplicitInstantiationOrSpecialization*/false);
13448 if (!Previous.empty()) {
13449 Redeclaration = true;
13450
13451 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13452 if (!OldDecl && !Invalid) {
13453 Diag(UsingLoc, diag::err_redefinition_different_kind)
13454 << Name.Identifier;
13455
13456 NamedDecl *OldD = Previous.getRepresentativeDecl();
13457 if (OldD->getLocation().isValid())
13458 Diag(OldD->getLocation(), diag::note_previous_definition);
13459
13460 Invalid = true;
13461 }
13462
13463 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13464 if (TemplateParameterListsAreEqual(TemplateParams,
13465 OldDecl->getTemplateParameters(),
13466 /*Complain=*/true,
13468 OldTemplateParams =
13470 else
13471 Invalid = true;
13472
13473 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13474 if (!Invalid &&
13476 NewTD->getUnderlyingType())) {
13477 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13478 // but we can't reasonably accept it.
13479 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13480 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13481 if (OldTD->getLocation().isValid())
13482 Diag(OldTD->getLocation(), diag::note_previous_definition);
13483 Invalid = true;
13484 }
13485 }
13486 }
13487
13488 // Merge any previous default template arguments into our parameters,
13489 // and check the parameter list.
13490 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13492 return nullptr;
13493
13494 TypeAliasTemplateDecl *NewDecl =
13496 Name.Identifier, TemplateParams,
13497 NewTD);
13498 NewTD->setDescribedAliasTemplate(NewDecl);
13499
13500 NewDecl->setAccess(AS);
13501
13502 if (Invalid)
13503 NewDecl->setInvalidDecl();
13504 else if (OldDecl) {
13505 NewDecl->setPreviousDecl(OldDecl);
13506 CheckRedeclarationInModule(NewDecl, OldDecl);
13507 }
13508
13509 NewND = NewDecl;
13510 } else {
13511 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13513 handleTagNumbering(TD, S);
13514 }
13515 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13516 NewND = NewTD;
13517 }
13518
13519 PushOnScopeChains(NewND, S);
13520 ActOnDocumentableDecl(NewND);
13521 return NewND;
13522}
13523
13525 SourceLocation AliasLoc,
13526 IdentifierInfo *Alias, CXXScopeSpec &SS,
13527 SourceLocation IdentLoc,
13528 IdentifierInfo *Ident) {
13529
13530 // Lookup the namespace name.
13531 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13532 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13533
13534 if (R.isAmbiguous())
13535 return nullptr;
13536
13537 if (R.empty()) {
13538 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13539 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13540 return nullptr;
13541 }
13542 }
13543 assert(!R.isAmbiguous() && !R.empty());
13545
13546 // Check if we have a previous declaration with the same name.
13547 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13548 RedeclarationKind::ForVisibleRedeclaration);
13549 LookupName(PrevR, S);
13550
13551 // Check we're not shadowing a template parameter.
13552 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13554 PrevR.clear();
13555 }
13556
13557 // Filter out any other lookup result from an enclosing scope.
13558 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13559 /*AllowInlineNamespace*/false);
13560
13561 // Find the previous declaration and check that we can redeclare it.
13562 NamespaceAliasDecl *Prev = nullptr;
13563 if (PrevR.isSingleResult()) {
13564 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13565 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13566 // We already have an alias with the same name that points to the same
13567 // namespace; check that it matches.
13568 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13569 Prev = AD;
13570 } else if (isVisible(PrevDecl)) {
13571 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13572 << Alias;
13573 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13574 << AD->getNamespace();
13575 return nullptr;
13576 }
13577 } else if (isVisible(PrevDecl)) {
13578 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13579 ? diag::err_redefinition
13580 : diag::err_redefinition_different_kind;
13581 Diag(AliasLoc, DiagID) << Alias;
13582 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13583 return nullptr;
13584 }
13585 }
13586
13587 // The use of a nested name specifier may trigger deprecation warnings.
13588 DiagnoseUseOfDecl(ND, IdentLoc);
13589
13591 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13592 Alias, SS.getWithLocInContext(Context),
13593 IdentLoc, ND);
13594 if (Prev)
13595 AliasDecl->setPreviousDecl(Prev);
13596
13598 return AliasDecl;
13599}
13600
13601namespace {
13602struct SpecialMemberExceptionSpecInfo
13603 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13606
13607 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13611 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13612
13613 bool visitBase(CXXBaseSpecifier *Base);
13614 bool visitField(FieldDecl *FD);
13615
13616 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13617 unsigned Quals);
13618
13619 void visitSubobjectCall(Subobject Subobj,
13621};
13622}
13623
13624bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13625 auto *RT = Base->getType()->getAs<RecordType>();
13626 if (!RT)
13627 return false;
13628
13629 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13630 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13631 if (auto *BaseCtor = SMOR.getMethod()) {
13632 visitSubobjectCall(Base, BaseCtor);
13633 return false;
13634 }
13635
13636 visitClassSubobject(BaseClass, Base, 0);
13637 return false;
13638}
13639
13640bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13642 FD->hasInClassInitializer()) {
13643 Expr *E = FD->getInClassInitializer();
13644 if (!E)
13645 // FIXME: It's a little wasteful to build and throw away a
13646 // CXXDefaultInitExpr here.
13647 // FIXME: We should have a single context note pointing at Loc, and
13648 // this location should be MD->getLocation() instead, since that's
13649 // the location where we actually use the default init expression.
13650 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13651 if (E)
13652 ExceptSpec.CalledExpr(E);
13653 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13654 ->getAs<RecordType>()) {
13655 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13656 FD->getType().getCVRQualifiers());
13657 }
13658 return false;
13659}
13660
13661void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13662 Subobject Subobj,
13663 unsigned Quals) {
13664 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13665 bool IsMutable = Field && Field->isMutable();
13666 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13667}
13668
13669void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13670 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13671 // Note, if lookup fails, it doesn't matter what exception specification we
13672 // choose because the special member will be deleted.
13673 if (CXXMethodDecl *MD = SMOR.getMethod())
13674 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13675}
13676
13678 llvm::APSInt Result;
13680 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13681 ExplicitSpec.setExpr(Converted.get());
13682 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13683 ExplicitSpec.setKind(Result.getBoolValue()
13686 return true;
13687 }
13689 return false;
13690}
13691
13694 if (!ExplicitExpr->isTypeDependent())
13696 return ES;
13697}
13698
13703 ComputingExceptionSpec CES(S, MD, Loc);
13704
13705 CXXRecordDecl *ClassDecl = MD->getParent();
13706
13707 // C++ [except.spec]p14:
13708 // An implicitly declared special member function (Clause 12) shall have an
13709 // exception-specification. [...]
13710 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13711 if (ClassDecl->isInvalidDecl())
13712 return Info.ExceptSpec;
13713
13714 // FIXME: If this diagnostic fires, we're probably missing a check for
13715 // attempting to resolve an exception specification before it's known
13716 // at a higher level.
13717 if (S.RequireCompleteType(MD->getLocation(),
13718 S.Context.getRecordType(ClassDecl),
13719 diag::err_exception_spec_incomplete_type))
13720 return Info.ExceptSpec;
13721
13722 // C++1z [except.spec]p7:
13723 // [Look for exceptions thrown by] a constructor selected [...] to
13724 // initialize a potentially constructed subobject,
13725 // C++1z [except.spec]p8:
13726 // The exception specification for an implicitly-declared destructor, or a
13727 // destructor without a noexcept-specifier, is potentially-throwing if and
13728 // only if any of the destructors for any of its potentially constructed
13729 // subojects is potentially throwing.
13730 // FIXME: We respect the first rule but ignore the "potentially constructed"
13731 // in the second rule to resolve a core issue (no number yet) that would have
13732 // us reject:
13733 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13734 // struct B : A {};
13735 // struct C : B { void f(); };
13736 // ... due to giving B::~B() a non-throwing exception specification.
13737 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13738 : Info.VisitAllBases);
13739
13740 return Info.ExceptSpec;
13741}
13742
13743namespace {
13744/// RAII object to register a special member as being currently declared.
13745struct DeclaringSpecialMember {
13746 Sema &S;
13748 Sema::ContextRAII SavedContext;
13749 bool WasAlreadyBeingDeclared;
13750
13751 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13752 : S(S), D(RD, CSM), SavedContext(S, RD) {
13753 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13754 if (WasAlreadyBeingDeclared)
13755 // This almost never happens, but if it does, ensure that our cache
13756 // doesn't contain a stale result.
13757 S.SpecialMemberCache.clear();
13758 else {
13759 // Register a note to be produced if we encounter an error while
13760 // declaring the special member.
13763 // FIXME: We don't have a location to use here. Using the class's
13764 // location maintains the fiction that we declare all special members
13765 // with the class, but (1) it's not clear that lying about that helps our
13766 // users understand what's going on, and (2) there may be outer contexts
13767 // on the stack (some of which are relevant) and printing them exposes
13768 // our lies.
13770 Ctx.Entity = RD;
13771 Ctx.SpecialMember = CSM;
13773 }
13774 }
13775 ~DeclaringSpecialMember() {
13776 if (!WasAlreadyBeingDeclared) {
13779 }
13780 }
13781
13782 /// Are we already trying to declare this special member?
13783 bool isAlreadyBeingDeclared() const {
13784 return WasAlreadyBeingDeclared;
13785 }
13786};
13787}
13788
13790 // Look up any existing declarations, but don't trigger declaration of all
13791 // implicit special members with this name.
13792 DeclarationName Name = FD->getDeclName();
13794 RedeclarationKind::ForExternalRedeclaration);
13795 for (auto *D : FD->getParent()->lookup(Name))
13796 if (auto *Acceptable = R.getAcceptableDecl(D))
13797 R.addDecl(Acceptable);
13798 R.resolveKind();
13800
13801 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13803}
13804
13805void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13806 QualType ResultTy,
13807 ArrayRef<QualType> Args) {
13808 // Build an exception specification pointing back at this constructor.
13810
13812 if (AS != LangAS::Default) {
13813 EPI.TypeQuals.addAddressSpace(AS);
13814 }
13815
13816 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13817 SpecialMem->setType(QT);
13818
13819 // During template instantiation of implicit special member functions we need
13820 // a reliable TypeSourceInfo for the function prototype in order to allow
13821 // functions to be substituted.
13823 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13824 TypeSourceInfo *TSI =
13826 SpecialMem->setTypeSourceInfo(TSI);
13827 }
13828}
13829
13831 CXXRecordDecl *ClassDecl) {
13832 // C++ [class.ctor]p5:
13833 // A default constructor for a class X is a constructor of class X
13834 // that can be called without an argument. If there is no
13835 // user-declared constructor for class X, a default constructor is
13836 // implicitly declared. An implicitly-declared default constructor
13837 // is an inline public member of its class.
13838 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13839 "Should not build implicit default constructor!");
13840
13841 DeclaringSpecialMember DSM(*this, ClassDecl,
13843 if (DSM.isAlreadyBeingDeclared())
13844 return nullptr;
13845
13847 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13848
13849 // Create the actual constructor declaration.
13850 CanQualType ClassType
13852 SourceLocation ClassLoc = ClassDecl->getLocation();
13853 DeclarationName Name
13855 DeclarationNameInfo NameInfo(Name, ClassLoc);
13857 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13858 /*TInfo=*/nullptr, ExplicitSpecifier(),
13859 getCurFPFeatures().isFPConstrained(),
13860 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13863 DefaultCon->setAccess(AS_public);
13864 DefaultCon->setDefaulted();
13865
13866 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13867
13868 if (getLangOpts().CUDA)
13870 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13871 /* ConstRHS */ false,
13872 /* Diagnose */ false);
13873
13874 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13875 // constructors is easy to compute.
13876 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13877
13878 // Note that we have declared this constructor.
13880
13881 Scope *S = getScopeForContext(ClassDecl);
13883
13884 if (ShouldDeleteSpecialMember(DefaultCon,
13886 SetDeclDeleted(DefaultCon, ClassLoc);
13887
13888 if (S)
13889 PushOnScopeChains(DefaultCon, S, false);
13890 ClassDecl->addDecl(DefaultCon);
13891
13892 return DefaultCon;
13893}
13894
13896 CXXConstructorDecl *Constructor) {
13897 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13898 !Constructor->doesThisDeclarationHaveABody() &&
13899 !Constructor->isDeleted()) &&
13900 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13901 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13902 return;
13903
13904 CXXRecordDecl *ClassDecl = Constructor->getParent();
13905 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13906 if (ClassDecl->isInvalidDecl()) {
13907 return;
13908 }
13909
13910 SynthesizedFunctionScope Scope(*this, Constructor);
13911
13912 // The exception specification is needed because we are defining the
13913 // function.
13914 ResolveExceptionSpec(CurrentLocation,
13915 Constructor->getType()->castAs<FunctionProtoType>());
13916 MarkVTableUsed(CurrentLocation, ClassDecl);
13917
13918 // Add a context note for diagnostics produced after this point.
13919 Scope.addContextNote(CurrentLocation);
13920
13921 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13922 Constructor->setInvalidDecl();
13923 return;
13924 }
13925
13926 SourceLocation Loc = Constructor->getEndLoc().isValid()
13927 ? Constructor->getEndLoc()
13928 : Constructor->getLocation();
13929 Constructor->setBody(new (Context) CompoundStmt(Loc));
13930 Constructor->markUsed(Context);
13931
13933 L->CompletedImplicitDefinition(Constructor);
13934 }
13935
13936 DiagnoseUninitializedFields(*this, Constructor);
13937}
13938
13940 // Perform any delayed checks on exception specifications.
13942}
13943
13944/// Find or create the fake constructor we synthesize to model constructing an
13945/// object of a derived class via a constructor of a base class.
13948 CXXConstructorDecl *BaseCtor,
13950 CXXRecordDecl *Derived = Shadow->getParent();
13951 SourceLocation UsingLoc = Shadow->getLocation();
13952
13953 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13954 // For now we use the name of the base class constructor as a member of the
13955 // derived class to indicate a (fake) inherited constructor name.
13956 DeclarationName Name = BaseCtor->getDeclName();
13957
13958 // Check to see if we already have a fake constructor for this inherited
13959 // constructor call.
13960 for (NamedDecl *Ctor : Derived->lookup(Name))
13961 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13962 ->getInheritedConstructor()
13963 .getConstructor(),
13964 BaseCtor))
13965 return cast<CXXConstructorDecl>(Ctor);
13966
13967 DeclarationNameInfo NameInfo(Name, UsingLoc);
13968 TypeSourceInfo *TInfo =
13969 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13970 FunctionProtoTypeLoc ProtoLoc =
13972
13973 // Check the inherited constructor is valid and find the list of base classes
13974 // from which it was inherited.
13975 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13976
13977 bool Constexpr = BaseCtor->isConstexpr() &&
13980 false, BaseCtor, &ICI);
13981
13983 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13984 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13985 /*isInline=*/true,
13986 /*isImplicitlyDeclared=*/true,
13988 InheritedConstructor(Shadow, BaseCtor),
13989 BaseCtor->getTrailingRequiresClause());
13990 if (Shadow->isInvalidDecl())
13991 DerivedCtor->setInvalidDecl();
13992
13993 // Build an unevaluated exception specification for this fake constructor.
13994 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13997 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13998 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13999 FPT->getParamTypes(), EPI));
14000
14001 // Build the parameter declarations.
14003 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14004 TypeSourceInfo *TInfo =
14007 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14008 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14009 PD->setScopeInfo(0, I);
14010 PD->setImplicit();
14011 // Ensure attributes are propagated onto parameters (this matters for
14012 // format, pass_object_size, ...).
14013 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14014 ParamDecls.push_back(PD);
14015 ProtoLoc.setParam(I, PD);
14016 }
14017
14018 // Set up the new constructor.
14019 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14020 DerivedCtor->setAccess(BaseCtor->getAccess());
14021 DerivedCtor->setParams(ParamDecls);
14022 Derived->addDecl(DerivedCtor);
14023
14024 if (ShouldDeleteSpecialMember(DerivedCtor,
14026 SetDeclDeleted(DerivedCtor, UsingLoc);
14027
14028 return DerivedCtor;
14029}
14030
14032 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14035 &ICI,
14036 /*Diagnose*/ true);
14037}
14038
14040 CXXConstructorDecl *Constructor) {
14041 CXXRecordDecl *ClassDecl = Constructor->getParent();
14042 assert(Constructor->getInheritedConstructor() &&
14043 !Constructor->doesThisDeclarationHaveABody() &&
14044 !Constructor->isDeleted());
14045 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14046 return;
14047
14048 // Initializations are performed "as if by a defaulted default constructor",
14049 // so enter the appropriate scope.
14050 SynthesizedFunctionScope Scope(*this, Constructor);
14051
14052 // The exception specification is needed because we are defining the
14053 // function.
14054 ResolveExceptionSpec(CurrentLocation,
14055 Constructor->getType()->castAs<FunctionProtoType>());
14056 MarkVTableUsed(CurrentLocation, ClassDecl);
14057
14058 // Add a context note for diagnostics produced after this point.
14059 Scope.addContextNote(CurrentLocation);
14060
14062 Constructor->getInheritedConstructor().getShadowDecl();
14063 CXXConstructorDecl *InheritedCtor =
14064 Constructor->getInheritedConstructor().getConstructor();
14065
14066 // [class.inhctor.init]p1:
14067 // initialization proceeds as if a defaulted default constructor is used to
14068 // initialize the D object and each base class subobject from which the
14069 // constructor was inherited
14070
14071 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14072 CXXRecordDecl *RD = Shadow->getParent();
14073 SourceLocation InitLoc = Shadow->getLocation();
14074
14075 // Build explicit initializers for all base classes from which the
14076 // constructor was inherited.
14078 for (bool VBase : {false, true}) {
14079 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14080 if (B.isVirtual() != VBase)
14081 continue;
14082
14083 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14084 if (!BaseRD)
14085 continue;
14086
14087 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14088 if (!BaseCtor.first)
14089 continue;
14090
14091 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14093 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14094
14095 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14096 Inits.push_back(new (Context) CXXCtorInitializer(
14097 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14098 SourceLocation()));
14099 }
14100 }
14101
14102 // We now proceed as if for a defaulted default constructor, with the relevant
14103 // initializers replaced.
14104
14105 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14106 Constructor->setInvalidDecl();
14107 return;
14108 }
14109
14110 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14111 Constructor->markUsed(Context);
14112
14114 L->CompletedImplicitDefinition(Constructor);
14115 }
14116
14117 DiagnoseUninitializedFields(*this, Constructor);
14118}
14119
14121 // C++ [class.dtor]p2:
14122 // If a class has no user-declared destructor, a destructor is
14123 // declared implicitly. An implicitly-declared destructor is an
14124 // inline public member of its class.
14125 assert(ClassDecl->needsImplicitDestructor());
14126
14127 DeclaringSpecialMember DSM(*this, ClassDecl,
14129 if (DSM.isAlreadyBeingDeclared())
14130 return nullptr;
14131
14133 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14134
14135 // Create the actual destructor declaration.
14136 CanQualType ClassType
14138 SourceLocation ClassLoc = ClassDecl->getLocation();
14139 DeclarationName Name
14141 DeclarationNameInfo NameInfo(Name, ClassLoc);
14143 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14144 getCurFPFeatures().isFPConstrained(),
14145 /*isInline=*/true,
14146 /*isImplicitlyDeclared=*/true,
14149 Destructor->setAccess(AS_public);
14150 Destructor->setDefaulted();
14151
14152 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14153
14154 if (getLangOpts().CUDA)
14157 /* ConstRHS */ false,
14158 /* Diagnose */ false);
14159
14160 // We don't need to use SpecialMemberIsTrivial here; triviality for
14161 // destructors is easy to compute.
14162 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14163 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14164 ClassDecl->hasTrivialDestructorForCall());
14165
14166 // Note that we have declared this destructor.
14168
14169 Scope *S = getScopeForContext(ClassDecl);
14171
14172 // We can't check whether an implicit destructor is deleted before we complete
14173 // the definition of the class, because its validity depends on the alignment
14174 // of the class. We'll check this from ActOnFields once the class is complete.
14175 if (ClassDecl->isCompleteDefinition() &&
14177 SetDeclDeleted(Destructor, ClassLoc);
14178
14179 // Introduce this destructor into its scope.
14180 if (S)
14181 PushOnScopeChains(Destructor, S, false);
14182 ClassDecl->addDecl(Destructor);
14183
14184 return Destructor;
14185}
14186
14189 assert((Destructor->isDefaulted() &&
14190 !Destructor->doesThisDeclarationHaveABody() &&
14191 !Destructor->isDeleted()) &&
14192 "DefineImplicitDestructor - call it for implicit default dtor");
14193 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14194 return;
14195
14196 CXXRecordDecl *ClassDecl = Destructor->getParent();
14197 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14198
14200
14201 // The exception specification is needed because we are defining the
14202 // function.
14203 ResolveExceptionSpec(CurrentLocation,
14204 Destructor->getType()->castAs<FunctionProtoType>());
14205 MarkVTableUsed(CurrentLocation, ClassDecl);
14206
14207 // Add a context note for diagnostics produced after this point.
14208 Scope.addContextNote(CurrentLocation);
14209
14211 Destructor->getParent());
14212
14214 Destructor->setInvalidDecl();
14215 return;
14216 }
14217
14218 SourceLocation Loc = Destructor->getEndLoc().isValid()
14219 ? Destructor->getEndLoc()
14220 : Destructor->getLocation();
14221 Destructor->setBody(new (Context) CompoundStmt(Loc));
14222 Destructor->markUsed(Context);
14223
14225 L->CompletedImplicitDefinition(Destructor);
14226 }
14227}
14228
14231 if (Destructor->isInvalidDecl())
14232 return;
14233
14234 CXXRecordDecl *ClassDecl = Destructor->getParent();
14236 "implicit complete dtors unneeded outside MS ABI");
14237 assert(ClassDecl->getNumVBases() > 0 &&
14238 "complete dtor only exists for classes with vbases");
14239
14241
14242 // Add a context note for diagnostics produced after this point.
14243 Scope.addContextNote(CurrentLocation);
14244
14245 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14246}
14247
14249 // If the context is an invalid C++ class, just suppress these checks.
14250 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14251 if (Record->isInvalidDecl()) {
14254 return;
14255 }
14257 }
14258}
14259
14262
14263 if (!DelayedDllExportMemberFunctions.empty()) {
14265 std::swap(DelayedDllExportMemberFunctions, WorkList);
14266 for (CXXMethodDecl *M : WorkList) {
14267 DefineDefaultedFunction(*this, M, M->getLocation());
14268
14269 // Pass the method to the consumer to get emitted. This is not necessary
14270 // for explicit instantiation definitions, as they will get emitted
14271 // anyway.
14272 if (M->getParent()->getTemplateSpecializationKind() !=
14275 }
14276 }
14277}
14278
14280 if (!DelayedDllExportClasses.empty()) {
14281 // Calling ReferenceDllExportedMembers might cause the current function to
14282 // be called again, so use a local copy of DelayedDllExportClasses.
14284 std::swap(DelayedDllExportClasses, WorkList);
14285 for (CXXRecordDecl *Class : WorkList)
14287 }
14288}
14289
14291 assert(getLangOpts().CPlusPlus11 &&
14292 "adjusting dtor exception specs was introduced in c++11");
14293
14294 if (Destructor->isDependentContext())
14295 return;
14296
14297 // C++11 [class.dtor]p3:
14298 // A declaration of a destructor that does not have an exception-
14299 // specification is implicitly considered to have the same exception-
14300 // specification as an implicit declaration.
14301 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14302 if (DtorType->hasExceptionSpec())
14303 return;
14304
14305 // Replace the destructor's type, building off the existing one. Fortunately,
14306 // the only thing of interest in the destructor type is its extended info.
14307 // The return and arguments are fixed.
14308 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14311 Destructor->setType(
14312 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14313
14314 // FIXME: If the destructor has a body that could throw, and the newly created
14315 // spec doesn't allow exceptions, we should emit a warning, because this
14316 // change in behavior can break conforming C++03 programs at runtime.
14317 // However, we don't have a body or an exception specification yet, so it
14318 // needs to be done somewhere else.
14319}
14320
14321namespace {
14322/// An abstract base class for all helper classes used in building the
14323// copy/move operators. These classes serve as factory functions and help us
14324// avoid using the same Expr* in the AST twice.
14325class ExprBuilder {
14326 ExprBuilder(const ExprBuilder&) = delete;
14327 ExprBuilder &operator=(const ExprBuilder&) = delete;
14328
14329protected:
14330 static Expr *assertNotNull(Expr *E) {
14331 assert(E && "Expression construction must not fail.");
14332 return E;
14333 }
14334
14335public:
14336 ExprBuilder() {}
14337 virtual ~ExprBuilder() {}
14338
14339 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14340};
14341
14342class RefBuilder: public ExprBuilder {
14343 VarDecl *Var;
14344 QualType VarType;
14345
14346public:
14347 Expr *build(Sema &S, SourceLocation Loc) const override {
14348 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14349 }
14350
14351 RefBuilder(VarDecl *Var, QualType VarType)
14352 : Var(Var), VarType(VarType) {}
14353};
14354
14355class ThisBuilder: public ExprBuilder {
14356public:
14357 Expr *build(Sema &S, SourceLocation Loc) const override {
14358 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14359 }
14360};
14361
14362class CastBuilder: public ExprBuilder {
14363 const ExprBuilder &Builder;
14364 QualType Type;
14366 const CXXCastPath &Path;
14367
14368public:
14369 Expr *build(Sema &S, SourceLocation Loc) const override {
14370 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14371 CK_UncheckedDerivedToBase, Kind,
14372 &Path).get());
14373 }
14374
14375 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14376 const CXXCastPath &Path)
14377 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14378};
14379
14380class DerefBuilder: public ExprBuilder {
14381 const ExprBuilder &Builder;
14382
14383public:
14384 Expr *build(Sema &S, SourceLocation Loc) const override {
14385 return assertNotNull(
14386 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14387 }
14388
14389 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14390};
14391
14392class MemberBuilder: public ExprBuilder {
14393 const ExprBuilder &Builder;
14394 QualType Type;
14395 CXXScopeSpec SS;
14396 bool IsArrow;
14397 LookupResult &MemberLookup;
14398
14399public:
14400 Expr *build(Sema &S, SourceLocation Loc) const override {
14401 return assertNotNull(S.BuildMemberReferenceExpr(
14402 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14403 nullptr, MemberLookup, nullptr, nullptr).get());
14404 }
14405
14406 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14407 LookupResult &MemberLookup)
14408 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14409 MemberLookup(MemberLookup) {}
14410};
14411
14412class MoveCastBuilder: public ExprBuilder {
14413 const ExprBuilder &Builder;
14414
14415public:
14416 Expr *build(Sema &S, SourceLocation Loc) const override {
14417 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14418 }
14419
14420 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14421};
14422
14423class LvalueConvBuilder: public ExprBuilder {
14424 const ExprBuilder &Builder;
14425
14426public:
14427 Expr *build(Sema &S, SourceLocation Loc) const override {
14428 return assertNotNull(
14429 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14430 }
14431
14432 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14433};
14434
14435class SubscriptBuilder: public ExprBuilder {
14436 const ExprBuilder &Base;
14437 const ExprBuilder &Index;
14438
14439public:
14440 Expr *build(Sema &S, SourceLocation Loc) const override {
14441 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14442 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14443 }
14444
14445 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14446 : Base(Base), Index(Index) {}
14447};
14448
14449} // end anonymous namespace
14450
14451/// When generating a defaulted copy or move assignment operator, if a field
14452/// should be copied with __builtin_memcpy rather than via explicit assignments,
14453/// do so. This optimization only applies for arrays of scalars, and for arrays
14454/// of class type where the selected copy/move-assignment operator is trivial.
14455static StmtResult
14457 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14458 // Compute the size of the memory buffer to be copied.
14459 QualType SizeType = S.Context.getSizeType();
14460 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14462
14463 // Take the address of the field references for "from" and "to". We
14464 // directly construct UnaryOperators here because semantic analysis
14465 // does not permit us to take the address of an xvalue.
14466 Expr *From = FromB.build(S, Loc);
14467 From = UnaryOperator::Create(
14468 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14470 Expr *To = ToB.build(S, Loc);
14472 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14474
14475 const Type *E = T->getBaseElementTypeUnsafe();
14476 bool NeedsCollectableMemCpy =
14477 E->isRecordType() &&
14478 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14479
14480 // Create a reference to the __builtin_objc_memmove_collectable function
14481 StringRef MemCpyName = NeedsCollectableMemCpy ?
14482 "__builtin_objc_memmove_collectable" :
14483 "__builtin_memcpy";
14484 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14486 S.LookupName(R, S.TUScope, true);
14487
14488 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14489 if (!MemCpy)
14490 // Something went horribly wrong earlier, and we will have complained
14491 // about it.
14492 return StmtError();
14493
14494 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14495 VK_PRValue, Loc, nullptr);
14496 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14497
14498 Expr *CallArgs[] = {
14499 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14500 };
14501 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14502 Loc, CallArgs, Loc);
14503
14504 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14505 return Call.getAs<Stmt>();
14506}
14507
14508/// Builds a statement that copies/moves the given entity from \p From to
14509/// \c To.
14510///
14511/// This routine is used to copy/move the members of a class with an
14512/// implicitly-declared copy/move assignment operator. When the entities being
14513/// copied are arrays, this routine builds for loops to copy them.
14514///
14515/// \param S The Sema object used for type-checking.
14516///
14517/// \param Loc The location where the implicit copy/move is being generated.
14518///
14519/// \param T The type of the expressions being copied/moved. Both expressions
14520/// must have this type.
14521///
14522/// \param To The expression we are copying/moving to.
14523///
14524/// \param From The expression we are copying/moving from.
14525///
14526/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14527/// Otherwise, it's a non-static member subobject.
14528///
14529/// \param Copying Whether we're copying or moving.
14530///
14531/// \param Depth Internal parameter recording the depth of the recursion.
14532///
14533/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14534/// if a memcpy should be used instead.
14535static StmtResult
14537 const ExprBuilder &To, const ExprBuilder &From,
14538 bool CopyingBaseSubobject, bool Copying,
14539 unsigned Depth = 0) {
14540 // C++11 [class.copy]p28:
14541 // Each subobject is assigned in the manner appropriate to its type:
14542 //
14543 // - if the subobject is of class type, as if by a call to operator= with
14544 // the subobject as the object expression and the corresponding
14545 // subobject of x as a single function argument (as if by explicit
14546 // qualification; that is, ignoring any possible virtual overriding
14547 // functions in more derived classes);
14548 //
14549 // C++03 [class.copy]p13:
14550 // - if the subobject is of class type, the copy assignment operator for
14551 // the class is used (as if by explicit qualification; that is,
14552 // ignoring any possible virtual overriding functions in more derived
14553 // classes);
14554 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14555 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14556
14557 // Look for operator=.
14558 DeclarationName Name
14560 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14561 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14562
14563 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14564 // operator.
14565 if (!S.getLangOpts().CPlusPlus11) {
14566 LookupResult::Filter F = OpLookup.makeFilter();
14567 while (F.hasNext()) {
14568 NamedDecl *D = F.next();
14569 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14570 if (Method->isCopyAssignmentOperator() ||
14571 (!Copying && Method->isMoveAssignmentOperator()))
14572 continue;
14573
14574 F.erase();
14575 }
14576 F.done();
14577 }
14578
14579 // Suppress the protected check (C++ [class.protected]) for each of the
14580 // assignment operators we found. This strange dance is required when
14581 // we're assigning via a base classes's copy-assignment operator. To
14582 // ensure that we're getting the right base class subobject (without
14583 // ambiguities), we need to cast "this" to that subobject type; to
14584 // ensure that we don't go through the virtual call mechanism, we need
14585 // to qualify the operator= name with the base class (see below). However,
14586 // this means that if the base class has a protected copy assignment
14587 // operator, the protected member access check will fail. So, we
14588 // rewrite "protected" access to "public" access in this case, since we
14589 // know by construction that we're calling from a derived class.
14590 if (CopyingBaseSubobject) {
14591 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14592 L != LEnd; ++L) {
14593 if (L.getAccess() == AS_protected)
14594 L.setAccess(AS_public);
14595 }
14596 }
14597
14598 // Create the nested-name-specifier that will be used to qualify the
14599 // reference to operator=; this is required to suppress the virtual
14600 // call mechanism.
14601 CXXScopeSpec SS;
14602 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14603 SS.MakeTrivial(S.Context,
14604 NestedNameSpecifier::Create(S.Context, nullptr, false,
14605 CanonicalT),
14606 Loc);
14607
14608 // Create the reference to operator=.
14609 ExprResult OpEqualRef
14610 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14611 SS, /*TemplateKWLoc=*/SourceLocation(),
14612 /*FirstQualifierInScope=*/nullptr,
14613 OpLookup,
14614 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14615 /*SuppressQualifierCheck=*/true);
14616 if (OpEqualRef.isInvalid())
14617 return StmtError();
14618
14619 // Build the call to the assignment operator.
14620
14621 Expr *FromInst = From.build(S, Loc);
14622 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14623 OpEqualRef.getAs<Expr>(),
14624 Loc, FromInst, Loc);
14625 if (Call.isInvalid())
14626 return StmtError();
14627
14628 // If we built a call to a trivial 'operator=' while copying an array,
14629 // bail out. We'll replace the whole shebang with a memcpy.
14630 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14631 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14632 return StmtResult((Stmt*)nullptr);
14633
14634 // Convert to an expression-statement, and clean up any produced
14635 // temporaries.
14636 return S.ActOnExprStmt(Call);
14637 }
14638
14639 // - if the subobject is of scalar type, the built-in assignment
14640 // operator is used.
14642 if (!ArrayTy) {
14643 ExprResult Assignment = S.CreateBuiltinBinOp(
14644 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14645 if (Assignment.isInvalid())
14646 return StmtError();
14647 return S.ActOnExprStmt(Assignment);
14648 }
14649
14650 // - if the subobject is an array, each element is assigned, in the
14651 // manner appropriate to the element type;
14652
14653 // Construct a loop over the array bounds, e.g.,
14654 //
14655 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14656 //
14657 // that will copy each of the array elements.
14658 QualType SizeType = S.Context.getSizeType();
14659
14660 // Create the iteration variable.
14661 IdentifierInfo *IterationVarName = nullptr;
14662 {
14663 SmallString<8> Str;
14664 llvm::raw_svector_ostream OS(Str);
14665 OS << "__i" << Depth;
14666 IterationVarName = &S.Context.Idents.get(OS.str());
14667 }
14668 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14669 IterationVarName, SizeType,
14671 SC_None);
14672
14673 // Initialize the iteration variable to zero.
14674 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14675 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14676
14677 // Creates a reference to the iteration variable.
14678 RefBuilder IterationVarRef(IterationVar, SizeType);
14679 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14680
14681 // Create the DeclStmt that holds the iteration variable.
14682 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14683
14684 // Subscript the "from" and "to" expressions with the iteration variable.
14685 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14686 MoveCastBuilder FromIndexMove(FromIndexCopy);
14687 const ExprBuilder *FromIndex;
14688 if (Copying)
14689 FromIndex = &FromIndexCopy;
14690 else
14691 FromIndex = &FromIndexMove;
14692
14693 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14694
14695 // Build the copy/move for an individual element of the array.
14698 ToIndex, *FromIndex, CopyingBaseSubobject,
14699 Copying, Depth + 1);
14700 // Bail out if copying fails or if we determined that we should use memcpy.
14701 if (Copy.isInvalid() || !Copy.get())
14702 return Copy;
14703
14704 // Create the comparison against the array bound.
14705 llvm::APInt Upper
14706 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14707 Expr *Comparison = BinaryOperator::Create(
14708 S.Context, IterationVarRefRVal.build(S, Loc),
14709 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14712
14713 // Create the pre-increment of the iteration variable. We can determine
14714 // whether the increment will overflow based on the value of the array
14715 // bound.
14716 Expr *Increment = UnaryOperator::Create(
14717 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14718 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14719
14720 // Construct the loop that copies all elements of this array.
14721 return S.ActOnForStmt(
14722 Loc, Loc, InitStmt,
14723 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14724 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14725}
14726
14727static StmtResult
14729 const ExprBuilder &To, const ExprBuilder &From,
14730 bool CopyingBaseSubobject, bool Copying) {
14731 // Maybe we should use a memcpy?
14732 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14733 T.isTriviallyCopyableType(S.Context))
14734 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14735
14737 CopyingBaseSubobject,
14738 Copying, 0));
14739
14740 // If we ended up picking a trivial assignment operator for an array of a
14741 // non-trivially-copyable class type, just emit a memcpy.
14742 if (!Result.isInvalid() && !Result.get())
14743 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14744
14745 return Result;
14746}
14747
14749 // Note: The following rules are largely analoguous to the copy
14750 // constructor rules. Note that virtual bases are not taken into account
14751 // for determining the argument type of the operator. Note also that
14752 // operators taking an object instead of a reference are allowed.
14753 assert(ClassDecl->needsImplicitCopyAssignment());
14754
14755 DeclaringSpecialMember DSM(*this, ClassDecl,
14757 if (DSM.isAlreadyBeingDeclared())
14758 return nullptr;
14759
14760 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14762 ArgType, nullptr);
14764 if (AS != LangAS::Default)
14765 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14766 QualType RetType = Context.getLValueReferenceType(ArgType);
14767 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14768 if (Const)
14769 ArgType = ArgType.withConst();
14770
14771 ArgType = Context.getLValueReferenceType(ArgType);
14772
14774 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14775
14776 // An implicitly-declared copy assignment operator is an inline public
14777 // member of its class.
14779 SourceLocation ClassLoc = ClassDecl->getLocation();
14780 DeclarationNameInfo NameInfo(Name, ClassLoc);
14782 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14783 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14784 getCurFPFeatures().isFPConstrained(),
14785 /*isInline=*/true,
14787 SourceLocation());
14788 CopyAssignment->setAccess(AS_public);
14789 CopyAssignment->setDefaulted();
14790 CopyAssignment->setImplicit();
14791
14792 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14793
14794 if (getLangOpts().CUDA)
14797 /* ConstRHS */ Const,
14798 /* Diagnose */ false);
14799
14800 // Add the parameter to the operator.
14802 ClassLoc, ClassLoc,
14803 /*Id=*/nullptr, ArgType,
14804 /*TInfo=*/nullptr, SC_None,
14805 nullptr);
14806 CopyAssignment->setParams(FromParam);
14807
14808 CopyAssignment->setTrivial(
14812 : ClassDecl->hasTrivialCopyAssignment());
14813
14814 // Note that we have added this copy-assignment operator.
14816
14817 Scope *S = getScopeForContext(ClassDecl);
14819
14823 SetDeclDeleted(CopyAssignment, ClassLoc);
14824 }
14825
14826 if (S)
14828 ClassDecl->addDecl(CopyAssignment);
14829
14830 return CopyAssignment;
14831}
14832
14833/// Diagnose an implicit copy operation for a class which is odr-used, but
14834/// which is deprecated because the class has a user-declared copy constructor,
14835/// copy assignment operator, or destructor.
14837 assert(CopyOp->isImplicit());
14838
14839 CXXRecordDecl *RD = CopyOp->getParent();
14840 CXXMethodDecl *UserDeclaredOperation = nullptr;
14841
14842 if (RD->hasUserDeclaredDestructor()) {
14843 UserDeclaredOperation = RD->getDestructor();
14844 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14846 // Find any user-declared copy constructor.
14847 for (auto *I : RD->ctors()) {
14848 if (I->isCopyConstructor()) {
14849 UserDeclaredOperation = I;
14850 break;
14851 }
14852 }
14853 assert(UserDeclaredOperation);
14854 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14856 // Find any user-declared move assignment operator.
14857 for (auto *I : RD->methods()) {
14858 if (I->isCopyAssignmentOperator()) {
14859 UserDeclaredOperation = I;
14860 break;
14861 }
14862 }
14863 assert(UserDeclaredOperation);
14864 }
14865
14866 if (UserDeclaredOperation) {
14867 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14868 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14869 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14870 unsigned DiagID =
14871 (UDOIsUserProvided && UDOIsDestructor)
14872 ? diag::warn_deprecated_copy_with_user_provided_dtor
14873 : (UDOIsUserProvided && !UDOIsDestructor)
14874 ? diag::warn_deprecated_copy_with_user_provided_copy
14875 : (!UDOIsUserProvided && UDOIsDestructor)
14876 ? diag::warn_deprecated_copy_with_dtor
14877 : diag::warn_deprecated_copy;
14878 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14879 << RD << IsCopyAssignment;
14880 }
14881}
14882
14884 CXXMethodDecl *CopyAssignOperator) {
14885 assert((CopyAssignOperator->isDefaulted() &&
14886 CopyAssignOperator->isOverloadedOperator() &&
14887 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14888 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14889 !CopyAssignOperator->isDeleted()) &&
14890 "DefineImplicitCopyAssignment called for wrong function");
14891 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14892 return;
14893
14894 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14895 if (ClassDecl->isInvalidDecl()) {
14896 CopyAssignOperator->setInvalidDecl();
14897 return;
14898 }
14899
14900 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14901
14902 // The exception specification is needed because we are defining the
14903 // function.
14904 ResolveExceptionSpec(CurrentLocation,
14905 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14906
14907 // Add a context note for diagnostics produced after this point.
14908 Scope.addContextNote(CurrentLocation);
14909
14910 // C++11 [class.copy]p18:
14911 // The [definition of an implicitly declared copy assignment operator] is
14912 // deprecated if the class has a user-declared copy constructor or a
14913 // user-declared destructor.
14914 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14915 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14916
14917 // C++0x [class.copy]p30:
14918 // The implicitly-defined or explicitly-defaulted copy assignment operator
14919 // for a non-union class X performs memberwise copy assignment of its
14920 // subobjects. The direct base classes of X are assigned first, in the
14921 // order of their declaration in the base-specifier-list, and then the
14922 // immediate non-static data members of X are assigned, in the order in
14923 // which they were declared in the class definition.
14924
14925 // The statements that form the synthesized function body.
14926 SmallVector<Stmt*, 8> Statements;
14927
14928 // The parameter for the "other" object, which we are copying from.
14929 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
14930 Qualifiers OtherQuals = Other->getType().getQualifiers();
14931 QualType OtherRefType = Other->getType();
14932 if (OtherRefType->isLValueReferenceType()) {
14933 OtherRefType = OtherRefType->getPointeeType();
14934 OtherQuals = OtherRefType.getQualifiers();
14935 }
14936
14937 // Our location for everything implicitly-generated.
14938 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14939 ? CopyAssignOperator->getEndLoc()
14940 : CopyAssignOperator->getLocation();
14941
14942 // Builds a DeclRefExpr for the "other" object.
14943 RefBuilder OtherRef(Other, OtherRefType);
14944
14945 // Builds the function object parameter.
14946 std::optional<ThisBuilder> This;
14947 std::optional<DerefBuilder> DerefThis;
14948 std::optional<RefBuilder> ExplicitObject;
14949 bool IsArrow = false;
14950 QualType ObjectType;
14951 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
14952 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
14953 if (ObjectType->isReferenceType())
14954 ObjectType = ObjectType->getPointeeType();
14955 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
14956 } else {
14957 ObjectType = getCurrentThisType();
14958 This.emplace();
14959 DerefThis.emplace(*This);
14960 IsArrow = !LangOpts.HLSL;
14961 }
14962 ExprBuilder &ObjectParameter =
14963 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14964 : static_cast<ExprBuilder &>(*This);
14965
14966 // Assign base classes.
14967 bool Invalid = false;
14968 for (auto &Base : ClassDecl->bases()) {
14969 // Form the assignment:
14970 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14971 QualType BaseType = Base.getType().getUnqualifiedType();
14972 if (!BaseType->isRecordType()) {
14973 Invalid = true;
14974 continue;
14975 }
14976
14977 CXXCastPath BasePath;
14978 BasePath.push_back(&Base);
14979
14980 // Construct the "from" expression, which is an implicit cast to the
14981 // appropriately-qualified base type.
14982 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14983 VK_LValue, BasePath);
14984
14985 // Dereference "this".
14986 CastBuilder To(
14987 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14988 : static_cast<ExprBuilder &>(*DerefThis),
14989 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
14990 VK_LValue, BasePath);
14991
14992 // Build the copy.
14993 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14994 To, From,
14995 /*CopyingBaseSubobject=*/true,
14996 /*Copying=*/true);
14997 if (Copy.isInvalid()) {
14998 CopyAssignOperator->setInvalidDecl();
14999 return;
15000 }
15001
15002 // Success! Record the copy.
15003 Statements.push_back(Copy.getAs<Expr>());
15004 }
15005
15006 // Assign non-static members.
15007 for (auto *Field : ClassDecl->fields()) {
15008 // FIXME: We should form some kind of AST representation for the implied
15009 // memcpy in a union copy operation.
15010 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15011 continue;
15012
15013 if (Field->isInvalidDecl()) {
15014 Invalid = true;
15015 continue;
15016 }
15017
15018 // Check for members of reference type; we can't copy those.
15019 if (Field->getType()->isReferenceType()) {
15020 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15021 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15022 Diag(Field->getLocation(), diag::note_declared_at);
15023 Invalid = true;
15024 continue;
15025 }
15026
15027 // Check for members of const-qualified, non-class type.
15028 QualType BaseType = Context.getBaseElementType(Field->getType());
15029 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15030 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15031 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15032 Diag(Field->getLocation(), diag::note_declared_at);
15033 Invalid = true;
15034 continue;
15035 }
15036
15037 // Suppress assigning zero-width bitfields.
15038 if (Field->isZeroLengthBitField(Context))
15039 continue;
15040
15041 QualType FieldType = Field->getType().getNonReferenceType();
15042 if (FieldType->isIncompleteArrayType()) {
15043 assert(ClassDecl->hasFlexibleArrayMember() &&
15044 "Incomplete array type is not valid");
15045 continue;
15046 }
15047
15048 // Build references to the field in the object we're copying from and to.
15049 CXXScopeSpec SS; // Intentionally empty
15050 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15052 MemberLookup.addDecl(Field);
15053 MemberLookup.resolveKind();
15054
15055 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15056 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15057 // Build the copy of this field.
15058 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15059 To, From,
15060 /*CopyingBaseSubobject=*/false,
15061 /*Copying=*/true);
15062 if (Copy.isInvalid()) {
15063 CopyAssignOperator->setInvalidDecl();
15064 return;
15065 }
15066
15067 // Success! Record the copy.
15068 Statements.push_back(Copy.getAs<Stmt>());
15069 }
15070
15071 if (!Invalid) {
15072 // Add a "return *this;"
15073 Expr *ThisExpr =
15074 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15075 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15076 : static_cast<ExprBuilder &>(*DerefThis))
15077 .build(*this, Loc);
15078 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15079 if (Return.isInvalid())
15080 Invalid = true;
15081 else
15082 Statements.push_back(Return.getAs<Stmt>());
15083 }
15084
15085 if (Invalid) {
15086 CopyAssignOperator->setInvalidDecl();
15087 return;
15088 }
15089
15090 StmtResult Body;
15091 {
15092 CompoundScopeRAII CompoundScope(*this);
15093 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15094 /*isStmtExpr=*/false);
15095 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15096 }
15097 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15098 CopyAssignOperator->markUsed(Context);
15099
15101 L->CompletedImplicitDefinition(CopyAssignOperator);
15102 }
15103}
15104
15106 assert(ClassDecl->needsImplicitMoveAssignment());
15107
15108 DeclaringSpecialMember DSM(*this, ClassDecl,
15110 if (DSM.isAlreadyBeingDeclared())
15111 return nullptr;
15112
15113 // Note: The following rules are largely analoguous to the move
15114 // constructor rules.
15115
15116 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15118 ArgType, nullptr);
15120 if (AS != LangAS::Default)
15121 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15122 QualType RetType = Context.getLValueReferenceType(ArgType);
15123 ArgType = Context.getRValueReferenceType(ArgType);
15124
15126 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15127
15128 // An implicitly-declared move assignment operator is an inline public
15129 // member of its class.
15131 SourceLocation ClassLoc = ClassDecl->getLocation();
15132 DeclarationNameInfo NameInfo(Name, ClassLoc);
15134 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15135 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15136 getCurFPFeatures().isFPConstrained(),
15137 /*isInline=*/true,
15139 SourceLocation());
15140 MoveAssignment->setAccess(AS_public);
15141 MoveAssignment->setDefaulted();
15142 MoveAssignment->setImplicit();
15143
15144 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15145
15146 if (getLangOpts().CUDA)
15149 /* ConstRHS */ false,
15150 /* Diagnose */ false);
15151
15152 // Add the parameter to the operator.
15154 ClassLoc, ClassLoc,
15155 /*Id=*/nullptr, ArgType,
15156 /*TInfo=*/nullptr, SC_None,
15157 nullptr);
15158 MoveAssignment->setParams(FromParam);
15159
15160 MoveAssignment->setTrivial(
15164 : ClassDecl->hasTrivialMoveAssignment());
15165
15166 // Note that we have added this copy-assignment operator.
15168
15169 Scope *S = getScopeForContext(ClassDecl);
15171
15175 SetDeclDeleted(MoveAssignment, ClassLoc);
15176 }
15177
15178 if (S)
15180 ClassDecl->addDecl(MoveAssignment);
15181
15182 return MoveAssignment;
15183}
15184
15185/// Check if we're implicitly defining a move assignment operator for a class
15186/// with virtual bases. Such a move assignment might move-assign the virtual
15187/// base multiple times.
15189 SourceLocation CurrentLocation) {
15190 assert(!Class->isDependentContext() && "should not define dependent move");
15191
15192 // Only a virtual base could get implicitly move-assigned multiple times.
15193 // Only a non-trivial move assignment can observe this. We only want to
15194 // diagnose if we implicitly define an assignment operator that assigns
15195 // two base classes, both of which move-assign the same virtual base.
15196 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15197 Class->getNumBases() < 2)
15198 return;
15199
15201 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15202 VBaseMap VBases;
15203
15204 for (auto &BI : Class->bases()) {
15205 Worklist.push_back(&BI);
15206 while (!Worklist.empty()) {
15207 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15208 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15209
15210 // If the base has no non-trivial move assignment operators,
15211 // we don't care about moves from it.
15212 if (!Base->hasNonTrivialMoveAssignment())
15213 continue;
15214
15215 // If there's nothing virtual here, skip it.
15216 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15217 continue;
15218
15219 // If we're not actually going to call a move assignment for this base,
15220 // or the selected move assignment is trivial, skip it.
15223 /*ConstArg*/ false, /*VolatileArg*/ false,
15224 /*RValueThis*/ true, /*ConstThis*/ false,
15225 /*VolatileThis*/ false);
15226 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15228 continue;
15229
15230 if (BaseSpec->isVirtual()) {
15231 // We're going to move-assign this virtual base, and its move
15232 // assignment operator is not trivial. If this can happen for
15233 // multiple distinct direct bases of Class, diagnose it. (If it
15234 // only happens in one base, we'll diagnose it when synthesizing
15235 // that base class's move assignment operator.)
15236 CXXBaseSpecifier *&Existing =
15237 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15238 .first->second;
15239 if (Existing && Existing != &BI) {
15240 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15241 << Class << Base;
15242 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15243 << (Base->getCanonicalDecl() ==
15245 << Base << Existing->getType() << Existing->getSourceRange();
15246 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15247 << (Base->getCanonicalDecl() ==
15248 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15249 << Base << BI.getType() << BaseSpec->getSourceRange();
15250
15251 // Only diagnose each vbase once.
15252 Existing = nullptr;
15253 }
15254 } else {
15255 // Only walk over bases that have defaulted move assignment operators.
15256 // We assume that any user-provided move assignment operator handles
15257 // the multiple-moves-of-vbase case itself somehow.
15258 if (!SMOR.getMethod()->isDefaulted())
15259 continue;
15260
15261 // We're going to move the base classes of Base. Add them to the list.
15262 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15263 }
15264 }
15265 }
15266}
15267
15269 CXXMethodDecl *MoveAssignOperator) {
15270 assert((MoveAssignOperator->isDefaulted() &&
15271 MoveAssignOperator->isOverloadedOperator() &&
15272 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15273 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15274 !MoveAssignOperator->isDeleted()) &&
15275 "DefineImplicitMoveAssignment called for wrong function");
15276 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15277 return;
15278
15279 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15280 if (ClassDecl->isInvalidDecl()) {
15281 MoveAssignOperator->setInvalidDecl();
15282 return;
15283 }
15284
15285 // C++0x [class.copy]p28:
15286 // The implicitly-defined or move assignment operator for a non-union class
15287 // X performs memberwise move assignment of its subobjects. The direct base
15288 // classes of X are assigned first, in the order of their declaration in the
15289 // base-specifier-list, and then the immediate non-static data members of X
15290 // are assigned, in the order in which they were declared in the class
15291 // definition.
15292
15293 // Issue a warning if our implicit move assignment operator will move
15294 // from a virtual base more than once.
15295 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15296
15297 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15298
15299 // The exception specification is needed because we are defining the
15300 // function.
15301 ResolveExceptionSpec(CurrentLocation,
15302 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15303
15304 // Add a context note for diagnostics produced after this point.
15305 Scope.addContextNote(CurrentLocation);
15306
15307 // The statements that form the synthesized function body.
15308 SmallVector<Stmt*, 8> Statements;
15309
15310 // The parameter for the "other" object, which we are move from.
15311 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15312 QualType OtherRefType =
15313 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15314
15315 // Our location for everything implicitly-generated.
15316 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15317 ? MoveAssignOperator->getEndLoc()
15318 : MoveAssignOperator->getLocation();
15319
15320 // Builds a reference to the "other" object.
15321 RefBuilder OtherRef(Other, OtherRefType);
15322 // Cast to rvalue.
15323 MoveCastBuilder MoveOther(OtherRef);
15324
15325 // Builds the function object parameter.
15326 std::optional<ThisBuilder> This;
15327 std::optional<DerefBuilder> DerefThis;
15328 std::optional<RefBuilder> ExplicitObject;
15329 QualType ObjectType;
15330 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15331 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15332 if (ObjectType->isReferenceType())
15333 ObjectType = ObjectType->getPointeeType();
15334 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15335 } else {
15336 ObjectType = getCurrentThisType();
15337 This.emplace();
15338 DerefThis.emplace(*This);
15339 }
15340 ExprBuilder &ObjectParameter =
15341 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15342
15343 // Assign base classes.
15344 bool Invalid = false;
15345 for (auto &Base : ClassDecl->bases()) {
15346 // C++11 [class.copy]p28:
15347 // It is unspecified whether subobjects representing virtual base classes
15348 // are assigned more than once by the implicitly-defined copy assignment
15349 // operator.
15350 // FIXME: Do not assign to a vbase that will be assigned by some other base
15351 // class. For a move-assignment, this can result in the vbase being moved
15352 // multiple times.
15353
15354 // Form the assignment:
15355 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15356 QualType BaseType = Base.getType().getUnqualifiedType();
15357 if (!BaseType->isRecordType()) {
15358 Invalid = true;
15359 continue;
15360 }
15361
15362 CXXCastPath BasePath;
15363 BasePath.push_back(&Base);
15364
15365 // Construct the "from" expression, which is an implicit cast to the
15366 // appropriately-qualified base type.
15367 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15368
15369 // Implicitly cast "this" to the appropriately-qualified base type.
15370 // Dereference "this".
15371 CastBuilder To(
15372 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15373 : static_cast<ExprBuilder &>(*DerefThis),
15374 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15375 VK_LValue, BasePath);
15376
15377 // Build the move.
15378 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15379 To, From,
15380 /*CopyingBaseSubobject=*/true,
15381 /*Copying=*/false);
15382 if (Move.isInvalid()) {
15383 MoveAssignOperator->setInvalidDecl();
15384 return;
15385 }
15386
15387 // Success! Record the move.
15388 Statements.push_back(Move.getAs<Expr>());
15389 }
15390
15391 // Assign non-static members.
15392 for (auto *Field : ClassDecl->fields()) {
15393 // FIXME: We should form some kind of AST representation for the implied
15394 // memcpy in a union copy operation.
15395 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15396 continue;
15397
15398 if (Field->isInvalidDecl()) {
15399 Invalid = true;
15400 continue;
15401 }
15402
15403 // Check for members of reference type; we can't move those.
15404 if (Field->getType()->isReferenceType()) {
15405 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15406 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15407 Diag(Field->getLocation(), diag::note_declared_at);
15408 Invalid = true;
15409 continue;
15410 }
15411
15412 // Check for members of const-qualified, non-class type.
15413 QualType BaseType = Context.getBaseElementType(Field->getType());
15414 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15415 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15416 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15417 Diag(Field->getLocation(), diag::note_declared_at);
15418 Invalid = true;
15419 continue;
15420 }
15421
15422 // Suppress assigning zero-width bitfields.
15423 if (Field->isZeroLengthBitField(Context))
15424 continue;
15425
15426 QualType FieldType = Field->getType().getNonReferenceType();
15427 if (FieldType->isIncompleteArrayType()) {
15428 assert(ClassDecl->hasFlexibleArrayMember() &&
15429 "Incomplete array type is not valid");
15430 continue;
15431 }
15432
15433 // Build references to the field in the object we're copying from and to.
15434 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15436 MemberLookup.addDecl(Field);
15437 MemberLookup.resolveKind();
15438 MemberBuilder From(MoveOther, OtherRefType,
15439 /*IsArrow=*/false, MemberLookup);
15440 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15441 MemberLookup);
15442
15443 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15444 "Member reference with rvalue base must be rvalue except for reference "
15445 "members, which aren't allowed for move assignment.");
15446
15447 // Build the move of this field.
15448 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15449 To, From,
15450 /*CopyingBaseSubobject=*/false,
15451 /*Copying=*/false);
15452 if (Move.isInvalid()) {
15453 MoveAssignOperator->setInvalidDecl();
15454 return;
15455 }
15456
15457 // Success! Record the copy.
15458 Statements.push_back(Move.getAs<Stmt>());
15459 }
15460
15461 if (!Invalid) {
15462 // Add a "return *this;"
15463 Expr *ThisExpr =
15464 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15465 : static_cast<ExprBuilder &>(*DerefThis))
15466 .build(*this, Loc);
15467
15468 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15469 if (Return.isInvalid())
15470 Invalid = true;
15471 else
15472 Statements.push_back(Return.getAs<Stmt>());
15473 }
15474
15475 if (Invalid) {
15476 MoveAssignOperator->setInvalidDecl();
15477 return;
15478 }
15479
15480 StmtResult Body;
15481 {
15482 CompoundScopeRAII CompoundScope(*this);
15483 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15484 /*isStmtExpr=*/false);
15485 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15486 }
15487 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15488 MoveAssignOperator->markUsed(Context);
15489
15491 L->CompletedImplicitDefinition(MoveAssignOperator);
15492 }
15493}
15494
15496 CXXRecordDecl *ClassDecl) {
15497 // C++ [class.copy]p4:
15498 // If the class definition does not explicitly declare a copy
15499 // constructor, one is declared implicitly.
15500 assert(ClassDecl->needsImplicitCopyConstructor());
15501
15502 DeclaringSpecialMember DSM(*this, ClassDecl,
15504 if (DSM.isAlreadyBeingDeclared())
15505 return nullptr;
15506
15507 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15508 QualType ArgType = ClassType;
15510 ArgType, nullptr);
15511 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15512 if (Const)
15513 ArgType = ArgType.withConst();
15514
15516 if (AS != LangAS::Default)
15517 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15518
15519 ArgType = Context.getLValueReferenceType(ArgType);
15520
15522 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15523
15524 DeclarationName Name
15526 Context.getCanonicalType(ClassType));
15527 SourceLocation ClassLoc = ClassDecl->getLocation();
15528 DeclarationNameInfo NameInfo(Name, ClassLoc);
15529
15530 // An implicitly-declared copy constructor is an inline public
15531 // member of its class.
15533 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15534 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15535 /*isInline=*/true,
15536 /*isImplicitlyDeclared=*/true,
15539 CopyConstructor->setAccess(AS_public);
15540 CopyConstructor->setDefaulted();
15541
15542 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15543
15544 if (getLangOpts().CUDA)
15547 /* ConstRHS */ Const,
15548 /* Diagnose */ false);
15549
15550 // During template instantiation of special member functions we need a
15551 // reliable TypeSourceInfo for the parameter types in order to allow functions
15552 // to be substituted.
15553 TypeSourceInfo *TSI = nullptr;
15554 if (inTemplateInstantiation() && ClassDecl->isLambda())
15555 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15556
15557 // Add the parameter to the constructor.
15558 ParmVarDecl *FromParam =
15559 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15560 /*IdentifierInfo=*/nullptr, ArgType,
15561 /*TInfo=*/TSI, SC_None, nullptr);
15562 CopyConstructor->setParams(FromParam);
15563
15564 CopyConstructor->setTrivial(
15568 : ClassDecl->hasTrivialCopyConstructor());
15569
15570 CopyConstructor->setTrivialForCall(
15571 ClassDecl->hasAttr<TrivialABIAttr>() ||
15576 : ClassDecl->hasTrivialCopyConstructorForCall()));
15577
15578 // Note that we have declared this constructor.
15580
15581 Scope *S = getScopeForContext(ClassDecl);
15583
15588 }
15589
15590 if (S)
15592 ClassDecl->addDecl(CopyConstructor);
15593
15594 return CopyConstructor;
15595}
15596
15599 assert((CopyConstructor->isDefaulted() &&
15600 CopyConstructor->isCopyConstructor() &&
15601 !CopyConstructor->doesThisDeclarationHaveABody() &&
15602 !CopyConstructor->isDeleted()) &&
15603 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15604 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15605 return;
15606
15607 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15608 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15609
15611
15612 // The exception specification is needed because we are defining the
15613 // function.
15614 ResolveExceptionSpec(CurrentLocation,
15615 CopyConstructor->getType()->castAs<FunctionProtoType>());
15616 MarkVTableUsed(CurrentLocation, ClassDecl);
15617
15618 // Add a context note for diagnostics produced after this point.
15619 Scope.addContextNote(CurrentLocation);
15620
15621 // C++11 [class.copy]p7:
15622 // The [definition of an implicitly declared copy constructor] is
15623 // deprecated if the class has a user-declared copy assignment operator
15624 // or a user-declared destructor.
15625 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15627
15628 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15629 CopyConstructor->setInvalidDecl();
15630 } else {
15631 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15632 ? CopyConstructor->getEndLoc()
15633 : CopyConstructor->getLocation();
15634 Sema::CompoundScopeRAII CompoundScope(*this);
15635 CopyConstructor->setBody(
15636 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15637 .getAs<Stmt>());
15638 CopyConstructor->markUsed(Context);
15639 }
15640
15642 L->CompletedImplicitDefinition(CopyConstructor);
15643 }
15644}
15645
15647 CXXRecordDecl *ClassDecl) {
15648 assert(ClassDecl->needsImplicitMoveConstructor());
15649
15650 DeclaringSpecialMember DSM(*this, ClassDecl,
15652 if (DSM.isAlreadyBeingDeclared())
15653 return nullptr;
15654
15655 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15656
15657 QualType ArgType = ClassType;
15659 ArgType, nullptr);
15661 if (AS != LangAS::Default)
15662 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15663 ArgType = Context.getRValueReferenceType(ArgType);
15664
15666 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15667
15668 DeclarationName Name
15670 Context.getCanonicalType(ClassType));
15671 SourceLocation ClassLoc = ClassDecl->getLocation();
15672 DeclarationNameInfo NameInfo(Name, ClassLoc);
15673
15674 // C++11 [class.copy]p11:
15675 // An implicitly-declared copy/move constructor is an inline public
15676 // member of its class.
15678 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15679 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15680 /*isInline=*/true,
15681 /*isImplicitlyDeclared=*/true,
15684 MoveConstructor->setAccess(AS_public);
15685 MoveConstructor->setDefaulted();
15686
15687 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15688
15689 if (getLangOpts().CUDA)
15692 /* ConstRHS */ false,
15693 /* Diagnose */ false);
15694
15695 // Add the parameter to the constructor.
15697 ClassLoc, ClassLoc,
15698 /*IdentifierInfo=*/nullptr,
15699 ArgType, /*TInfo=*/nullptr,
15700 SC_None, nullptr);
15701 MoveConstructor->setParams(FromParam);
15702
15703 MoveConstructor->setTrivial(
15707 : ClassDecl->hasTrivialMoveConstructor());
15708
15709 MoveConstructor->setTrivialForCall(
15710 ClassDecl->hasAttr<TrivialABIAttr>() ||
15715 : ClassDecl->hasTrivialMoveConstructorForCall()));
15716
15717 // Note that we have declared this constructor.
15719
15720 Scope *S = getScopeForContext(ClassDecl);
15722
15727 }
15728
15729 if (S)
15731 ClassDecl->addDecl(MoveConstructor);
15732
15733 return MoveConstructor;
15734}
15735
15738 assert((MoveConstructor->isDefaulted() &&
15739 MoveConstructor->isMoveConstructor() &&
15740 !MoveConstructor->doesThisDeclarationHaveABody() &&
15741 !MoveConstructor->isDeleted()) &&
15742 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15743 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15744 return;
15745
15746 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15747 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15748
15750
15751 // The exception specification is needed because we are defining the
15752 // function.
15753 ResolveExceptionSpec(CurrentLocation,
15754 MoveConstructor->getType()->castAs<FunctionProtoType>());
15755 MarkVTableUsed(CurrentLocation, ClassDecl);
15756
15757 // Add a context note for diagnostics produced after this point.
15758 Scope.addContextNote(CurrentLocation);
15759
15760 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15761 MoveConstructor->setInvalidDecl();
15762 } else {
15763 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15764 ? MoveConstructor->getEndLoc()
15765 : MoveConstructor->getLocation();
15766 Sema::CompoundScopeRAII CompoundScope(*this);
15767 MoveConstructor->setBody(
15768 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15769 .getAs<Stmt>());
15770 MoveConstructor->markUsed(Context);
15771 }
15772
15774 L->CompletedImplicitDefinition(MoveConstructor);
15775 }
15776}
15777
15779 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15780}
15781
15783 SourceLocation CurrentLocation,
15784 CXXConversionDecl *Conv) {
15785 SynthesizedFunctionScope Scope(*this, Conv);
15786 assert(!Conv->getReturnType()->isUndeducedType());
15787
15788 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15789 CallingConv CC =
15790 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15791
15792 CXXRecordDecl *Lambda = Conv->getParent();
15793 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15794 FunctionDecl *Invoker =
15795 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15796 ? CallOp
15797 : Lambda->getLambdaStaticInvoker(CC);
15798
15799 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15801 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15802 if (!CallOp)
15803 return;
15804
15805 if (CallOp != Invoker) {
15807 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15808 CurrentLocation);
15809 if (!Invoker)
15810 return;
15811 }
15812 }
15813
15814 if (CallOp->isInvalidDecl())
15815 return;
15816
15817 // Mark the call operator referenced (and add to pending instantiations
15818 // if necessary).
15819 // For both the conversion and static-invoker template specializations
15820 // we construct their body's in this function, so no need to add them
15821 // to the PendingInstantiations.
15822 MarkFunctionReferenced(CurrentLocation, CallOp);
15823
15824 if (Invoker != CallOp) {
15825 // Fill in the __invoke function with a dummy implementation. IR generation
15826 // will fill in the actual details. Update its type in case it contained
15827 // an 'auto'.
15828 Invoker->markUsed(Context);
15829 Invoker->setReferenced();
15830 Invoker->setType(Conv->getReturnType()->getPointeeType());
15831 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15832 }
15833
15834 // Construct the body of the conversion function { return __invoke; }.
15835 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15836 Conv->getLocation());
15837 assert(FunctionRef && "Can't refer to __invoke function?");
15838 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15840 Conv->getLocation(), Conv->getLocation()));
15841 Conv->markUsed(Context);
15842 Conv->setReferenced();
15843
15845 L->CompletedImplicitDefinition(Conv);
15846 if (Invoker != CallOp)
15847 L->CompletedImplicitDefinition(Invoker);
15848 }
15849}
15850
15852 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15853 assert(!Conv->getParent()->isGenericLambda());
15854
15855 SynthesizedFunctionScope Scope(*this, Conv);
15856
15857 // Copy-initialize the lambda object as needed to capture it.
15858 Expr *This = ActOnCXXThis(CurrentLocation).get();
15859 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15860
15861 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15862 Conv->getLocation(),
15863 Conv, DerefThis);
15864
15865 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15866 // behavior. Note that only the general conversion function does this
15867 // (since it's unusable otherwise); in the case where we inline the
15868 // block literal, it has block literal lifetime semantics.
15869 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15870 BuildBlock = ImplicitCastExpr::Create(
15871 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15872 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15873
15874 if (BuildBlock.isInvalid()) {
15875 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15876 Conv->setInvalidDecl();
15877 return;
15878 }
15879
15880 // Create the return statement that returns the block from the conversion
15881 // function.
15882 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15883 if (Return.isInvalid()) {
15884 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15885 Conv->setInvalidDecl();
15886 return;
15887 }
15888
15889 // Set the body of the conversion function.
15890 Stmt *ReturnS = Return.get();
15892 Conv->getLocation(), Conv->getLocation()));
15893 Conv->markUsed(Context);
15894
15895 // We're done; notify the mutation listener, if any.
15897 L->CompletedImplicitDefinition(Conv);
15898 }
15899}
15900
15901/// Determine whether the given list arguments contains exactly one
15902/// "real" (non-default) argument.
15904 switch (Args.size()) {
15905 case 0:
15906 return false;
15907
15908 default:
15909 if (!Args[1]->isDefaultArgument())
15910 return false;
15911
15912 [[fallthrough]];
15913 case 1:
15914 return !Args[0]->isDefaultArgument();
15915 }
15916
15917 return false;
15918}
15919
15921 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15922 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
15923 bool HadMultipleCandidates, bool IsListInitialization,
15924 bool IsStdInitListInitialization, bool RequiresZeroInit,
15925 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15926 bool Elidable = false;
15927
15928 // C++0x [class.copy]p34:
15929 // When certain criteria are met, an implementation is allowed to
15930 // omit the copy/move construction of a class object, even if the
15931 // copy/move constructor and/or destructor for the object have
15932 // side effects. [...]
15933 // - when a temporary class object that has not been bound to a
15934 // reference (12.2) would be copied/moved to a class object
15935 // with the same cv-unqualified type, the copy/move operation
15936 // can be omitted by constructing the temporary object
15937 // directly into the target of the omitted copy/move
15938 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
15939 // FIXME: Converting constructors should also be accepted.
15940 // But to fix this, the logic that digs down into a CXXConstructExpr
15941 // to find the source object needs to handle it.
15942 // Right now it assumes the source object is passed directly as the
15943 // first argument.
15944 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15945 Expr *SubExpr = ExprArgs[0];
15946 // FIXME: Per above, this is also incorrect if we want to accept
15947 // converting constructors, as isTemporaryObject will
15948 // reject temporaries with different type from the
15949 // CXXRecord itself.
15950 Elidable = SubExpr->isTemporaryObject(
15951 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15952 }
15953
15954 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15955 FoundDecl, Constructor,
15956 Elidable, ExprArgs, HadMultipleCandidates,
15957 IsListInitialization,
15958 IsStdInitListInitialization, RequiresZeroInit,
15959 ConstructKind, ParenRange);
15960}
15961
15963 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15964 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15965 bool HadMultipleCandidates, bool IsListInitialization,
15966 bool IsStdInitListInitialization, bool RequiresZeroInit,
15967 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15968 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15969 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15970 // The only way to get here is if we did overload resolution to find the
15971 // shadow decl, so we don't need to worry about re-checking the trailing
15972 // requires clause.
15973 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15974 return ExprError();
15975 }
15976
15977 return BuildCXXConstructExpr(
15978 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15979 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15980 RequiresZeroInit, ConstructKind, ParenRange);
15981}
15982
15983/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15984/// including handling of its default argument expressions.
15986 SourceLocation ConstructLoc, QualType DeclInitType,
15987 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15988 bool HadMultipleCandidates, bool IsListInitialization,
15989 bool IsStdInitListInitialization, bool RequiresZeroInit,
15990 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15991 assert(declaresSameEntity(
15992 Constructor->getParent(),
15993 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15994 "given constructor for wrong type");
15995 MarkFunctionReferenced(ConstructLoc, Constructor);
15996 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
15997 return ExprError();
15998
16001 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16002 HadMultipleCandidates, IsListInitialization,
16003 IsStdInitListInitialization, RequiresZeroInit,
16004 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16005 Constructor);
16006}
16007
16009 if (VD->isInvalidDecl()) return;
16010 // If initializing the variable failed, don't also diagnose problems with
16011 // the destructor, they're likely related.
16012 if (VD->getInit() && VD->getInit()->containsErrors())
16013 return;
16014
16015 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16016 if (ClassDecl->isInvalidDecl()) return;
16017 if (ClassDecl->hasIrrelevantDestructor()) return;
16018 if (ClassDecl->isDependentContext()) return;
16019
16020 if (VD->isNoDestroy(getASTContext()))
16021 return;
16022
16024 // The result of `LookupDestructor` might be nullptr if the destructor is
16025 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16026 // will not be selected by `CXXRecordDecl::getDestructor()`.
16027 if (!Destructor)
16028 return;
16029 // If this is an array, we'll require the destructor during initialization, so
16030 // we can skip over this. We still want to emit exit-time destructor warnings
16031 // though.
16032 if (!VD->getType()->isArrayType()) {
16035 PDiag(diag::err_access_dtor_var)
16036 << VD->getDeclName() << VD->getType());
16038 }
16039
16040 if (Destructor->isTrivial()) return;
16041
16042 // If the destructor is constexpr, check whether the variable has constant
16043 // destruction now.
16044 if (Destructor->isConstexpr()) {
16045 bool HasConstantInit = false;
16046 if (VD->getInit() && !VD->getInit()->isValueDependent())
16047 HasConstantInit = VD->evaluateValue();
16049 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16050 HasConstantInit) {
16051 Diag(VD->getLocation(),
16052 diag::err_constexpr_var_requires_const_destruction) << VD;
16053 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16054 Diag(Notes[I].first, Notes[I].second);
16055 }
16056 }
16057
16058 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16059 return;
16060
16061 // Emit warning for non-trivial dtor in global scope (a real global,
16062 // class-static, function-static).
16063 if (!VD->hasAttr<AlwaysDestroyAttr>())
16064 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16065
16066 // TODO: this should be re-enabled for static locals by !CXAAtExit
16067 if (!VD->isStaticLocal())
16068 Diag(VD->getLocation(), diag::warn_global_destructor);
16069}
16070
16072 QualType DeclInitType, MultiExprArg ArgsPtr,
16074 SmallVectorImpl<Expr *> &ConvertedArgs,
16075 bool AllowExplicit,
16076 bool IsListInitialization) {
16077 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16078 unsigned NumArgs = ArgsPtr.size();
16079 Expr **Args = ArgsPtr.data();
16080
16081 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16082 unsigned NumParams = Proto->getNumParams();
16083
16084 // If too few arguments are available, we'll fill in the rest with defaults.
16085 if (NumArgs < NumParams)
16086 ConvertedArgs.reserve(NumParams);
16087 else
16088 ConvertedArgs.reserve(NumArgs);
16089
16090 VariadicCallType CallType =
16091 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16092 SmallVector<Expr *, 8> AllArgs;
16094 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16095 CallType, AllowExplicit, IsListInitialization);
16096 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16097
16098 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16099
16100 CheckConstructorCall(Constructor, DeclInitType,
16101 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16102 Loc);
16103
16104 return Invalid;
16105}
16106
16107static inline bool
16109 const FunctionDecl *FnDecl) {
16110 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16111 if (isa<NamespaceDecl>(DC)) {
16112 return SemaRef.Diag(FnDecl->getLocation(),
16113 diag::err_operator_new_delete_declared_in_namespace)
16114 << FnDecl->getDeclName();
16115 }
16116
16117 if (isa<TranslationUnitDecl>(DC) &&
16118 FnDecl->getStorageClass() == SC_Static) {
16119 return SemaRef.Diag(FnDecl->getLocation(),
16120 diag::err_operator_new_delete_declared_static)
16121 << FnDecl->getDeclName();
16122 }
16123
16124 return false;
16125}
16126
16128 const PointerType *PtrTy) {
16129 auto &Ctx = SemaRef.Context;
16130 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16131 PtrQuals.removeAddressSpace();
16132 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16133 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16134}
16135
16136static inline bool
16138 CanQualType ExpectedResultType,
16139 CanQualType ExpectedFirstParamType,
16140 unsigned DependentParamTypeDiag,
16141 unsigned InvalidParamTypeDiag) {
16142 QualType ResultType =
16143 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16144
16145 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16146 // The operator is valid on any address space for OpenCL.
16147 // Drop address space from actual and expected result types.
16148 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16149 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16150
16151 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16152 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16153 }
16154
16155 // Check that the result type is what we expect.
16156 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16157 // Reject even if the type is dependent; an operator delete function is
16158 // required to have a non-dependent result type.
16159 return SemaRef.Diag(
16160 FnDecl->getLocation(),
16161 ResultType->isDependentType()
16162 ? diag::err_operator_new_delete_dependent_result_type
16163 : diag::err_operator_new_delete_invalid_result_type)
16164 << FnDecl->getDeclName() << ExpectedResultType;
16165 }
16166
16167 // A function template must have at least 2 parameters.
16168 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16169 return SemaRef.Diag(FnDecl->getLocation(),
16170 diag::err_operator_new_delete_template_too_few_parameters)
16171 << FnDecl->getDeclName();
16172
16173 // The function decl must have at least 1 parameter.
16174 if (FnDecl->getNumParams() == 0)
16175 return SemaRef.Diag(FnDecl->getLocation(),
16176 diag::err_operator_new_delete_too_few_parameters)
16177 << FnDecl->getDeclName();
16178
16179 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16180 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16181 // The operator is valid on any address space for OpenCL.
16182 // Drop address space from actual and expected first parameter types.
16183 if (const auto *PtrTy =
16184 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16185 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16186
16187 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16188 ExpectedFirstParamType =
16189 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16190 }
16191
16192 // Check that the first parameter type is what we expect.
16193 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16194 ExpectedFirstParamType) {
16195 // The first parameter type is not allowed to be dependent. As a tentative
16196 // DR resolution, we allow a dependent parameter type if it is the right
16197 // type anyway, to allow destroying operator delete in class templates.
16198 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16199 ? DependentParamTypeDiag
16200 : InvalidParamTypeDiag)
16201 << FnDecl->getDeclName() << ExpectedFirstParamType;
16202 }
16203
16204 return false;
16205}
16206
16207static bool
16209 // C++ [basic.stc.dynamic.allocation]p1:
16210 // A program is ill-formed if an allocation function is declared in a
16211 // namespace scope other than global scope or declared static in global
16212 // scope.
16214 return true;
16215
16216 CanQualType SizeTy =
16218
16219 // C++ [basic.stc.dynamic.allocation]p1:
16220 // The return type shall be void*. The first parameter shall have type
16221 // std::size_t.
16223 SizeTy,
16224 diag::err_operator_new_dependent_param_type,
16225 diag::err_operator_new_param_type))
16226 return true;
16227
16228 // C++ [basic.stc.dynamic.allocation]p1:
16229 // The first parameter shall not have an associated default argument.
16230 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16231 return SemaRef.Diag(FnDecl->getLocation(),
16232 diag::err_operator_new_default_arg)
16233 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16234
16235 return false;
16236}
16237
16238static bool
16240 // C++ [basic.stc.dynamic.deallocation]p1:
16241 // A program is ill-formed if deallocation functions are declared in a
16242 // namespace scope other than global scope or declared static in global
16243 // scope.
16245 return true;
16246
16247 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16248
16249 // C++ P0722:
16250 // Within a class C, the first parameter of a destroying operator delete
16251 // shall be of type C *. The first parameter of any other deallocation
16252 // function shall be of type void *.
16253 CanQualType ExpectedFirstParamType =
16254 MD && MD->isDestroyingOperatorDelete()
16258
16259 // C++ [basic.stc.dynamic.deallocation]p2:
16260 // Each deallocation function shall return void
16262 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16263 diag::err_operator_delete_dependent_param_type,
16264 diag::err_operator_delete_param_type))
16265 return true;
16266
16267 // C++ P0722:
16268 // A destroying operator delete shall be a usual deallocation function.
16269 if (MD && !MD->getParent()->isDependentContext() &&
16272 SemaRef.Diag(MD->getLocation(),
16273 diag::err_destroying_operator_delete_not_usual);
16274 return true;
16275 }
16276
16277 return false;
16278}
16279
16281 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16282 "Expected an overloaded operator declaration");
16283
16285
16286 // C++ [over.oper]p5:
16287 // The allocation and deallocation functions, operator new,
16288 // operator new[], operator delete and operator delete[], are
16289 // described completely in 3.7.3. The attributes and restrictions
16290 // found in the rest of this subclause do not apply to them unless
16291 // explicitly stated in 3.7.3.
16292 if (Op == OO_Delete || Op == OO_Array_Delete)
16293 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16294
16295 if (Op == OO_New || Op == OO_Array_New)
16296 return CheckOperatorNewDeclaration(*this, FnDecl);
16297
16298 // C++ [over.oper]p7:
16299 // An operator function shall either be a member function or
16300 // be a non-member function and have at least one parameter
16301 // whose type is a class, a reference to a class, an enumeration,
16302 // or a reference to an enumeration.
16303 // Note: Before C++23, a member function could not be static. The only member
16304 // function allowed to be static is the call operator function.
16305 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16306 if (MethodDecl->isStatic()) {
16307 if (Op == OO_Call || Op == OO_Subscript)
16308 Diag(FnDecl->getLocation(),
16309 (LangOpts.CPlusPlus23
16310 ? diag::warn_cxx20_compat_operator_overload_static
16311 : diag::ext_operator_overload_static))
16312 << FnDecl;
16313 else
16314 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16315 << FnDecl;
16316 }
16317 } else {
16318 bool ClassOrEnumParam = false;
16319 for (auto *Param : FnDecl->parameters()) {
16320 QualType ParamType = Param->getType().getNonReferenceType();
16321 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16322 ParamType->isEnumeralType()) {
16323 ClassOrEnumParam = true;
16324 break;
16325 }
16326 }
16327
16328 if (!ClassOrEnumParam)
16329 return Diag(FnDecl->getLocation(),
16330 diag::err_operator_overload_needs_class_or_enum)
16331 << FnDecl->getDeclName();
16332 }
16333
16334 // C++ [over.oper]p8:
16335 // An operator function cannot have default arguments (8.3.6),
16336 // except where explicitly stated below.
16337 //
16338 // Only the function-call operator (C++ [over.call]p1) and the subscript
16339 // operator (CWG2507) allow default arguments.
16340 if (Op != OO_Call) {
16341 ParmVarDecl *FirstDefaultedParam = nullptr;
16342 for (auto *Param : FnDecl->parameters()) {
16343 if (Param->hasDefaultArg()) {
16344 FirstDefaultedParam = Param;
16345 break;
16346 }
16347 }
16348 if (FirstDefaultedParam) {
16349 if (Op == OO_Subscript) {
16350 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16351 ? diag::ext_subscript_overload
16352 : diag::error_subscript_overload)
16353 << FnDecl->getDeclName() << 1
16354 << FirstDefaultedParam->getDefaultArgRange();
16355 } else {
16356 return Diag(FirstDefaultedParam->getLocation(),
16357 diag::err_operator_overload_default_arg)
16358 << FnDecl->getDeclName()
16359 << FirstDefaultedParam->getDefaultArgRange();
16360 }
16361 }
16362 }
16363
16364 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16365 { false, false, false }
16366#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16367 , { Unary, Binary, MemberOnly }
16368#include "clang/Basic/OperatorKinds.def"
16369 };
16370
16371 bool CanBeUnaryOperator = OperatorUses[Op][0];
16372 bool CanBeBinaryOperator = OperatorUses[Op][1];
16373 bool MustBeMemberOperator = OperatorUses[Op][2];
16374
16375 // C++ [over.oper]p8:
16376 // [...] Operator functions cannot have more or fewer parameters
16377 // than the number required for the corresponding operator, as
16378 // described in the rest of this subclause.
16379 unsigned NumParams = FnDecl->getNumParams() +
16380 (isa<CXXMethodDecl>(FnDecl) &&
16382 ? 1
16383 : 0);
16384 if (Op != OO_Call && Op != OO_Subscript &&
16385 ((NumParams == 1 && !CanBeUnaryOperator) ||
16386 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16387 (NumParams > 2))) {
16388 // We have the wrong number of parameters.
16389 unsigned ErrorKind;
16390 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16391 ErrorKind = 2; // 2 -> unary or binary.
16392 } else if (CanBeUnaryOperator) {
16393 ErrorKind = 0; // 0 -> unary
16394 } else {
16395 assert(CanBeBinaryOperator &&
16396 "All non-call overloaded operators are unary or binary!");
16397 ErrorKind = 1; // 1 -> binary
16398 }
16399 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16400 << FnDecl->getDeclName() << NumParams << ErrorKind;
16401 }
16402
16403 if (Op == OO_Subscript && NumParams != 2) {
16404 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16405 ? diag::ext_subscript_overload
16406 : diag::error_subscript_overload)
16407 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16408 }
16409
16410 // Overloaded operators other than operator() and operator[] cannot be
16411 // variadic.
16412 if (Op != OO_Call &&
16413 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16414 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16415 << FnDecl->getDeclName();
16416 }
16417
16418 // Some operators must be member functions.
16419 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16420 return Diag(FnDecl->getLocation(),
16421 diag::err_operator_overload_must_be_member)
16422 << FnDecl->getDeclName();
16423 }
16424
16425 // C++ [over.inc]p1:
16426 // The user-defined function called operator++ implements the
16427 // prefix and postfix ++ operator. If this function is a member
16428 // function with no parameters, or a non-member function with one
16429 // parameter of class or enumeration type, it defines the prefix
16430 // increment operator ++ for objects of that type. If the function
16431 // is a member function with one parameter (which shall be of type
16432 // int) or a non-member function with two parameters (the second
16433 // of which shall be of type int), it defines the postfix
16434 // increment operator ++ for objects of that type.
16435 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16436 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16437 QualType ParamType = LastParam->getType();
16438
16439 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16440 !ParamType->isDependentType())
16441 return Diag(LastParam->getLocation(),
16442 diag::err_operator_overload_post_incdec_must_be_int)
16443 << LastParam->getType() << (Op == OO_MinusMinus);
16444 }
16445
16446 return false;
16447}
16448
16449static bool
16451 FunctionTemplateDecl *TpDecl) {
16452 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16453
16454 // Must have one or two template parameters.
16455 if (TemplateParams->size() == 1) {
16456 NonTypeTemplateParmDecl *PmDecl =
16457 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16458
16459 // The template parameter must be a char parameter pack.
16460 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16462 return false;
16463
16464 // C++20 [over.literal]p5:
16465 // A string literal operator template is a literal operator template
16466 // whose template-parameter-list comprises a single non-type
16467 // template-parameter of class type.
16468 //
16469 // As a DR resolution, we also allow placeholders for deduced class
16470 // template specializations.
16471 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16472 !PmDecl->isTemplateParameterPack() &&
16473 (PmDecl->getType()->isRecordType() ||
16475 return false;
16476 } else if (TemplateParams->size() == 2) {
16477 TemplateTypeParmDecl *PmType =
16478 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16479 NonTypeTemplateParmDecl *PmArgs =
16480 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16481
16482 // The second template parameter must be a parameter pack with the
16483 // first template parameter as its type.
16484 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16485 PmArgs->isTemplateParameterPack()) {
16486 const TemplateTypeParmType *TArgs =
16487 PmArgs->getType()->getAs<TemplateTypeParmType>();
16488 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16489 TArgs->getIndex() == PmType->getIndex()) {
16491 SemaRef.Diag(TpDecl->getLocation(),
16492 diag::ext_string_literal_operator_template);
16493 return false;
16494 }
16495 }
16496 }
16497
16499 diag::err_literal_operator_template)
16500 << TpDecl->getTemplateParameters()->getSourceRange();
16501 return true;
16502}
16503
16505 if (isa<CXXMethodDecl>(FnDecl)) {
16506 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16507 << FnDecl->getDeclName();
16508 return true;
16509 }
16510
16511 if (FnDecl->isExternC()) {
16512 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16513 if (const LinkageSpecDecl *LSD =
16514 FnDecl->getDeclContext()->getExternCContext())
16515 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16516 return true;
16517 }
16518
16519 // This might be the definition of a literal operator template.
16521
16522 // This might be a specialization of a literal operator template.
16523 if (!TpDecl)
16524 TpDecl = FnDecl->getPrimaryTemplate();
16525
16526 // template <char...> type operator "" name() and
16527 // template <class T, T...> type operator "" name() are the only valid
16528 // template signatures, and the only valid signatures with no parameters.
16529 //
16530 // C++20 also allows template <SomeClass T> type operator "" name().
16531 if (TpDecl) {
16532 if (FnDecl->param_size() != 0) {
16533 Diag(FnDecl->getLocation(),
16534 diag::err_literal_operator_template_with_params);
16535 return true;
16536 }
16537
16539 return true;
16540
16541 } else if (FnDecl->param_size() == 1) {
16542 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16543
16544 QualType ParamType = Param->getType().getUnqualifiedType();
16545
16546 // Only unsigned long long int, long double, any character type, and const
16547 // char * are allowed as the only parameters.
16548 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16549 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16550 Context.hasSameType(ParamType, Context.CharTy) ||
16551 Context.hasSameType(ParamType, Context.WideCharTy) ||
16552 Context.hasSameType(ParamType, Context.Char8Ty) ||
16553 Context.hasSameType(ParamType, Context.Char16Ty) ||
16554 Context.hasSameType(ParamType, Context.Char32Ty)) {
16555 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16556 QualType InnerType = Ptr->getPointeeType();
16557
16558 // Pointer parameter must be a const char *.
16559 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16560 Context.CharTy) &&
16561 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16562 Diag(Param->getSourceRange().getBegin(),
16563 diag::err_literal_operator_param)
16564 << ParamType << "'const char *'" << Param->getSourceRange();
16565 return true;
16566 }
16567
16568 } else if (ParamType->isRealFloatingType()) {
16569 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16570 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16571 return true;
16572
16573 } else if (ParamType->isIntegerType()) {
16574 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16575 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16576 return true;
16577
16578 } else {
16579 Diag(Param->getSourceRange().getBegin(),
16580 diag::err_literal_operator_invalid_param)
16581 << ParamType << Param->getSourceRange();
16582 return true;
16583 }
16584
16585 } else if (FnDecl->param_size() == 2) {
16586 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16587
16588 // First, verify that the first parameter is correct.
16589
16590 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16591
16592 // Two parameter function must have a pointer to const as a
16593 // first parameter; let's strip those qualifiers.
16594 const PointerType *PT = FirstParamType->getAs<PointerType>();
16595
16596 if (!PT) {
16597 Diag((*Param)->getSourceRange().getBegin(),
16598 diag::err_literal_operator_param)
16599 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16600 return true;
16601 }
16602
16603 QualType PointeeType = PT->getPointeeType();
16604 // First parameter must be const
16605 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16606 Diag((*Param)->getSourceRange().getBegin(),
16607 diag::err_literal_operator_param)
16608 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16609 return true;
16610 }
16611
16612 QualType InnerType = PointeeType.getUnqualifiedType();
16613 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16614 // const char32_t* are allowed as the first parameter to a two-parameter
16615 // function
16616 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16617 Context.hasSameType(InnerType, Context.WideCharTy) ||
16618 Context.hasSameType(InnerType, Context.Char8Ty) ||
16619 Context.hasSameType(InnerType, Context.Char16Ty) ||
16620 Context.hasSameType(InnerType, Context.Char32Ty))) {
16621 Diag((*Param)->getSourceRange().getBegin(),
16622 diag::err_literal_operator_param)
16623 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16624 return true;
16625 }
16626
16627 // Move on to the second and final parameter.
16628 ++Param;
16629
16630 // The second parameter must be a std::size_t.
16631 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16632 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16633 Diag((*Param)->getSourceRange().getBegin(),
16634 diag::err_literal_operator_param)
16635 << SecondParamType << Context.getSizeType()
16636 << (*Param)->getSourceRange();
16637 return true;
16638 }
16639 } else {
16640 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16641 return true;
16642 }
16643
16644 // Parameters are good.
16645
16646 // A parameter-declaration-clause containing a default argument is not
16647 // equivalent to any of the permitted forms.
16648 for (auto *Param : FnDecl->parameters()) {
16649 if (Param->hasDefaultArg()) {
16650 Diag(Param->getDefaultArgRange().getBegin(),
16651 diag::err_literal_operator_default_argument)
16652 << Param->getDefaultArgRange();
16653 break;
16654 }
16655 }
16656
16657 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16660 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16661 // C++23 [usrlit.suffix]p1:
16662 // Literal suffix identifiers that do not start with an underscore are
16663 // reserved for future standardization. Literal suffix identifiers that
16664 // contain a double underscore __ are reserved for use by C++
16665 // implementations.
16666 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16667 << static_cast<int>(Status)
16669 }
16670
16671 return false;
16672}
16673
16675 Expr *LangStr,
16676 SourceLocation LBraceLoc) {
16677 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16678 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16679
16680 StringRef Lang = Lit->getString();
16682 if (Lang == "C")
16684 else if (Lang == "C++")
16686 else {
16687 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16688 << LangStr->getSourceRange();
16689 return nullptr;
16690 }
16691
16692 // FIXME: Add all the various semantics of linkage specifications
16693
16695 LangStr->getExprLoc(), Language,
16696 LBraceLoc.isValid());
16697
16698 /// C++ [module.unit]p7.2.3
16699 /// - Otherwise, if the declaration
16700 /// - ...
16701 /// - ...
16702 /// - appears within a linkage-specification,
16703 /// it is attached to the global module.
16704 ///
16705 /// If the declaration is already in global module fragment, we don't
16706 /// need to attach it again.
16707 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16708 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16709 D->setLocalOwningModule(GlobalModule);
16710 }
16711
16713 PushDeclContext(S, D);
16714 return D;
16715}
16716
16718 Decl *LinkageSpec,
16719 SourceLocation RBraceLoc) {
16720 if (RBraceLoc.isValid()) {
16721 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16722 LSDecl->setRBraceLoc(RBraceLoc);
16723 }
16724
16725 // If the current module doesn't has Parent, it implies that the
16726 // LinkageSpec isn't in the module created by itself. So we don't
16727 // need to pop it.
16728 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16729 getCurrentModule()->isImplicitGlobalModule() &&
16731 PopImplicitGlobalModuleFragment();
16732
16734 return LinkageSpec;
16735}
16736
16738 const ParsedAttributesView &AttrList,
16739 SourceLocation SemiLoc) {
16740 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16741 // Attribute declarations appertain to empty declaration so we handle
16742 // them here.
16743 ProcessDeclAttributeList(S, ED, AttrList);
16744
16745 CurContext->addDecl(ED);
16746 return ED;
16747}
16748
16750 SourceLocation StartLoc,
16752 const IdentifierInfo *Name) {
16753 bool Invalid = false;
16754 QualType ExDeclType = TInfo->getType();
16755
16756 // Arrays and functions decay.
16757 if (ExDeclType->isArrayType())
16758 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16759 else if (ExDeclType->isFunctionType())
16760 ExDeclType = Context.getPointerType(ExDeclType);
16761
16762 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16763 // The exception-declaration shall not denote a pointer or reference to an
16764 // incomplete type, other than [cv] void*.
16765 // N2844 forbids rvalue references.
16766 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16767 Diag(Loc, diag::err_catch_rvalue_ref);
16768 Invalid = true;
16769 }
16770
16771 if (ExDeclType->isVariablyModifiedType()) {
16772 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16773 Invalid = true;
16774 }
16775
16776 QualType BaseType = ExDeclType;
16777 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16778 unsigned DK = diag::err_catch_incomplete;
16779 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16780 BaseType = Ptr->getPointeeType();
16781 Mode = 1;
16782 DK = diag::err_catch_incomplete_ptr;
16783 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16784 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16785 BaseType = Ref->getPointeeType();
16786 Mode = 2;
16787 DK = diag::err_catch_incomplete_ref;
16788 }
16789 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16790 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16791 Invalid = true;
16792
16793 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16794 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16795 Invalid = true;
16796 }
16797
16798 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16799 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16800 Invalid = true;
16801 }
16802
16803 if (!Invalid && !ExDeclType->isDependentType() &&
16804 RequireNonAbstractType(Loc, ExDeclType,
16805 diag::err_abstract_type_in_decl,
16807 Invalid = true;
16808
16809 // Only the non-fragile NeXT runtime currently supports C++ catches
16810 // of ObjC types, and no runtime supports catching ObjC types by value.
16811 if (!Invalid && getLangOpts().ObjC) {
16812 QualType T = ExDeclType;
16813 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16814 T = RT->getPointeeType();
16815
16816 if (T->isObjCObjectType()) {
16817 Diag(Loc, diag::err_objc_object_catch);
16818 Invalid = true;
16819 } else if (T->isObjCObjectPointerType()) {
16820 // FIXME: should this be a test for macosx-fragile specifically?
16822 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16823 }
16824 }
16825
16826 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16827 ExDeclType, TInfo, SC_None);
16828 ExDecl->setExceptionVariable(true);
16829
16830 // In ARC, infer 'retaining' for variables of retainable type.
16831 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16832 Invalid = true;
16833
16834 if (!Invalid && !ExDeclType->isDependentType()) {
16835 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16836 // Insulate this from anything else we might currently be parsing.
16839
16840 // C++ [except.handle]p16:
16841 // The object declared in an exception-declaration or, if the
16842 // exception-declaration does not specify a name, a temporary (12.2) is
16843 // copy-initialized (8.5) from the exception object. [...]
16844 // The object is destroyed when the handler exits, after the destruction
16845 // of any automatic objects initialized within the handler.
16846 //
16847 // We just pretend to initialize the object with itself, then make sure
16848 // it can be destroyed later.
16849 QualType initType = Context.getExceptionObjectType(ExDeclType);
16850
16851 InitializedEntity entity =
16853 InitializationKind initKind =
16855
16856 Expr *opaqueValue =
16857 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16858 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16859 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16860 if (result.isInvalid())
16861 Invalid = true;
16862 else {
16863 // If the constructor used was non-trivial, set this as the
16864 // "initializer".
16865 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16866 if (!construct->getConstructor()->isTrivial()) {
16867 Expr *init = MaybeCreateExprWithCleanups(construct);
16868 ExDecl->setInit(init);
16869 }
16870
16871 // And make sure it's destructable.
16873 }
16874 }
16875 }
16876
16877 if (Invalid)
16878 ExDecl->setInvalidDecl();
16879
16880 return ExDecl;
16881}
16882
16885 bool Invalid = D.isInvalidType();
16886
16887 // Check for unexpanded parameter packs.
16888 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16891 D.getIdentifierLoc());
16892 Invalid = true;
16893 }
16894
16895 const IdentifierInfo *II = D.getIdentifier();
16896 if (NamedDecl *PrevDecl =
16897 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16898 RedeclarationKind::ForVisibleRedeclaration)) {
16899 // The scope should be freshly made just for us. There is just no way
16900 // it contains any previous declaration, except for function parameters in
16901 // a function-try-block's catch statement.
16902 assert(!S->isDeclScope(PrevDecl));
16903 if (isDeclInScope(PrevDecl, CurContext, S)) {
16904 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16905 << D.getIdentifier();
16906 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16907 Invalid = true;
16908 } else if (PrevDecl->isTemplateParameter())
16909 // Maybe we will complain about the shadowed template parameter.
16910 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16911 }
16912
16913 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16914 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16915 << D.getCXXScopeSpec().getRange();
16916 Invalid = true;
16917 }
16918
16920 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16921 if (Invalid)
16922 ExDecl->setInvalidDecl();
16923
16924 // Add the exception declaration into this scope.
16925 if (II)
16926 PushOnScopeChains(ExDecl, S);
16927 else
16928 CurContext->addDecl(ExDecl);
16929
16930 ProcessDeclAttributes(S, ExDecl, D);
16931 return ExDecl;
16932}
16933
16935 Expr *AssertExpr,
16936 Expr *AssertMessageExpr,
16937 SourceLocation RParenLoc) {
16939 return nullptr;
16940
16941 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16942 AssertMessageExpr, RParenLoc, false);
16943}
16944
16945static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
16946 switch (BTK) {
16947 case BuiltinType::Char_S:
16948 case BuiltinType::Char_U:
16949 break;
16950 case BuiltinType::Char8:
16951 OS << "u8";
16952 break;
16953 case BuiltinType::Char16:
16954 OS << 'u';
16955 break;
16956 case BuiltinType::Char32:
16957 OS << 'U';
16958 break;
16959 case BuiltinType::WChar_S:
16960 case BuiltinType::WChar_U:
16961 OS << 'L';
16962 break;
16963 default:
16964 llvm_unreachable("Non-character type");
16965 }
16966}
16967
16968/// Convert character's value, interpreted as a code unit, to a string.
16969/// The value needs to be zero-extended to 32-bits.
16970/// FIXME: This assumes Unicode literal encodings
16971static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
16972 unsigned TyWidth,
16973 SmallVectorImpl<char> &Str) {
16974 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
16975 char *Ptr = Arr;
16976 BuiltinType::Kind K = BTy->getKind();
16977 llvm::raw_svector_ostream OS(Str);
16978
16979 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
16980 // other types.
16981 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
16982 K == BuiltinType::Char8 || Value <= 0x7F) {
16983 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
16984 if (!Escaped.empty())
16985 EscapeStringForDiagnostic(Escaped, Str);
16986 else
16987 OS << static_cast<char>(Value);
16988 return;
16989 }
16990
16991 switch (K) {
16992 case BuiltinType::Char16:
16993 case BuiltinType::Char32:
16994 case BuiltinType::WChar_S:
16995 case BuiltinType::WChar_U: {
16996 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
16997 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
16998 else
16999 OS << "\\x"
17000 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17001 break;
17002 }
17003 default:
17004 llvm_unreachable("Non-character type is passed");
17005 }
17006}
17007
17008/// Convert \V to a string we can present to the user in a diagnostic
17009/// \T is the type of the expression that has been evaluated into \V
17013 if (!V.hasValue())
17014 return false;
17015
17016 switch (V.getKind()) {
17018 if (T->isBooleanType()) {
17019 // Bools are reduced to ints during evaluation, but for
17020 // diagnostic purposes we want to print them as
17021 // true or false.
17022 int64_t BoolValue = V.getInt().getExtValue();
17023 assert((BoolValue == 0 || BoolValue == 1) &&
17024 "Bool type, but value is not 0 or 1");
17025 llvm::raw_svector_ostream OS(Str);
17026 OS << (BoolValue ? "true" : "false");
17027 } else {
17028 llvm::raw_svector_ostream OS(Str);
17029 // Same is true for chars.
17030 // We want to print the character representation for textual types
17031 const auto *BTy = T->getAs<BuiltinType>();
17032 if (BTy) {
17033 switch (BTy->getKind()) {
17034 case BuiltinType::Char_S:
17035 case BuiltinType::Char_U:
17036 case BuiltinType::Char8:
17037 case BuiltinType::Char16:
17038 case BuiltinType::Char32:
17039 case BuiltinType::WChar_S:
17040 case BuiltinType::WChar_U: {
17041 unsigned TyWidth = Context.getIntWidth(T);
17042 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17043 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17044 WriteCharTypePrefix(BTy->getKind(), OS);
17045 OS << '\'';
17046 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17047 OS << "' (0x"
17048 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17049 /*Upper=*/true)
17050 << ", " << V.getInt() << ')';
17051 return true;
17052 }
17053 default:
17054 break;
17055 }
17056 }
17057 V.getInt().toString(Str);
17058 }
17059
17060 break;
17061
17063 V.getFloat().toString(Str);
17064 break;
17065
17067 if (V.isNullPointer()) {
17068 llvm::raw_svector_ostream OS(Str);
17069 OS << "nullptr";
17070 } else
17071 return false;
17072 break;
17073
17075 llvm::raw_svector_ostream OS(Str);
17076 OS << '(';
17077 V.getComplexFloatReal().toString(Str);
17078 OS << " + ";
17079 V.getComplexFloatImag().toString(Str);
17080 OS << "i)";
17081 } break;
17082
17084 llvm::raw_svector_ostream OS(Str);
17085 OS << '(';
17086 V.getComplexIntReal().toString(Str);
17087 OS << " + ";
17088 V.getComplexIntImag().toString(Str);
17089 OS << "i)";
17090 } break;
17091
17092 default:
17093 return false;
17094 }
17095
17096 return true;
17097}
17098
17099/// Some Expression types are not useful to print notes about,
17100/// e.g. literals and values that have already been expanded
17101/// before such as int-valued template parameters.
17102static bool UsefulToPrintExpr(const Expr *E) {
17103 E = E->IgnoreParenImpCasts();
17104 // Literals are pretty easy for humans to understand.
17107 return false;
17108
17109 // These have been substituted from template parameters
17110 // and appear as literals in the static assert error.
17111 if (isa<SubstNonTypeTemplateParmExpr>(E))
17112 return false;
17113
17114 // -5 is also simple to understand.
17115 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17116 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17117
17118 // Only print nested arithmetic operators.
17119 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17120 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17121 BO->isBitwiseOp());
17122
17123 return true;
17124}
17125
17127 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17128 Op && Op->getOpcode() != BO_LOr) {
17129 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17130 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17131
17132 // Ignore comparisons of boolean expressions with a boolean literal.
17133 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17134 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17135 return;
17136
17137 // Don't print obvious expressions.
17138 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17139 return;
17140
17141 struct {
17142 const clang::Expr *Cond;
17144 SmallString<12> ValueString;
17145 bool Print;
17146 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17147 {RHS, Expr::EvalResult(), {}, false}};
17148 for (unsigned I = 0; I < 2; I++) {
17149 const Expr *Side = DiagSide[I].Cond;
17150
17151 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17152
17153 DiagSide[I].Print =
17154 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17155 DiagSide[I].ValueString, Context);
17156 }
17157 if (DiagSide[0].Print && DiagSide[1].Print) {
17158 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17159 << DiagSide[0].ValueString << Op->getOpcodeStr()
17160 << DiagSide[1].ValueString << Op->getSourceRange();
17161 }
17162 }
17163}
17164
17166 std::string &Result,
17167 ASTContext &Ctx,
17168 bool ErrorOnInvalidMessage) {
17169 assert(Message);
17170 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17171 "can't evaluate a dependant static assert message");
17172
17173 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17174 assert(SL->isUnevaluated() && "expected an unevaluated string");
17175 Result.assign(SL->getString().begin(), SL->getString().end());
17176 return true;
17177 }
17178
17179 SourceLocation Loc = Message->getBeginLoc();
17180 QualType T = Message->getType().getNonReferenceType();
17181 auto *RD = T->getAsCXXRecordDecl();
17182 if (!RD) {
17183 Diag(Loc, diag::err_static_assert_invalid_message);
17184 return false;
17185 }
17186
17187 auto FindMember = [&](StringRef Member, bool &Empty,
17188 bool Diag = false) -> std::optional<LookupResult> {
17190 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17191 LookupQualifiedName(MemberLookup, RD);
17192 Empty = MemberLookup.empty();
17193 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17195 if (MemberLookup.empty())
17196 return std::nullopt;
17197 return std::move(MemberLookup);
17198 };
17199
17200 bool SizeNotFound, DataNotFound;
17201 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17202 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17203 if (SizeNotFound || DataNotFound) {
17204 Diag(Loc, diag::err_static_assert_missing_member_function)
17205 << ((SizeNotFound && DataNotFound) ? 2
17206 : SizeNotFound ? 0
17207 : 1);
17208 return false;
17209 }
17210
17211 if (!SizeMember || !DataMember) {
17212 if (!SizeMember)
17213 FindMember("size", SizeNotFound, /*Diag=*/true);
17214 if (!DataMember)
17215 FindMember("data", DataNotFound, /*Diag=*/true);
17216 return false;
17217 }
17218
17219 auto BuildExpr = [&](LookupResult &LR) {
17221 Message, Message->getType(), Message->getBeginLoc(), false,
17222 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17223 if (Res.isInvalid())
17224 return ExprError();
17225 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17226 false, true);
17227 if (Res.isInvalid())
17228 return ExprError();
17229 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17230 return ExprError();
17232 };
17233
17234 ExprResult SizeE = BuildExpr(*SizeMember);
17235 ExprResult DataE = BuildExpr(*DataMember);
17236
17237 QualType SizeT = Context.getSizeType();
17238 QualType ConstCharPtr =
17240
17241 ExprResult EvaluatedSize =
17242 SizeE.isInvalid() ? ExprError()
17244 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17245 if (EvaluatedSize.isInvalid()) {
17246 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17247 return false;
17248 }
17249
17250 ExprResult EvaluatedData =
17251 DataE.isInvalid()
17252 ? ExprError()
17253 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17255 if (EvaluatedData.isInvalid()) {
17256 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17257 return false;
17258 }
17259
17260 if (!ErrorOnInvalidMessage &&
17261 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17262 return true;
17263
17264 Expr::EvalResult Status;
17266 Status.Diag = &Notes;
17267 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17268 EvaluatedData.get(), Ctx, Status) ||
17269 !Notes.empty()) {
17270 Diag(Message->getBeginLoc(),
17271 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17272 : diag::warn_static_assert_message_constexpr);
17273 for (const auto &Note : Notes)
17274 Diag(Note.first, Note.second);
17275 return !ErrorOnInvalidMessage;
17276 }
17277 return true;
17278}
17279
17281 Expr *AssertExpr, Expr *AssertMessage,
17282 SourceLocation RParenLoc,
17283 bool Failed) {
17284 assert(AssertExpr != nullptr && "Expected non-null condition");
17285 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17286 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17287 !AssertMessage->isValueDependent())) &&
17288 !Failed) {
17289 // In a static_assert-declaration, the constant-expression shall be a
17290 // constant expression that can be contextually converted to bool.
17291 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17292 if (Converted.isInvalid())
17293 Failed = true;
17294
17295 ExprResult FullAssertExpr =
17296 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17297 /*DiscardedValue*/ false,
17298 /*IsConstexpr*/ true);
17299 if (FullAssertExpr.isInvalid())
17300 Failed = true;
17301 else
17302 AssertExpr = FullAssertExpr.get();
17303
17304 llvm::APSInt Cond;
17305 Expr *BaseExpr = AssertExpr;
17306 AllowFoldKind FoldKind = NoFold;
17307
17308 if (!getLangOpts().CPlusPlus) {
17309 // In C mode, allow folding as an extension for better compatibility with
17310 // C++ in terms of expressions like static_assert("test") or
17311 // static_assert(nullptr).
17312 FoldKind = AllowFold;
17313 }
17314
17315 if (!Failed && VerifyIntegerConstantExpression(
17316 BaseExpr, &Cond,
17317 diag::err_static_assert_expression_is_not_constant,
17318 FoldKind).isInvalid())
17319 Failed = true;
17320
17321 // If the static_assert passes, only verify that
17322 // the message is grammatically valid without evaluating it.
17323 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17324 std::string Str;
17325 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17326 /*ErrorOnInvalidMessage=*/false);
17327 }
17328
17329 // CWG2518
17330 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17331 // template definition, the declaration has no effect.
17332 bool InTemplateDefinition =
17333 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17334
17335 if (!Failed && !Cond && !InTemplateDefinition) {
17336 SmallString<256> MsgBuffer;
17337 llvm::raw_svector_ostream Msg(MsgBuffer);
17338 bool HasMessage = AssertMessage;
17339 if (AssertMessage) {
17340 std::string Str;
17341 HasMessage =
17343 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17344 !Str.empty();
17345 Msg << Str;
17346 }
17347 Expr *InnerCond = nullptr;
17348 std::string InnerCondDescription;
17349 std::tie(InnerCond, InnerCondDescription) =
17350 findFailedBooleanCondition(Converted.get());
17351 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17352 // Drill down into concept specialization expressions to see why they
17353 // weren't satisfied.
17354 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17355 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17356 ConstraintSatisfaction Satisfaction;
17357 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17358 DiagnoseUnsatisfiedConstraint(Satisfaction);
17359 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17360 && !isa<IntegerLiteral>(InnerCond)) {
17361 Diag(InnerCond->getBeginLoc(),
17362 diag::err_static_assert_requirement_failed)
17363 << InnerCondDescription << !HasMessage << Msg.str()
17364 << InnerCond->getSourceRange();
17365 DiagnoseStaticAssertDetails(InnerCond);
17366 } else {
17367 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17368 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17370 }
17371 Failed = true;
17372 }
17373 } else {
17374 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17375 /*DiscardedValue*/false,
17376 /*IsConstexpr*/true);
17377 if (FullAssertExpr.isInvalid())
17378 Failed = true;
17379 else
17380 AssertExpr = FullAssertExpr.get();
17381 }
17382
17384 AssertExpr, AssertMessage, RParenLoc,
17385 Failed);
17386
17388 return Decl;
17389}
17390
17392 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17393 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17394 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17395 MultiTemplateParamsArg TempParamLists) {
17397
17398 bool IsMemberSpecialization = false;
17399 bool Invalid = false;
17400
17401 if (TemplateParameterList *TemplateParams =
17403 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17404 IsMemberSpecialization, Invalid)) {
17405 if (TemplateParams->size() > 0) {
17406 // This is a declaration of a class template.
17407 if (Invalid)
17408 return true;
17409
17410 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17411 Name, NameLoc, Attr, TemplateParams, AS_public,
17412 /*ModulePrivateLoc=*/SourceLocation(),
17413 FriendLoc, TempParamLists.size() - 1,
17414 TempParamLists.data())
17415 .get();
17416 } else {
17417 // The "template<>" header is extraneous.
17418 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17419 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17420 IsMemberSpecialization = true;
17421 }
17422 }
17423
17424 if (Invalid) return true;
17425
17426 bool isAllExplicitSpecializations = true;
17427 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17428 if (TempParamLists[I]->size()) {
17429 isAllExplicitSpecializations = false;
17430 break;
17431 }
17432 }
17433
17434 // FIXME: don't ignore attributes.
17435
17436 // If it's explicit specializations all the way down, just forget
17437 // about the template header and build an appropriate non-templated
17438 // friend. TODO: for source fidelity, remember the headers.
17440 if (isAllExplicitSpecializations) {
17441 if (SS.isEmpty()) {
17442 bool Owned = false;
17443 bool IsDependent = false;
17444 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17445 Attr, AS_public,
17446 /*ModulePrivateLoc=*/SourceLocation(),
17447 MultiTemplateParamsArg(), Owned, IsDependent,
17448 /*ScopedEnumKWLoc=*/SourceLocation(),
17449 /*ScopedEnumUsesClassTag=*/false,
17450 /*UnderlyingType=*/TypeResult(),
17451 /*IsTypeSpecifier=*/false,
17452 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17453 }
17454
17455 ElaboratedTypeKeyword Keyword
17457 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17458 *Name, NameLoc);
17459 if (T.isNull())
17460 return true;
17461
17463 if (isa<DependentNameType>(T)) {
17466 TL.setElaboratedKeywordLoc(TagLoc);
17467 TL.setQualifierLoc(QualifierLoc);
17468 TL.setNameLoc(NameLoc);
17469 } else {
17471 TL.setElaboratedKeywordLoc(TagLoc);
17472 TL.setQualifierLoc(QualifierLoc);
17473 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17474 }
17475
17477 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17478 EllipsisLoc, TempParamLists);
17479 Friend->setAccess(AS_public);
17481 return Friend;
17482 }
17483
17484 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17485
17486 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17487 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17488 // shall not have been introduced by the template-declaration.
17490 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
17491 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17492 for (UnexpandedParameterPack &U : Unexpanded) {
17493 if (getDepthAndIndex(U).first >= FriendDeclDepth) {
17494 auto *ND = U.first.dyn_cast<NamedDecl *>();
17495 if (!ND)
17496 ND = U.first.get<const TemplateTypeParmType *>()->getDecl();
17497 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
17498 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
17499 return true;
17500 }
17501 }
17502
17503 // Handle the case of a templated-scope friend class. e.g.
17504 // template <class T> class A<T>::B;
17505 // FIXME: we don't support these right now.
17506 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17507 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17512 TL.setElaboratedKeywordLoc(TagLoc);
17514 TL.setNameLoc(NameLoc);
17515
17517 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17518 EllipsisLoc, TempParamLists);
17519 Friend->setAccess(AS_public);
17520 Friend->setUnsupportedFriend(true);
17522 return Friend;
17523}
17524
17526 MultiTemplateParamsArg TempParams,
17527 SourceLocation EllipsisLoc) {
17529 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17530
17531 assert(DS.isFriendSpecified());
17533
17534 // C++ [class.friend]p3:
17535 // A friend declaration that does not declare a function shall have one of
17536 // the following forms:
17537 // friend elaborated-type-specifier ;
17538 // friend simple-type-specifier ;
17539 // friend typename-specifier ;
17540 //
17541 // If the friend keyword isn't first, or if the declarations has any type
17542 // qualifiers, then the declaration doesn't have that form.
17544 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17545 if (DS.getTypeQualifiers()) {
17547 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17549 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17551 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17553 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17555 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17556 }
17557
17558 // Try to convert the decl specifier to a type. This works for
17559 // friend templates because ActOnTag never produces a ClassTemplateDecl
17560 // for a TagUseKind::Friend.
17561 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17563 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17564 QualType T = TSI->getType();
17565 if (TheDeclarator.isInvalidType())
17566 return nullptr;
17567
17568 // If '...' is present, the type must contain an unexpanded parameter
17569 // pack, and vice versa.
17570 bool Invalid = false;
17571 if (EllipsisLoc.isInvalid() &&
17573 return nullptr;
17574 if (EllipsisLoc.isValid() &&
17576 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
17577 << TSI->getTypeLoc().getSourceRange();
17578 Invalid = true;
17579 }
17580
17581 if (!T->isElaboratedTypeSpecifier()) {
17582 if (TempParams.size()) {
17583 // C++23 [dcl.pre]p5:
17584 // In a simple-declaration, the optional init-declarator-list can be
17585 // omitted only when declaring a class or enumeration, that is, when
17586 // the decl-specifier-seq contains either a class-specifier, an
17587 // elaborated-type-specifier with a class-key, or an enum-specifier.
17588 //
17589 // The declaration of a template-declaration or explicit-specialization
17590 // is never a member-declaration, so this must be a simple-declaration
17591 // with no init-declarator-list. Therefore, this is ill-formed.
17592 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17593 return nullptr;
17594 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17595 SmallString<16> InsertionText(" ");
17596 InsertionText += RD->getKindName();
17597
17599 ? diag::warn_cxx98_compat_unelaborated_friend_type
17600 : diag::ext_unelaborated_friend_type)
17601 << (unsigned)RD->getTagKind() << T
17603 InsertionText);
17604 } else {
17605 Diag(FriendLoc, getLangOpts().CPlusPlus11
17606 ? diag::warn_cxx98_compat_nonclass_type_friend
17607 : diag::ext_nonclass_type_friend)
17608 << T << DS.getSourceRange();
17609 }
17610 }
17611
17612 // C++98 [class.friend]p1: A friend of a class is a function
17613 // or class that is not a member of the class . . .
17614 // This is fixed in DR77, which just barely didn't make the C++03
17615 // deadline. It's also a very silly restriction that seriously
17616 // affects inner classes and which nobody else seems to implement;
17617 // thus we never diagnose it, not even in -pedantic.
17618 //
17619 // But note that we could warn about it: it's always useless to
17620 // friend one of your own members (it's not, however, worthless to
17621 // friend a member of an arbitrary specialization of your template).
17622
17623 Decl *D;
17624 if (!TempParams.empty())
17625 // TODO: Support variadic friend template decls?
17626 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17627 FriendLoc);
17628 else
17630 TSI, FriendLoc, EllipsisLoc);
17631
17632 if (!D)
17633 return nullptr;
17634
17637
17638 if (Invalid)
17639 D->setInvalidDecl();
17640
17641 return D;
17642}
17643
17645 MultiTemplateParamsArg TemplateParams) {
17646 const DeclSpec &DS = D.getDeclSpec();
17647
17648 assert(DS.isFriendSpecified());
17650
17651 SourceLocation Loc = D.getIdentifierLoc();
17653
17654 // C++ [class.friend]p1
17655 // A friend of a class is a function or class....
17656 // Note that this sees through typedefs, which is intended.
17657 // It *doesn't* see through dependent types, which is correct
17658 // according to [temp.arg.type]p3:
17659 // If a declaration acquires a function type through a
17660 // type dependent on a template-parameter and this causes
17661 // a declaration that does not use the syntactic form of a
17662 // function declarator to have a function type, the program
17663 // is ill-formed.
17664 if (!TInfo->getType()->isFunctionType()) {
17665 Diag(Loc, diag::err_unexpected_friend);
17666
17667 // It might be worthwhile to try to recover by creating an
17668 // appropriate declaration.
17669 return nullptr;
17670 }
17671
17672 // C++ [namespace.memdef]p3
17673 // - If a friend declaration in a non-local class first declares a
17674 // class or function, the friend class or function is a member
17675 // of the innermost enclosing namespace.
17676 // - The name of the friend is not found by simple name lookup
17677 // until a matching declaration is provided in that namespace
17678 // scope (either before or after the class declaration granting
17679 // friendship).
17680 // - If a friend function is called, its name may be found by the
17681 // name lookup that considers functions from namespaces and
17682 // classes associated with the types of the function arguments.
17683 // - When looking for a prior declaration of a class or a function
17684 // declared as a friend, scopes outside the innermost enclosing
17685 // namespace scope are not considered.
17686
17687 CXXScopeSpec &SS = D.getCXXScopeSpec();
17689 assert(NameInfo.getName());
17690
17691 // Check for unexpanded parameter packs.
17695 return nullptr;
17696
17697 // The context we found the declaration in, or in which we should
17698 // create the declaration.
17699 DeclContext *DC;
17700 Scope *DCScope = S;
17701 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17702 RedeclarationKind::ForExternalRedeclaration);
17703
17704 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17705
17706 // There are five cases here.
17707 // - There's no scope specifier and we're in a local class. Only look
17708 // for functions declared in the immediately-enclosing block scope.
17709 // We recover from invalid scope qualifiers as if they just weren't there.
17710 FunctionDecl *FunctionContainingLocalClass = nullptr;
17711 if ((SS.isInvalid() || !SS.isSet()) &&
17712 (FunctionContainingLocalClass =
17713 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17714 // C++11 [class.friend]p11:
17715 // If a friend declaration appears in a local class and the name
17716 // specified is an unqualified name, a prior declaration is
17717 // looked up without considering scopes that are outside the
17718 // innermost enclosing non-class scope. For a friend function
17719 // declaration, if there is no prior declaration, the program is
17720 // ill-formed.
17721
17722 // Find the innermost enclosing non-class scope. This is the block
17723 // scope containing the local class definition (or for a nested class,
17724 // the outer local class).
17725 DCScope = S->getFnParent();
17726
17727 // Look up the function name in the scope.
17729 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17730
17731 if (!Previous.empty()) {
17732 // All possible previous declarations must have the same context:
17733 // either they were declared at block scope or they are members of
17734 // one of the enclosing local classes.
17735 DC = Previous.getRepresentativeDecl()->getDeclContext();
17736 } else {
17737 // This is ill-formed, but provide the context that we would have
17738 // declared the function in, if we were permitted to, for error recovery.
17739 DC = FunctionContainingLocalClass;
17740 }
17742
17743 // - There's no scope specifier, in which case we just go to the
17744 // appropriate scope and look for a function or function template
17745 // there as appropriate.
17746 } else if (SS.isInvalid() || !SS.isSet()) {
17747 // C++11 [namespace.memdef]p3:
17748 // If the name in a friend declaration is neither qualified nor
17749 // a template-id and the declaration is a function or an
17750 // elaborated-type-specifier, the lookup to determine whether
17751 // the entity has been previously declared shall not consider
17752 // any scopes outside the innermost enclosing namespace.
17753
17754 // Find the appropriate context according to the above.
17755 DC = CurContext;
17756
17757 // Skip class contexts. If someone can cite chapter and verse
17758 // for this behavior, that would be nice --- it's what GCC and
17759 // EDG do, and it seems like a reasonable intent, but the spec
17760 // really only says that checks for unqualified existing
17761 // declarations should stop at the nearest enclosing namespace,
17762 // not that they should only consider the nearest enclosing
17763 // namespace.
17764 while (DC->isRecord())
17765 DC = DC->getParent();
17766
17767 DeclContext *LookupDC = DC->getNonTransparentContext();
17768 while (true) {
17769 LookupQualifiedName(Previous, LookupDC);
17770
17771 if (!Previous.empty()) {
17772 DC = LookupDC;
17773 break;
17774 }
17775
17776 if (isTemplateId) {
17777 if (isa<TranslationUnitDecl>(LookupDC)) break;
17778 } else {
17779 if (LookupDC->isFileContext()) break;
17780 }
17781 LookupDC = LookupDC->getParent();
17782 }
17783
17784 DCScope = getScopeForDeclContext(S, DC);
17785
17786 // - There's a non-dependent scope specifier, in which case we
17787 // compute it and do a previous lookup there for a function
17788 // or function template.
17789 } else if (!SS.getScopeRep()->isDependent()) {
17790 DC = computeDeclContext(SS);
17791 if (!DC) return nullptr;
17792
17793 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17794
17796
17797 // C++ [class.friend]p1: A friend of a class is a function or
17798 // class that is not a member of the class . . .
17799 if (DC->Equals(CurContext))
17802 diag::warn_cxx98_compat_friend_is_member :
17803 diag::err_friend_is_member);
17804
17805 // - There's a scope specifier that does not match any template
17806 // parameter lists, in which case we use some arbitrary context,
17807 // create a method or method template, and wait for instantiation.
17808 // - There's a scope specifier that does match some template
17809 // parameter lists, which we don't handle right now.
17810 } else {
17811 DC = CurContext;
17812 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17813 }
17814
17815 if (!DC->isRecord()) {
17816 int DiagArg = -1;
17817 switch (D.getName().getKind()) {
17820 DiagArg = 0;
17821 break;
17823 DiagArg = 1;
17824 break;
17826 DiagArg = 2;
17827 break;
17829 DiagArg = 3;
17830 break;
17836 break;
17837 }
17838 // This implies that it has to be an operator or function.
17839 if (DiagArg >= 0) {
17840 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17841 return nullptr;
17842 }
17843 }
17844
17845 // FIXME: This is an egregious hack to cope with cases where the scope stack
17846 // does not contain the declaration context, i.e., in an out-of-line
17847 // definition of a class.
17848 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17849 if (!DCScope) {
17850 FakeDCScope.setEntity(DC);
17851 DCScope = &FakeDCScope;
17852 }
17853
17854 bool AddToScope = true;
17855 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17856 TemplateParams, AddToScope);
17857 if (!ND) return nullptr;
17858
17859 assert(ND->getLexicalDeclContext() == CurContext);
17860
17861 // If we performed typo correction, we might have added a scope specifier
17862 // and changed the decl context.
17863 DC = ND->getDeclContext();
17864
17865 // Add the function declaration to the appropriate lookup tables,
17866 // adjusting the redeclarations list as necessary. We don't
17867 // want to do this yet if the friending class is dependent.
17868 //
17869 // Also update the scope-based lookup if the target context's
17870 // lookup context is in lexical scope.
17872 DC = DC->getRedeclContext();
17874 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17875 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17876 }
17877
17879 D.getIdentifierLoc(), ND,
17880 DS.getFriendSpecLoc());
17881 FrD->setAccess(AS_public);
17882 CurContext->addDecl(FrD);
17883
17884 if (ND->isInvalidDecl()) {
17885 FrD->setInvalidDecl();
17886 } else {
17887 if (DC->isRecord()) CheckFriendAccess(ND);
17888
17889 FunctionDecl *FD;
17890 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17891 FD = FTD->getTemplatedDecl();
17892 else
17893 FD = cast<FunctionDecl>(ND);
17894
17895 // C++ [class.friend]p6:
17896 // A function may be defined in a friend declaration of a class if and
17897 // only if the class is a non-local class, and the function name is
17898 // unqualified.
17899 if (D.isFunctionDefinition()) {
17900 // Qualified friend function definition.
17901 if (SS.isNotEmpty()) {
17902 // FIXME: We should only do this if the scope specifier names the
17903 // innermost enclosing namespace; otherwise the fixit changes the
17904 // meaning of the code.
17906 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17907
17908 DB << SS.getScopeRep();
17909 if (DC->isFileContext())
17911
17912 // Friend function defined in a local class.
17913 } else if (FunctionContainingLocalClass) {
17914 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17915
17916 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
17917 // a template-id, the function name is not unqualified because these is
17918 // no name. While the wording requires some reading in-between the
17919 // lines, GCC, MSVC, and EDG all consider a friend function
17920 // specialization definitions // to be de facto explicit specialization
17921 // and diagnose them as such.
17922 } else if (isTemplateId) {
17923 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
17924 }
17925 }
17926
17927 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17928 // default argument expression, that declaration shall be a definition
17929 // and shall be the only declaration of the function or function
17930 // template in the translation unit.
17932 // We can't look at FD->getPreviousDecl() because it may not have been set
17933 // if we're in a dependent context. If the function is known to be a
17934 // redeclaration, we will have narrowed Previous down to the right decl.
17935 if (D.isRedeclaration()) {
17936 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17937 Diag(Previous.getRepresentativeDecl()->getLocation(),
17938 diag::note_previous_declaration);
17939 } else if (!D.isFunctionDefinition())
17940 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17941 }
17942
17943 // Mark templated-scope function declarations as unsupported.
17944 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17945 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17946 << SS.getScopeRep() << SS.getRange()
17947 << cast<CXXRecordDecl>(CurContext);
17948 FrD->setUnsupportedFriend(true);
17949 }
17950 }
17951
17953
17954 return ND;
17955}
17956
17958 StringLiteral *Message) {
17960
17961 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17962 if (!Fn) {
17963 Diag(DelLoc, diag::err_deleted_non_function);
17964 return;
17965 }
17966
17967 // Deleted function does not have a body.
17968 Fn->setWillHaveBody(false);
17969
17970 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17971 // Don't consider the implicit declaration we generate for explicit
17972 // specializations. FIXME: Do not generate these implicit declarations.
17973 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17974 Prev->getPreviousDecl()) &&
17975 !Prev->isDefined()) {
17976 Diag(DelLoc, diag::err_deleted_decl_not_first);
17977 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17978 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17979 : diag::note_previous_declaration);
17980 // We can't recover from this; the declaration might have already
17981 // been used.
17982 Fn->setInvalidDecl();
17983 return;
17984 }
17985
17986 // To maintain the invariant that functions are only deleted on their first
17987 // declaration, mark the implicitly-instantiated declaration of the
17988 // explicitly-specialized function as deleted instead of marking the
17989 // instantiated redeclaration.
17990 Fn = Fn->getCanonicalDecl();
17991 }
17992
17993 // dllimport/dllexport cannot be deleted.
17994 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17995 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17996 Fn->setInvalidDecl();
17997 }
17998
17999 // C++11 [basic.start.main]p3:
18000 // A program that defines main as deleted [...] is ill-formed.
18001 if (Fn->isMain())
18002 Diag(DelLoc, diag::err_deleted_main);
18003
18004 // C++11 [dcl.fct.def.delete]p4:
18005 // A deleted function is implicitly inline.
18006 Fn->setImplicitlyInline();
18007 Fn->setDeletedAsWritten(true, Message);
18008}
18009
18011 if (!Dcl || Dcl->isInvalidDecl())
18012 return;
18013
18014 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18015 if (!FD) {
18016 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18017 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18018 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18019 return;
18020 }
18021 }
18022
18023 Diag(DefaultLoc, diag::err_default_special_members)
18024 << getLangOpts().CPlusPlus20;
18025 return;
18026 }
18027
18028 // Reject if this can't possibly be a defaultable function.
18030 if (!DefKind &&
18031 // A dependent function that doesn't locally look defaultable can
18032 // still instantiate to a defaultable function if it's a constructor
18033 // or assignment operator.
18034 (!FD->isDependentContext() ||
18035 (!isa<CXXConstructorDecl>(FD) &&
18036 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18037 Diag(DefaultLoc, diag::err_default_special_members)
18038 << getLangOpts().CPlusPlus20;
18039 return;
18040 }
18041
18042 // Issue compatibility warning. We already warned if the operator is
18043 // 'operator<=>' when parsing the '<=>' token.
18044 if (DefKind.isComparison() &&
18046 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18047 ? diag::warn_cxx17_compat_defaulted_comparison
18048 : diag::ext_defaulted_comparison);
18049 }
18050
18051 FD->setDefaulted();
18052 FD->setExplicitlyDefaulted();
18053 FD->setDefaultLoc(DefaultLoc);
18054
18055 // Defer checking functions that are defaulted in a dependent context.
18056 if (FD->isDependentContext())
18057 return;
18058
18059 // Unset that we will have a body for this function. We might not,
18060 // if it turns out to be trivial, and we don't need this marking now
18061 // that we've marked it as defaulted.
18062 FD->setWillHaveBody(false);
18063
18064 if (DefKind.isComparison()) {
18065 // If this comparison's defaulting occurs within the definition of its
18066 // lexical class context, we have to do the checking when complete.
18067 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18068 if (!RD->isCompleteDefinition())
18069 return;
18070 }
18071
18072 // If this member fn was defaulted on its first declaration, we will have
18073 // already performed the checking in CheckCompletedCXXClass. Such a
18074 // declaration doesn't trigger an implicit definition.
18075 if (isa<CXXMethodDecl>(FD)) {
18076 const FunctionDecl *Primary = FD;
18077 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18078 // Ask the template instantiation pattern that actually had the
18079 // '= default' on it.
18080 Primary = Pattern;
18081 if (Primary->getCanonicalDecl()->isDefaulted())
18082 return;
18083 }
18084
18085 if (DefKind.isComparison()) {
18086 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18087 FD->setInvalidDecl();
18088 else
18089 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18090 } else {
18091 auto *MD = cast<CXXMethodDecl>(FD);
18092
18094 DefaultLoc))
18095 MD->setInvalidDecl();
18096 else
18097 DefineDefaultedFunction(*this, MD, DefaultLoc);
18098 }
18099}
18100
18102 for (Stmt *SubStmt : S->children()) {
18103 if (!SubStmt)
18104 continue;
18105 if (isa<ReturnStmt>(SubStmt))
18106 Self.Diag(SubStmt->getBeginLoc(),
18107 diag::err_return_in_constructor_handler);
18108 if (!isa<Expr>(SubStmt))
18109 SearchForReturnInStmt(Self, SubStmt);
18110 }
18111}
18112
18114 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18115 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18116 SearchForReturnInStmt(*this, Handler);
18117 }
18118}
18119
18121 StringLiteral *DeletedMessage) {
18122 switch (BodyKind) {
18123 case FnBodyKind::Delete:
18124 SetDeclDeleted(D, Loc, DeletedMessage);
18125 break;
18128 break;
18129 case FnBodyKind::Other:
18130 llvm_unreachable(
18131 "Parsed function body should be '= delete;' or '= default;'");
18132 }
18133}
18134
18136 const CXXMethodDecl *Old) {
18137 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18138 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18139
18140 if (OldFT->hasExtParameterInfos()) {
18141 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18142 // A parameter of the overriding method should be annotated with noescape
18143 // if the corresponding parameter of the overridden method is annotated.
18144 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18145 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18146 Diag(New->getParamDecl(I)->getLocation(),
18147 diag::warn_overriding_method_missing_noescape);
18148 Diag(Old->getParamDecl(I)->getLocation(),
18149 diag::note_overridden_marked_noescape);
18150 }
18151 }
18152
18153 // SME attributes must match when overriding a function declaration.
18154 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18155 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18156 << New << New->getType() << Old->getType();
18157 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18158 return true;
18159 }
18160
18161 // Virtual overrides must have the same code_seg.
18162 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18163 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18164 if ((NewCSA || OldCSA) &&
18165 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18166 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18167 Diag(Old->getLocation(), diag::note_previous_declaration);
18168 return true;
18169 }
18170
18171 // Virtual overrides: check for matching effects.
18173 const auto OldFX = Old->getFunctionEffects();
18174 const auto NewFXOrig = New->getFunctionEffects();
18175
18176 if (OldFX != NewFXOrig) {
18177 FunctionEffectSet NewFX(NewFXOrig);
18178 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
18180 for (const auto &Diff : Diffs) {
18181 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18183 break;
18185 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18186 << Diff.effectName();
18187 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18188 << Old->getReturnTypeSourceRange();
18189 break;
18191 NewFX.insert(Diff.Old, Errs);
18192 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18193 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18195 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18196 NewFT->getParamTypes(), EPI);
18197 New->setType(ModQT);
18198 break;
18199 }
18200 }
18201 }
18202 if (!Errs.empty())
18204 Old->getLocation());
18205 }
18206 }
18207
18208 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18209
18210 // If the calling conventions match, everything is fine
18211 if (NewCC == OldCC)
18212 return false;
18213
18214 // If the calling conventions mismatch because the new function is static,
18215 // suppress the calling convention mismatch error; the error about static
18216 // function override (err_static_overrides_virtual from
18217 // Sema::CheckFunctionDeclaration) is more clear.
18218 if (New->getStorageClass() == SC_Static)
18219 return false;
18220
18221 Diag(New->getLocation(),
18222 diag::err_conflicting_overriding_cc_attributes)
18223 << New->getDeclName() << New->getType() << Old->getType();
18224 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18225 return true;
18226}
18227
18229 const CXXMethodDecl *Old) {
18230 // CWG2553
18231 // A virtual function shall not be an explicit object member function.
18233 return true;
18234 Diag(New->getParamDecl(0)->getBeginLoc(),
18235 diag::err_explicit_object_parameter_nonmember)
18236 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18237 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18238 New->setInvalidDecl();
18239 return false;
18240}
18241
18243 const CXXMethodDecl *Old) {
18244 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18245 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18246
18247 if (Context.hasSameType(NewTy, OldTy) ||
18248 NewTy->isDependentType() || OldTy->isDependentType())
18249 return false;
18250
18251 // Check if the return types are covariant
18252 QualType NewClassTy, OldClassTy;
18253
18254 /// Both types must be pointers or references to classes.
18255 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18256 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18257 NewClassTy = NewPT->getPointeeType();
18258 OldClassTy = OldPT->getPointeeType();
18259 }
18260 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18261 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18262 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18263 NewClassTy = NewRT->getPointeeType();
18264 OldClassTy = OldRT->getPointeeType();
18265 }
18266 }
18267 }
18268
18269 // The return types aren't either both pointers or references to a class type.
18270 if (NewClassTy.isNull()) {
18271 Diag(New->getLocation(),
18272 diag::err_different_return_type_for_overriding_virtual_function)
18273 << New->getDeclName() << NewTy << OldTy
18274 << New->getReturnTypeSourceRange();
18275 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18276 << Old->getReturnTypeSourceRange();
18277
18278 return true;
18279 }
18280
18281 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18282 // C++14 [class.virtual]p8:
18283 // If the class type in the covariant return type of D::f differs from
18284 // that of B::f, the class type in the return type of D::f shall be
18285 // complete at the point of declaration of D::f or shall be the class
18286 // type D.
18287 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18288 if (!RT->isBeingDefined() &&
18289 RequireCompleteType(New->getLocation(), NewClassTy,
18290 diag::err_covariant_return_incomplete,
18291 New->getDeclName()))
18292 return true;
18293 }
18294
18295 // Check if the new class derives from the old class.
18296 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18297 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18298 << New->getDeclName() << NewTy << OldTy
18299 << New->getReturnTypeSourceRange();
18300 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18301 << Old->getReturnTypeSourceRange();
18302 return true;
18303 }
18304
18305 // Check if we the conversion from derived to base is valid.
18307 NewClassTy, OldClassTy,
18308 diag::err_covariant_return_inaccessible_base,
18309 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18311 New->getDeclName(), nullptr)) {
18312 // FIXME: this note won't trigger for delayed access control
18313 // diagnostics, and it's impossible to get an undelayed error
18314 // here from access control during the original parse because
18315 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18316 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18317 << Old->getReturnTypeSourceRange();
18318 return true;
18319 }
18320 }
18321
18322 // The qualifiers of the return types must be the same.
18323 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18324 Diag(New->getLocation(),
18325 diag::err_covariant_return_type_different_qualifications)
18326 << New->getDeclName() << NewTy << OldTy
18327 << New->getReturnTypeSourceRange();
18328 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18329 << Old->getReturnTypeSourceRange();
18330 return true;
18331 }
18332
18333
18334 // The new class type must have the same or less qualifiers as the old type.
18335 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18336 Diag(New->getLocation(),
18337 diag::err_covariant_return_type_class_type_more_qualified)
18338 << New->getDeclName() << NewTy << OldTy
18339 << New->getReturnTypeSourceRange();
18340 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18341 << Old->getReturnTypeSourceRange();
18342 return true;
18343 }
18344
18345 return false;
18346}
18347
18349 SourceLocation EndLoc = InitRange.getEnd();
18350 if (EndLoc.isValid())
18351 Method->setRangeEnd(EndLoc);
18352
18353 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18354 Method->setIsPureVirtual();
18355 return false;
18356 }
18357
18358 if (!Method->isInvalidDecl())
18359 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18360 << Method->getDeclName() << InitRange;
18361 return true;
18362}
18363
18365 if (D->getFriendObjectKind())
18366 Diag(D->getLocation(), diag::err_pure_friend);
18367 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18368 CheckPureMethod(M, ZeroLoc);
18369 else
18370 Diag(D->getLocation(), diag::err_illegal_initializer);
18371}
18372
18373/// Invoked when we are about to parse an initializer for the declaration
18374/// 'Dcl'.
18375///
18376/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18377/// static data member of class X, names should be looked up in the scope of
18378/// class X. If the declaration had a scope specifier, a scope will have
18379/// been created and passed in for this purpose. Otherwise, S will be null.
18381 assert(D && !D->isInvalidDecl());
18382
18383 // We will always have a nested name specifier here, but this declaration
18384 // might not be out of line if the specifier names the current namespace:
18385 // extern int n;
18386 // int ::n = 0;
18387 if (S && D->isOutOfLine())
18389
18392}
18393
18395 assert(D);
18396
18397 if (S && D->isOutOfLine())
18399
18400 if (getLangOpts().CPlusPlus23) {
18401 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18402 // [...]
18403 // - the initializer of a variable that is usable in constant expressions or
18404 // has constant initialization.
18405 if (auto *VD = dyn_cast<VarDecl>(D);
18408 // An expression or conversion is in an 'immediate function context' if it
18409 // is potentially evaluated and either:
18410 // [...]
18411 // - it is a subexpression of a manifestly constant-evaluated expression
18412 // or conversion.
18413 ExprEvalContexts.back().InImmediateFunctionContext = true;
18414 }
18415 }
18416
18417 // Unless the initializer is in an immediate function context (as determined
18418 // above), this will evaluate all contained immediate function calls as
18419 // constant expressions. If the initializer IS an immediate function context,
18420 // the initializer has been determined to be a constant expression, and all
18421 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18422 // it was a constant expression).
18424}
18425
18427 // C++ 6.4p2:
18428 // The declarator shall not specify a function or an array.
18429 // The type-specifier-seq shall not contain typedef and shall not declare a
18430 // new class or enumeration.
18431 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18432 "Parser allowed 'typedef' as storage class of condition decl.");
18433
18434 Decl *Dcl = ActOnDeclarator(S, D);
18435 if (!Dcl)
18436 return true;
18437
18438 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18439 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18440 << D.getSourceRange();
18441 return true;
18442 }
18443
18444 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18445 VD->setCXXCondDecl();
18446
18447 return Dcl;
18448}
18449
18451 if (!ExternalSource)
18452 return;
18453
18455 ExternalSource->ReadUsedVTables(VTables);
18457 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18458 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18459 = VTablesUsed.find(VTables[I].Record);
18460 // Even if a definition wasn't required before, it may be required now.
18461 if (Pos != VTablesUsed.end()) {
18462 if (!Pos->second && VTables[I].DefinitionRequired)
18463 Pos->second = true;
18464 continue;
18465 }
18466
18467 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18468 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18469 }
18470
18471 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18472}
18473
18475 bool DefinitionRequired) {
18476 // Ignore any vtable uses in unevaluated operands or for classes that do
18477 // not have a vtable.
18478 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18480 return;
18481 // Do not mark as used if compiling for the device outside of the target
18482 // region.
18483 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18484 !OpenMP().isInOpenMPDeclareTargetContext() &&
18485 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18486 if (!DefinitionRequired)
18488 return;
18489 }
18490
18491 // Try to insert this class into the map.
18493 Class = Class->getCanonicalDecl();
18494 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18495 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18496 if (!Pos.second) {
18497 // If we already had an entry, check to see if we are promoting this vtable
18498 // to require a definition. If so, we need to reappend to the VTableUses
18499 // list, since we may have already processed the first entry.
18500 if (DefinitionRequired && !Pos.first->second) {
18501 Pos.first->second = true;
18502 } else {
18503 // Otherwise, we can early exit.
18504 return;
18505 }
18506 } else {
18507 // The Microsoft ABI requires that we perform the destructor body
18508 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18509 // the deleting destructor is emitted with the vtable, not with the
18510 // destructor definition as in the Itanium ABI.
18512 CXXDestructorDecl *DD = Class->getDestructor();
18513 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18514 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18515 // If this is an out-of-line declaration, marking it referenced will
18516 // not do anything. Manually call CheckDestructor to look up operator
18517 // delete().
18518 ContextRAII SavedContext(*this, DD);
18519 CheckDestructor(DD);
18520 } else {
18521 MarkFunctionReferenced(Loc, Class->getDestructor());
18522 }
18523 }
18524 }
18525 }
18526
18527 // Local classes need to have their virtual members marked
18528 // immediately. For all other classes, we mark their virtual members
18529 // at the end of the translation unit.
18530 if (Class->isLocalClass())
18531 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18532 else
18533 VTableUses.push_back(std::make_pair(Class, Loc));
18534}
18535
18538 if (VTableUses.empty())
18539 return false;
18540
18541 // Note: The VTableUses vector could grow as a result of marking
18542 // the members of a class as "used", so we check the size each
18543 // time through the loop and prefer indices (which are stable) to
18544 // iterators (which are not).
18545 bool DefinedAnything = false;
18546 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18547 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18548 if (!Class)
18549 continue;
18551 Class->getTemplateSpecializationKind();
18552
18553 SourceLocation Loc = VTableUses[I].second;
18554
18555 bool DefineVTable = true;
18556
18557 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18558 // V-tables for non-template classes with an owning module are always
18559 // uniquely emitted in that module.
18560 if (Class->isInCurrentModuleUnit()) {
18561 DefineVTable = true;
18562 } else if (KeyFunction && !KeyFunction->hasBody()) {
18563 // If this class has a key function, but that key function is
18564 // defined in another translation unit, we don't need to emit the
18565 // vtable even though we're using it.
18566 // The key function is in another translation unit.
18567 DefineVTable = false;
18569 KeyFunction->getTemplateSpecializationKind();
18572 "Instantiations don't have key functions");
18573 (void)TSK;
18574 } else if (!KeyFunction) {
18575 // If we have a class with no key function that is the subject
18576 // of an explicit instantiation declaration, suppress the
18577 // vtable; it will live with the explicit instantiation
18578 // definition.
18579 bool IsExplicitInstantiationDeclaration =
18581 for (auto *R : Class->redecls()) {
18583 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18585 IsExplicitInstantiationDeclaration = true;
18586 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18587 IsExplicitInstantiationDeclaration = false;
18588 break;
18589 }
18590 }
18591
18592 if (IsExplicitInstantiationDeclaration)
18593 DefineVTable = false;
18594 }
18595
18596 // The exception specifications for all virtual members may be needed even
18597 // if we are not providing an authoritative form of the vtable in this TU.
18598 // We may choose to emit it available_externally anyway.
18599 if (!DefineVTable) {
18601 continue;
18602 }
18603
18604 // Mark all of the virtual members of this class as referenced, so
18605 // that we can build a vtable. Then, tell the AST consumer that a
18606 // vtable for this class is required.
18607 DefinedAnything = true;
18609 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18610 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
18612
18613 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18614 // no key function or the key function is inlined. Don't warn in C++ ABIs
18615 // that lack key functions, since the user won't be able to make one.
18617 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18619 const FunctionDecl *KeyFunctionDef = nullptr;
18620 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18621 KeyFunctionDef->isInlined()))
18622 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18623 }
18624 }
18625 VTableUses.clear();
18626
18627 return DefinedAnything;
18628}
18629
18631 const CXXRecordDecl *RD) {
18632 for (const auto *I : RD->methods())
18633 if (I->isVirtual() && !I->isPureVirtual())
18634 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18635}
18636
18638 const CXXRecordDecl *RD,
18639 bool ConstexprOnly) {
18640 // Mark all functions which will appear in RD's vtable as used.
18641 CXXFinalOverriderMap FinalOverriders;
18642 RD->getFinalOverriders(FinalOverriders);
18643 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18644 E = FinalOverriders.end();
18645 I != E; ++I) {
18646 for (OverridingMethods::const_iterator OI = I->second.begin(),
18647 OE = I->second.end();
18648 OI != OE; ++OI) {
18649 assert(OI->second.size() > 0 && "no final overrider");
18650 CXXMethodDecl *Overrider = OI->second.front().Method;
18651
18652 // C++ [basic.def.odr]p2:
18653 // [...] A virtual member function is used if it is not pure. [...]
18654 if (!Overrider->isPureVirtual() &&
18655 (!ConstexprOnly || Overrider->isConstexpr()))
18656 MarkFunctionReferenced(Loc, Overrider);
18657 }
18658 }
18659
18660 // Only classes that have virtual bases need a VTT.
18661 if (RD->getNumVBases() == 0)
18662 return;
18663
18664 for (const auto &I : RD->bases()) {
18665 const auto *Base =
18666 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18667 if (Base->getNumVBases() == 0)
18668 continue;
18670 }
18671}
18672
18673static
18678 Sema &S) {
18679 if (Ctor->isInvalidDecl())
18680 return;
18681
18683
18684 // Target may not be determinable yet, for instance if this is a dependent
18685 // call in an uninstantiated template.
18686 if (Target) {
18687 const FunctionDecl *FNTarget = nullptr;
18688 (void)Target->hasBody(FNTarget);
18689 Target = const_cast<CXXConstructorDecl*>(
18690 cast_or_null<CXXConstructorDecl>(FNTarget));
18691 }
18692
18693 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18694 // Avoid dereferencing a null pointer here.
18695 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18696
18697 if (!Current.insert(Canonical).second)
18698 return;
18699
18700 // We know that beyond here, we aren't chaining into a cycle.
18701 if (!Target || !Target->isDelegatingConstructor() ||
18702 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18703 Valid.insert(Current.begin(), Current.end());
18704 Current.clear();
18705 // We've hit a cycle.
18706 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18707 Current.count(TCanonical)) {
18708 // If we haven't diagnosed this cycle yet, do so now.
18709 if (!Invalid.count(TCanonical)) {
18710 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18711 diag::warn_delegating_ctor_cycle)
18712 << Ctor;
18713
18714 // Don't add a note for a function delegating directly to itself.
18715 if (TCanonical != Canonical)
18716 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18717
18719 while (C->getCanonicalDecl() != Canonical) {
18720 const FunctionDecl *FNTarget = nullptr;
18721 (void)C->getTargetConstructor()->hasBody(FNTarget);
18722 assert(FNTarget && "Ctor cycle through bodiless function");
18723
18724 C = const_cast<CXXConstructorDecl*>(
18725 cast<CXXConstructorDecl>(FNTarget));
18726 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18727 }
18728 }
18729
18730 Invalid.insert(Current.begin(), Current.end());
18731 Current.clear();
18732 } else {
18733 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18734 }
18735}
18736
18737
18740
18741 for (DelegatingCtorDeclsType::iterator
18744 I != E; ++I)
18745 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18746
18747 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18748 (*CI)->setInvalidDecl();
18749}
18750
18751namespace {
18752 /// AST visitor that finds references to the 'this' expression.
18753 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18754 Sema &S;
18755
18756 public:
18757 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18758
18759 bool VisitCXXThisExpr(CXXThisExpr *E) {
18760 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18761 << E->isImplicit();
18762 return false;
18763 }
18764 };
18765}
18766
18768 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18769 if (!TSInfo)
18770 return false;
18771
18772 TypeLoc TL = TSInfo->getTypeLoc();
18774 if (!ProtoTL)
18775 return false;
18776
18777 // C++11 [expr.prim.general]p3:
18778 // [The expression this] shall not appear before the optional
18779 // cv-qualifier-seq and it shall not appear within the declaration of a
18780 // static member function (although its type and value category are defined
18781 // within a static member function as they are within a non-static member
18782 // function). [ Note: this is because declaration matching does not occur
18783 // until the complete declarator is known. - end note ]
18784 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18785 FindCXXThisExpr Finder(*this);
18786
18787 // If the return type came after the cv-qualifier-seq, check it now.
18788 if (Proto->hasTrailingReturn() &&
18789 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18790 return true;
18791
18792 // Check the exception specification.
18794 return true;
18795
18796 // Check the trailing requires clause
18797 if (Expr *E = Method->getTrailingRequiresClause())
18798 if (!Finder.TraverseStmt(E))
18799 return true;
18800
18802}
18803
18805 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18806 if (!TSInfo)
18807 return false;
18808
18809 TypeLoc TL = TSInfo->getTypeLoc();
18811 if (!ProtoTL)
18812 return false;
18813
18814 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18815 FindCXXThisExpr Finder(*this);
18816
18817 switch (Proto->getExceptionSpecType()) {
18818 case EST_Unparsed:
18819 case EST_Uninstantiated:
18820 case EST_Unevaluated:
18821 case EST_BasicNoexcept:
18822 case EST_NoThrow:
18823 case EST_DynamicNone:
18824 case EST_MSAny:
18825 case EST_None:
18826 break;
18827
18829 case EST_NoexceptFalse:
18830 case EST_NoexceptTrue:
18831 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18832 return true;
18833 [[fallthrough]];
18834
18835 case EST_Dynamic:
18836 for (const auto &E : Proto->exceptions()) {
18837 if (!Finder.TraverseType(E))
18838 return true;
18839 }
18840 break;
18841 }
18842
18843 return false;
18844}
18845
18847 FindCXXThisExpr Finder(*this);
18848
18849 // Check attributes.
18850 for (const auto *A : Method->attrs()) {
18851 // FIXME: This should be emitted by tblgen.
18852 Expr *Arg = nullptr;
18853 ArrayRef<Expr *> Args;
18854 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18855 Arg = G->getArg();
18856 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18857 Arg = G->getArg();
18858 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18859 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18860 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18861 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18862 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18863 Arg = ETLF->getSuccessValue();
18864 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18865 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18866 Arg = STLF->getSuccessValue();
18867 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18868 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18869 Arg = LR->getArg();
18870 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18871 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18872 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18873 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18874 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18875 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18876 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18877 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18878 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18879 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18880
18881 if (Arg && !Finder.TraverseStmt(Arg))
18882 return true;
18883
18884 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18885 if (!Finder.TraverseStmt(Args[I]))
18886 return true;
18887 }
18888 }
18889
18890 return false;
18891}
18892
18894 bool IsTopLevel, ExceptionSpecificationType EST,
18895 ArrayRef<ParsedType> DynamicExceptions,
18896 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18897 SmallVectorImpl<QualType> &Exceptions,
18899 Exceptions.clear();
18900 ESI.Type = EST;
18901 if (EST == EST_Dynamic) {
18902 Exceptions.reserve(DynamicExceptions.size());
18903 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18904 // FIXME: Preserve type source info.
18905 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18906
18907 if (IsTopLevel) {
18909 collectUnexpandedParameterPacks(ET, Unexpanded);
18910 if (!Unexpanded.empty()) {
18912 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18913 Unexpanded);
18914 continue;
18915 }
18916 }
18917
18918 // Check that the type is valid for an exception spec, and
18919 // drop it if not.
18920 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18921 Exceptions.push_back(ET);
18922 }
18923 ESI.Exceptions = Exceptions;
18924 return;
18925 }
18926
18927 if (isComputedNoexcept(EST)) {
18928 assert((NoexceptExpr->isTypeDependent() ||
18929 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18930 Context.BoolTy) &&
18931 "Parser should have made sure that the expression is boolean");
18932 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18933 ESI.Type = EST_BasicNoexcept;
18934 return;
18935 }
18936
18937 ESI.NoexceptExpr = NoexceptExpr;
18938 return;
18939 }
18940}
18941
18943 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
18944 ArrayRef<ParsedType> DynamicExceptions,
18945 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
18946 if (!D)
18947 return;
18948
18949 // Dig out the function we're referring to.
18950 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
18951 D = FTD->getTemplatedDecl();
18952
18953 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
18954 if (!FD)
18955 return;
18956
18957 // Check the exception specification.
18960 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
18961 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18962 ESI);
18963
18964 // Update the exception specification on the function type.
18965 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
18966
18967 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
18968 if (MD->isStatic())
18970
18971 if (MD->isVirtual()) {
18972 // Check overrides, which we previously had to delay.
18973 for (const CXXMethodDecl *O : MD->overridden_methods())
18975 }
18976 }
18977}
18978
18979/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18980///
18982 SourceLocation DeclStart, Declarator &D,
18983 Expr *BitWidth,
18984 InClassInitStyle InitStyle,
18985 AccessSpecifier AS,
18986 const ParsedAttr &MSPropertyAttr) {
18987 const IdentifierInfo *II = D.getIdentifier();
18988 if (!II) {
18989 Diag(DeclStart, diag::err_anonymous_property);
18990 return nullptr;
18991 }
18992 SourceLocation Loc = D.getIdentifierLoc();
18993
18995 QualType T = TInfo->getType();
18996 if (getLangOpts().CPlusPlus) {
18998
18999 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19001 D.setInvalidType();
19002 T = Context.IntTy;
19004 }
19005 }
19006
19007 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19008
19009 if (D.getDeclSpec().isInlineSpecified())
19010 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19011 << getLangOpts().CPlusPlus17;
19012 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19013 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19014 diag::err_invalid_thread)
19016
19017 // Check to see if this name was declared as a member previously
19018 NamedDecl *PrevDecl = nullptr;
19020 RedeclarationKind::ForVisibleRedeclaration);
19021 LookupName(Previous, S);
19022 switch (Previous.getResultKind()) {
19025 PrevDecl = Previous.getAsSingle<NamedDecl>();
19026 break;
19027
19029 PrevDecl = Previous.getRepresentativeDecl();
19030 break;
19031
19035 break;
19036 }
19037
19038 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19039 // Maybe we will complain about the shadowed template parameter.
19040 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19041 // Just pretend that we didn't see the previous declaration.
19042 PrevDecl = nullptr;
19043 }
19044
19045 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19046 PrevDecl = nullptr;
19047
19048 SourceLocation TSSL = D.getBeginLoc();
19049 MSPropertyDecl *NewPD =
19050 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19051 MSPropertyAttr.getPropertyDataGetter(),
19052 MSPropertyAttr.getPropertyDataSetter());
19054 NewPD->setAccess(AS);
19055
19056 if (NewPD->isInvalidDecl())
19057 Record->setInvalidDecl();
19058
19059 if (D.getDeclSpec().isModulePrivateSpecified())
19060 NewPD->setModulePrivate();
19061
19062 if (NewPD->isInvalidDecl() && PrevDecl) {
19063 // Don't introduce NewFD into scope; there's already something
19064 // with the same name in the same scope.
19065 } else if (II) {
19066 PushOnScopeChains(NewPD, S);
19067 } else
19068 Record->addDecl(NewPD);
19069
19070 return NewPD;
19071}
19072
19074 Declarator &Declarator, unsigned TemplateParameterDepth) {
19075 auto &Info = InventedParameterInfos.emplace_back();
19076 TemplateParameterList *ExplicitParams = nullptr;
19077 ArrayRef<TemplateParameterList *> ExplicitLists =
19079 if (!ExplicitLists.empty()) {
19080 bool IsMemberSpecialization, IsInvalid;
19083 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19084 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19085 /*SuppressDiagnostic=*/true);
19086 }
19087 // C++23 [dcl.fct]p23:
19088 // An abbreviated function template can have a template-head. The invented
19089 // template-parameters are appended to the template-parameter-list after
19090 // the explicitly declared template-parameters.
19091 //
19092 // A template-head must have one or more template-parameters (read:
19093 // 'template<>' is *not* a template-head). Only append the invented
19094 // template parameters if we matched the nested-name-specifier to a non-empty
19095 // TemplateParameterList.
19096 if (ExplicitParams && !ExplicitParams->empty()) {
19097 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19098 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19099 Info.NumExplicitTemplateParams = ExplicitParams->size();
19100 } else {
19101 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19102 Info.NumExplicitTemplateParams = 0;
19103 }
19104}
19105
19107 auto &FSI = InventedParameterInfos.back();
19108 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19109 if (FSI.NumExplicitTemplateParams != 0) {
19110 TemplateParameterList *ExplicitParams =
19114 Context, ExplicitParams->getTemplateLoc(),
19115 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19116 ExplicitParams->getRAngleLoc(),
19117 ExplicitParams->getRequiresClause()));
19118 } else {
19121 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19122 SourceLocation(), /*RequiresClause=*/nullptr));
19123 }
19124 }
19125 InventedParameterInfos.pop_back();
19126}
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
enum clang::sema::@1655::IndirectLocalPathEntry::EntryKind Kind
IndirectLocalPath & Path
Expr * E
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:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
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:4275
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:4859
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:6365
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:1611
body_range body()
Definition: Stmt.h:1674
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:4213
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:1502
decl_range decls()
Definition: Stmt.h:1550
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1528
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:947
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:2148
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:5792
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:5039
unsigned getNumInits() const
Definition: Expr.h:5069
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5085
child_range children()
Definition: Expr.h:5231
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:7522
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:649
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:6497
ArrayRef< Expr * > semantics()
Definition: Expr.h:6576
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 getCanonicalType() const
Definition: Type.h:7802
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:3029
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:969
bool isInvalid() const
Definition: Sema.h:7351
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5901
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5933
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5930
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:5004
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:8967
CXXMethodDecl * getMethod() const
Definition: Sema.h:8979
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:13090
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7249
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
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:10917
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6666
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:12656
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:9689
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:6084
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:1558
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3590
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15288
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:5845
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:9042
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9050
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:9038
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
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:412
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6602
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, CXXScopeSpec *SS=nullptr)
VariadicCallType
Definition: Sema.h:2346
@ VariadicDoesNotApply
Definition: Sema.h:2351
@ VariadicConstructor
Definition: Sema.h:2350
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:6079
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:13232
SemaOpenMP & OpenMP()
Definition: Sema.h:1179
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5820
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:6064
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:918
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:6061
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:6042
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:1124
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:17182
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:1315
@ AR_accessible
Definition: Sema.h:1313
@ AR_inaccessible
Definition: Sema.h:1314
@ AR_delayed
Definition: Sema.h:1316
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:2296
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:2165
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:6207
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:16940
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:4797
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:18263
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1710
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:962
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:5771
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1164
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:4907
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:7263
@ AllowFold
Definition: Sema.h:7265
@ NoFold
Definition: Sema.h:7264
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
ASTContext & getASTContext() const
Definition: Sema.h:560
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:6068
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:19662
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:6146
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:17603
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:702
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:5616
@ 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:9274
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:6079
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:868
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2198
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:11802
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1586
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7987
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1568
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2184
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:555
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20164
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_RequiresClause
Definition: Sema.h:13966
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:13921
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:13939
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13930
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:13900
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13924
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13933
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13903
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13906
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:13912
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:553
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:5406
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:1387
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:961
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:6408
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:8175
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:14375
const LangOptions & LangOpts
Definition: Sema.h:960
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:17299
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7485
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6046
SemaHLSL & HLSL()
Definition: Sema.h:1129
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:11816
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:5412
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4801
@ 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:6039
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19813
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:3619
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:6138
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6072
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:9370
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:1374
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:1844
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:12668
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:5402
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
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:3175
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14990
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:9613
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:15335
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:6512
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:6053
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15259
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
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:14839
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5776
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:5885
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5887
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:5890
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7796
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:19762
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2165
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:13497
SourceManager & getSourceManager() const
Definition: Sema.h:558
@ AA_Passing
Definition: Sema.h:6497
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:1339
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:8995
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9524
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:216
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:8198
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:3790
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14945
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:9409
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14205
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:6064
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:10030
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10028
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:10032
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3078
ASTConsumer & Consumer
Definition: Sema.h:963
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:4238
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9812
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9804
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9808
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5102
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:9492
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
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:17010
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:8907
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:923
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18865
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:7339
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:17681
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:965
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:964
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:7321
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:7200
@ TPC_TypeAliasTemplate
Definition: Sema.h:11302
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:6703
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5527
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1314
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:2851
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6076
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:1578
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8808
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:1563
@ OOK_Outside
Definition: Sema.h:3879
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13277
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:5819
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:17862
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:5893
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20298
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:20914
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6038
AbstractDiagSelID
Definition: Sema.h:5765
@ AbstractVariableType
Definition: Sema.h:5769
@ AbstractReturnType
Definition: Sema.h:5767
@ AbstractNone
Definition: Sema.h:5766
@ AbstractFieldType
Definition: Sema.h:5770
@ AbstractArrayType
Definition: Sema.h:5773
@ AbstractParamType
Definition: Sema.h:5768
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:909
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:1702
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7991
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:14600
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:5961
@ 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:2731
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:416
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:3016
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:6025
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:7377
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:5314
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:600
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:8293
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:4916
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:771
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2243
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:871
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:1071
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:403
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:216
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::@222 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:12673
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12790
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12767
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12764
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12717
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12731
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12735
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12793
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:12819
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7887
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.