Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
49#include "clang/Sema/Template.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86};
87
88/// VisitExpr - Visit all of the children of this expression.
89bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
90 bool IsInvalid = false;
91 for (const Stmt *SubStmt : Node->children())
92 if (SubStmt)
93 IsInvalid |= Visit(SubStmt);
94 return IsInvalid;
95}
96
97/// VisitDeclRefExpr - Visit a reference to a declaration, to
98/// determine whether this declaration can be used in the default
99/// argument expression.
100bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
101 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
102
103 if (!isa<VarDecl, BindingDecl>(Decl))
104 return false;
105
106 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
107 // C++ [dcl.fct.default]p9:
108 // [...] parameters of a function shall not be used in default
109 // argument expressions, even if they are not evaluated. [...]
110 //
111 // C++17 [dcl.fct.default]p9 (by CWG 2082):
112 // [...] A parameter shall not appear as a potentially-evaluated
113 // expression in a default argument. [...]
114 //
115 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
116 return S.Diag(DRE->getBeginLoc(),
117 diag::err_param_default_argument_references_param)
118 << Param->getDeclName() << DefaultArg->getSourceRange();
119 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
120 // C++ [dcl.fct.default]p7:
121 // Local variables shall not be used in default argument
122 // expressions.
123 //
124 // C++17 [dcl.fct.default]p7 (by CWG 2082):
125 // A local variable shall not appear as a potentially-evaluated
126 // expression in a default argument.
127 //
128 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
129 // Note: A local variable cannot be odr-used (6.3) in a default
130 // argument.
131 //
132 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
133 return S.Diag(DRE->getBeginLoc(),
134 diag::err_param_default_argument_references_local)
135 << Decl << DefaultArg->getSourceRange();
136 }
137 return false;
138}
139
140/// VisitCXXThisExpr - Visit a C++ "this" expression.
141bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
142 // C++ [dcl.fct.default]p8:
143 // The keyword this shall not be used in a default argument of a
144 // member function.
145 return S.Diag(ThisE->getBeginLoc(),
146 diag::err_param_default_argument_references_this)
147 << ThisE->getSourceRange();
148}
149
150bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
151 const PseudoObjectExpr *POE) {
152 bool Invalid = false;
153 for (const Expr *E : POE->semantics()) {
154 // Look through bindings.
155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
156 E = OVE->getSourceExpr();
157 assert(E && "pseudo-object binding without source expression?");
158 }
159
160 Invalid |= Visit(E);
161 }
162 return Invalid;
163}
164
165bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
166 // [expr.prim.lambda.capture]p9
167 // a lambda-expression appearing in a default argument cannot implicitly or
168 // explicitly capture any local entity. Such a lambda-expression can still
169 // have an init-capture if any full-expression in its initializer satisfies
170 // the constraints of an expression appearing in a default argument.
171 bool Invalid = false;
172 for (const LambdaCapture &LC : Lambda->captures()) {
173 if (!Lambda->isInitCapture(&LC))
174 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
175 // Init captures are always VarDecl.
176 auto *D = cast<VarDecl>(LC.getCapturedVar());
177 Invalid |= Visit(D->getInit());
178 }
179 return Invalid;
180}
181} // namespace
182
183void
185 const CXXMethodDecl *Method) {
186 // If we have an MSAny spec already, don't bother.
187 if (!Method || ComputedEST == EST_MSAny)
188 return;
189
190 const FunctionProtoType *Proto
191 = Method->getType()->getAs<FunctionProtoType>();
192 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
193 if (!Proto)
194 return;
195
197
198 // If we have a throw-all spec at this point, ignore the function.
199 if (ComputedEST == EST_None)
200 return;
201
202 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
203 EST = EST_BasicNoexcept;
204
205 switch (EST) {
206 case EST_Unparsed:
208 case EST_Unevaluated:
209 llvm_unreachable("should not see unresolved exception specs here");
210
211 // If this function can throw any exceptions, make a note of that.
212 case EST_MSAny:
213 case EST_None:
214 // FIXME: Whichever we see last of MSAny and None determines our result.
215 // We should make a consistent, order-independent choice here.
216 ClearExceptions();
217 ComputedEST = EST;
218 return;
220 ClearExceptions();
221 ComputedEST = EST_None;
222 return;
223 // FIXME: If the call to this decl is using any of its default arguments, we
224 // need to search them for potentially-throwing calls.
225 // If this function has a basic noexcept, it doesn't affect the outcome.
227 case EST_NoexceptTrue:
228 case EST_NoThrow:
229 return;
230 // If we're still at noexcept(true) and there's a throw() callee,
231 // change to that specification.
232 case EST_DynamicNone:
233 if (ComputedEST == EST_BasicNoexcept)
234 ComputedEST = EST_DynamicNone;
235 return;
237 llvm_unreachable(
238 "should not generate implicit declarations for dependent cases");
239 case EST_Dynamic:
240 break;
241 }
242 assert(EST == EST_Dynamic && "EST case not considered earlier.");
243 assert(ComputedEST != EST_None &&
244 "Shouldn't collect exceptions when throw-all is guaranteed.");
245 ComputedEST = EST_Dynamic;
246 // Record the exceptions in this function's exception specification.
247 for (const auto &E : Proto->exceptions())
248 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
249 Exceptions.push_back(E);
250}
251
253 if (!S || ComputedEST == EST_MSAny)
254 return;
255
256 // FIXME:
257 //
258 // C++0x [except.spec]p14:
259 // [An] implicit exception-specification specifies the type-id T if and
260 // only if T is allowed by the exception-specification of a function directly
261 // invoked by f's implicit definition; f shall allow all exceptions if any
262 // function it directly invokes allows all exceptions, and f shall allow no
263 // exceptions if every function it directly invokes allows no exceptions.
264 //
265 // Note in particular that if an implicit exception-specification is generated
266 // for a function containing a throw-expression, that specification can still
267 // be noexcept(true).
268 //
269 // Note also that 'directly invoked' is not defined in the standard, and there
270 // is no indication that we should only consider potentially-evaluated calls.
271 //
272 // Ultimately we should implement the intent of the standard: the exception
273 // specification should be the set of exceptions which can be thrown by the
274 // implicit definition. For now, we assume that any non-nothrow expression can
275 // throw any exception.
276
277 if (Self->canThrow(S))
278 ComputedEST = EST_None;
279}
280
282 SourceLocation EqualLoc) {
283 if (RequireCompleteType(Param->getLocation(), Param->getType(),
284 diag::err_typecheck_decl_incomplete_type))
285 return true;
286
287 // C++ [dcl.fct.default]p5
288 // A default argument expression is implicitly converted (clause
289 // 4) to the parameter type. The default argument expression has
290 // the same semantic constraints as the initializer expression in
291 // a declaration of a variable of the parameter type, using the
292 // copy-initialization semantics (8.5).
294 Param);
295 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
296 EqualLoc);
297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
299 if (Result.isInvalid())
300 return true;
301 Arg = Result.getAs<Expr>();
302
303 CheckCompletedExpr(Arg, EqualLoc);
305
306 return Arg;
307}
308
310 SourceLocation EqualLoc) {
311 // Add the default argument to the parameter
312 Param->setDefaultArg(Arg);
313
314 // We have already instantiated this parameter; provide each of the
315 // instantiations with the uninstantiated default argument.
316 UnparsedDefaultArgInstantiationsMap::iterator InstPos
318 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
319 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
320 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
321
322 // We're done tracking this parameter's instantiations.
324 }
325}
326
327void
329 Expr *DefaultArg) {
330 if (!param || !DefaultArg)
331 return;
332
333 ParmVarDecl *Param = cast<ParmVarDecl>(param);
334 UnparsedDefaultArgLocs.erase(Param);
335
336 // Default arguments are only permitted in C++
337 if (!getLangOpts().CPlusPlus) {
338 Diag(EqualLoc, diag::err_param_default_argument)
339 << DefaultArg->getSourceRange();
340 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
341 }
342
343 // Check for unexpanded parameter packs.
345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346
347 // C++11 [dcl.fct.default]p3
348 // A default argument expression [...] shall not be specified for a
349 // parameter pack.
350 if (Param->isParameterPack()) {
351 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
352 << DefaultArg->getSourceRange();
353 // Recover by discarding the default argument.
354 Param->setDefaultArg(nullptr);
355 return;
356 }
357
358 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
359 if (Result.isInvalid())
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361
362 DefaultArg = Result.getAs<Expr>();
363
364 // Check that the default argument is well-formed
365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
366 if (DefaultArgChecker.Visit(DefaultArg))
367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
368
369 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
370}
371
373 SourceLocation EqualLoc,
374 SourceLocation ArgLoc) {
375 if (!param)
376 return;
377
378 ParmVarDecl *Param = cast<ParmVarDecl>(param);
379 Param->setUnparsedDefaultArg();
380 UnparsedDefaultArgLocs[Param] = ArgLoc;
381}
382
384 Expr *DefaultArg) {
385 if (!param)
386 return;
387
388 ParmVarDecl *Param = cast<ParmVarDecl>(param);
389 Param->setInvalidDecl();
390 UnparsedDefaultArgLocs.erase(Param);
391 ExprResult RE;
392 if (DefaultArg) {
393 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
394 Param->getType().getNonReferenceType());
395 } else {
396 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
397 Param->getType().getNonReferenceType());
398 }
399 Param->setDefaultArg(RE.get());
400}
401
403 // C++ [dcl.fct.default]p3
404 // A default argument expression shall be specified only in the
405 // parameter-declaration-clause of a function declaration or in a
406 // template-parameter (14.1). It shall not be specified for a
407 // parameter pack. If it is specified in a
408 // parameter-declaration-clause, it shall not occur within a
409 // declarator or abstract-declarator of a parameter-declaration.
410 bool MightBeFunction = D.isFunctionDeclarationContext();
411 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
412 DeclaratorChunk &chunk = D.getTypeObject(i);
413 if (chunk.Kind == DeclaratorChunk::Function) {
414 if (MightBeFunction) {
415 // This is a function declaration. It can have default arguments, but
416 // keep looking in case its return type is a function type with default
417 // arguments.
418 MightBeFunction = false;
419 continue;
420 }
421 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
422 ++argIdx) {
423 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
424 if (Param->hasUnparsedDefaultArg()) {
425 std::unique_ptr<CachedTokens> Toks =
426 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
427 SourceRange SR;
428 if (Toks->size() > 1)
429 SR = SourceRange((*Toks)[1].getLocation(),
430 Toks->back().getLocation());
431 else
432 SR = UnparsedDefaultArgLocs[Param];
433 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
434 << SR;
435 } else if (Param->getDefaultArg()) {
436 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
437 << Param->getDefaultArg()->getSourceRange();
438 Param->setDefaultArg(nullptr);
439 }
440 }
441 } else if (chunk.Kind != DeclaratorChunk::Paren) {
442 MightBeFunction = false;
443 }
444 }
445}
446
448 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
450 });
451}
452
454 Scope *S) {
455 bool Invalid = false;
456
457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463
464 // Find the previous declaration for the purpose of default arguments.
465 FunctionDecl *PrevForDefaultArgs = Old;
466 for (/**/; PrevForDefaultArgs;
467 // Don't bother looking back past the latest decl if this is a local
468 // extern declaration; nothing else could work.
469 PrevForDefaultArgs = New->isLocalExternDecl()
470 ? nullptr
471 : PrevForDefaultArgs->getPreviousDecl()) {
472 // Ignore hidden declarations.
473 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
474 continue;
475
476 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
477 !New->isCXXClassMember()) {
478 // Ignore default arguments of old decl if they are not in
479 // the same scope and this is not an out-of-line definition of
480 // a member function.
481 continue;
482 }
483
484 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
485 // If only one of these is a local function declaration, then they are
486 // declared in different scopes, even though isDeclInScope may think
487 // they're in the same scope. (If both are local, the scope check is
488 // sufficient, and if neither is local, then they are in the same scope.)
489 continue;
490 }
491
492 // We found the right previous declaration.
493 break;
494 }
495
496 // C++ [dcl.fct.default]p4:
497 // For non-template functions, default arguments can be added in
498 // later declarations of a function in the same
499 // scope. Declarations in different scopes have completely
500 // distinct sets of default arguments. That is, declarations in
501 // inner scopes do not acquire default arguments from
502 // declarations in outer scopes, and vice versa. In a given
503 // function declaration, all parameters subsequent to a
504 // parameter with a default argument shall have default
505 // arguments supplied in this or previous declarations. A
506 // default argument shall not be redefined by a later
507 // declaration (not even to the same value).
508 //
509 // C++ [dcl.fct.default]p6:
510 // Except for member functions of class templates, the default arguments
511 // in a member function definition that appears outside of the class
512 // definition are added to the set of default arguments provided by the
513 // member function declaration in the class definition.
514 for (unsigned p = 0, NumParams = PrevForDefaultArgs
515 ? PrevForDefaultArgs->getNumParams()
516 : 0;
517 p < NumParams; ++p) {
518 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
519 ParmVarDecl *NewParam = New->getParamDecl(p);
520
521 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
522 bool NewParamHasDfl = NewParam->hasDefaultArg();
523
524 if (OldParamHasDfl && NewParamHasDfl) {
525 unsigned DiagDefaultParamID =
526 diag::err_param_default_argument_redefinition;
527
528 // MSVC accepts that default parameters be redefined for member functions
529 // of template class. The new default parameter's value is ignored.
530 Invalid = true;
531 if (getLangOpts().MicrosoftExt) {
532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
533 if (MD && MD->getParent()->getDescribedClassTemplate()) {
534 // Merge the old default argument into the new parameter.
535 NewParam->setHasInheritedDefaultArg();
536 if (OldParam->hasUninstantiatedDefaultArg())
538 OldParam->getUninstantiatedDefaultArg());
539 else
540 NewParam->setDefaultArg(OldParam->getInit());
541 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
542 Invalid = false;
543 }
544 }
545
546 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
547 // hint here. Alternatively, we could walk the type-source information
548 // for NewParam to find the last source location in the type... but it
549 // isn't worth the effort right now. This is the kind of test case that
550 // is hard to get right:
551 // int f(int);
552 // void g(int (*fp)(int) = f);
553 // void g(int (*fp)(int) = &f);
554 Diag(NewParam->getLocation(), DiagDefaultParamID)
555 << NewParam->getDefaultArgRange();
556
557 // Look for the function declaration where the default argument was
558 // actually written, which may be a declaration prior to Old.
559 for (auto Older = PrevForDefaultArgs;
560 OldParam->hasInheritedDefaultArg(); /**/) {
561 Older = Older->getPreviousDecl();
562 OldParam = Older->getParamDecl(p);
563 }
564
565 Diag(OldParam->getLocation(), diag::note_previous_definition)
566 << OldParam->getDefaultArgRange();
567 } else if (OldParamHasDfl) {
568 // Merge the old default argument into the new parameter unless the new
569 // function is a friend declaration in a template class. In the latter
570 // case the default arguments will be inherited when the friend
571 // declaration will be instantiated.
572 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 !New->getLexicalDeclContext()->isDependentContext()) {
574 // It's important to use getInit() here; getDefaultArg()
575 // strips off any top-level ExprWithCleanups.
576 NewParam->setHasInheritedDefaultArg();
577 if (OldParam->hasUnparsedDefaultArg())
578 NewParam->setUnparsedDefaultArg();
579 else if (OldParam->hasUninstantiatedDefaultArg())
581 OldParam->getUninstantiatedDefaultArg());
582 else
583 NewParam->setDefaultArg(OldParam->getInit());
584 }
585 } else if (NewParamHasDfl) {
586 if (New->getDescribedFunctionTemplate()) {
587 // Paragraph 4, quoted above, only applies to non-template functions.
588 Diag(NewParam->getLocation(),
589 diag::err_param_default_argument_template_redecl)
590 << NewParam->getDefaultArgRange();
591 Diag(PrevForDefaultArgs->getLocation(),
592 diag::note_template_prev_declaration)
593 << false;
594 } else if (New->getTemplateSpecializationKind()
596 New->getTemplateSpecializationKind() != TSK_Undeclared) {
597 // C++ [temp.expr.spec]p21:
598 // Default function arguments shall not be specified in a declaration
599 // or a definition for one of the following explicit specializations:
600 // - the explicit specialization of a function template;
601 // - the explicit specialization of a member function template;
602 // - the explicit specialization of a member function of a class
603 // template where the class template specialization to which the
604 // member function specialization belongs is implicitly
605 // instantiated.
606 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
607 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
608 << New->getDeclName()
609 << NewParam->getDefaultArgRange();
610 } else if (New->getDeclContext()->isDependentContext()) {
611 // C++ [dcl.fct.default]p6 (DR217):
612 // Default arguments for a member function of a class template shall
613 // be specified on the initial declaration of the member function
614 // within the class template.
615 //
616 // Reading the tea leaves a bit in DR217 and its reference to DR205
617 // leads me to the conclusion that one cannot add default function
618 // arguments for an out-of-line definition of a member function of a
619 // dependent type.
620 int WhichKind = 2;
622 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
623 if (Record->getDescribedClassTemplate())
624 WhichKind = 0;
626 WhichKind = 1;
627 else
628 WhichKind = 2;
629 }
630
631 Diag(NewParam->getLocation(),
632 diag::err_param_default_argument_member_template_redecl)
633 << WhichKind
634 << NewParam->getDefaultArgRange();
635 }
636 }
637 }
638
639 // DR1344: If a default argument is added outside a class definition and that
640 // default argument makes the function a special member function, the program
641 // is ill-formed. This can only happen for constructors.
643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
646 if (NewSM != OldSM) {
647 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
648 assert(NewParam->hasDefaultArg());
649 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
650 << NewParam->getDefaultArgRange() << NewSM;
651 Diag(Old->getLocation(), diag::note_previous_declaration);
652 }
653 }
654
655 const FunctionDecl *Def;
656 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
657 // template has a constexpr specifier then all its declarations shall
658 // contain the constexpr specifier.
659 if (New->getConstexprKind() != Old->getConstexprKind()) {
660 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
661 << New << static_cast<int>(New->getConstexprKind())
662 << static_cast<int>(Old->getConstexprKind());
663 Diag(Old->getLocation(), diag::note_previous_declaration);
664 Invalid = true;
665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
666 Old->isDefined(Def) &&
667 // If a friend function is inlined but does not have 'inline'
668 // specifier, it is a definition. Do not report attribute conflict
669 // in this case, redefinition will be diagnosed later.
670 (New->isInlineSpecified() ||
671 New->getFriendObjectKind() == Decl::FOK_None)) {
672 // C++11 [dcl.fcn.spec]p4:
673 // If the definition of a function appears in a translation unit before its
674 // first declaration as inline, the program is ill-formed.
675 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
676 Diag(Def->getLocation(), diag::note_previous_definition);
677 Invalid = true;
678 }
679
680 // C++17 [temp.deduct.guide]p3:
681 // Two deduction guide declarations in the same translation unit
682 // for the same class template shall not have equivalent
683 // parameter-declaration-clauses.
685 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
686 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
687 Diag(Old->getLocation(), diag::note_previous_declaration);
688 }
689
690 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
691 // argument expression, that declaration shall be a definition and shall be
692 // the only declaration of the function or function template in the
693 // translation unit.
696 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
697 Diag(Old->getLocation(), diag::note_previous_declaration);
698 Invalid = true;
699 }
700
701 // C++11 [temp.friend]p4 (DR329):
702 // When a function is defined in a friend function declaration in a class
703 // template, the function is instantiated when the function is odr-used.
704 // The same restrictions on multiple declarations and definitions that
705 // apply to non-template function declarations and definitions also apply
706 // to these implicit definitions.
707 const FunctionDecl *OldDefinition = nullptr;
708 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
709 Old->isDefined(OldDefinition, true))
710 CheckForFunctionRedefinition(New, OldDefinition);
711
712 return Invalid;
713}
714
717 ? diag::warn_cxx23_placeholder_var_definition
718 : diag::ext_placeholder_var_definition);
719}
720
721NamedDecl *
723 MultiTemplateParamsArg TemplateParamLists) {
724 assert(D.isDecompositionDeclarator());
726
727 // The syntax only allows a decomposition declarator as a simple-declaration,
728 // a for-range-declaration, or a condition in Clang, but we parse it in more
729 // cases than that.
731 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
732 << Decomp.getSourceRange();
733 return nullptr;
734 }
735
736 if (!TemplateParamLists.empty()) {
737 // C++17 [temp]/1:
738 // A template defines a family of class, functions, or variables, or an
739 // alias for a family of types.
740 //
741 // Structured bindings are not included.
742 Diag(TemplateParamLists.front()->getTemplateLoc(),
743 diag::err_decomp_decl_template);
744 return nullptr;
745 }
746
747 unsigned DiagID;
749 DiagID = diag::compat_pre_cxx17_decomp_decl;
751 DiagID = getLangOpts().CPlusPlus26
752 ? diag::compat_cxx26_decomp_decl_cond
753 : diag::compat_pre_cxx26_decomp_decl_cond;
754 else
755 DiagID = diag::compat_cxx17_decomp_decl;
756
757 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
758
759 // The semantic context is always just the current context.
760 DeclContext *const DC = CurContext;
761
762 // C++17 [dcl.dcl]/8:
763 // The decl-specifier-seq shall contain only the type-specifier auto
764 // and cv-qualifiers.
765 // C++20 [dcl.dcl]/8:
766 // If decl-specifier-seq contains any decl-specifier other than static,
767 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
768 // C++23 [dcl.pre]/6:
769 // Each decl-specifier in the decl-specifier-seq shall be static,
770 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
771 // C++23 [dcl.pre]/7:
772 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
773 // constinit, static, thread_local, auto, or a cv-qualifier
774 auto &DS = D.getDeclSpec();
775 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
776 Diag(Loc, diag::err_decomp_decl_spec) << Name;
777 };
778
779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
780 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
781 };
782
783 if (auto SCS = DS.getStorageClassSpec()) {
784 if (SCS == DeclSpec::SCS_static)
785 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
786 DS.getStorageClassSpecLoc());
787 else
788 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
789 DS.getStorageClassSpecLoc());
790 }
791 if (auto TSCS = DS.getThreadStorageClassSpec())
792 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
793 DS.getThreadStorageClassSpecLoc());
794
795 if (DS.isInlineSpecified())
796 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
797
798 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
799 ConstexprSpec != ConstexprSpecKind::Unspecified) {
800 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
802 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
803 DS.getConstexprSpecLoc());
804 }
805
806 // We can't recover from it being declared as a typedef.
807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
808 return nullptr;
809
810 // C++2a [dcl.struct.bind]p1:
811 // A cv that includes volatile is deprecated
812 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
814 Diag(DS.getVolatileSpecLoc(),
815 diag::warn_deprecated_volatile_structured_binding);
816
818 QualType R = TInfo->getType();
819
822 D.setInvalidType();
823
824 // The syntax only allows a single ref-qualifier prior to the decomposition
825 // declarator. No other declarator chunks are permitted. Also check the type
826 // specifier here.
827 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
828 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
829 (D.getNumTypeObjects() == 1 &&
831 Diag(Decomp.getLSquareLoc(),
832 (D.hasGroupingParens() ||
833 (D.getNumTypeObjects() &&
835 ? diag::err_decomp_decl_parens
836 : diag::err_decomp_decl_type)
837 << R;
838
839 // In most cases, there's no actual problem with an explicitly-specified
840 // type, but a function type won't work here, and ActOnVariableDeclarator
841 // shouldn't be called for such a type.
842 if (R->isFunctionType())
843 D.setInvalidType();
844 }
845
846 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
847 if (DS.isConstrainedAuto()) {
848 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
849 assert(TemplRep->Kind == TNK_Concept_template &&
850 "No other template kind should be possible for a constrained auto");
851
852 SourceRange TemplRange{TemplRep->TemplateNameLoc,
853 TemplRep->RAngleLoc.isValid()
854 ? TemplRep->RAngleLoc
855 : TemplRep->TemplateNameLoc};
856 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
857 << TemplRange << FixItHint::CreateRemoval(TemplRange);
858 }
859
860 // Build the BindingDecls.
862
863 // Build the BindingDecls.
864 for (auto &B : D.getDecompositionDeclarator().bindings()) {
865 // Check for name conflicts.
866 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
867 IdentifierInfo *VarName = B.Name;
868 assert(VarName && "Cannot have an unnamed binding declaration");
869
873 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
874
875 // It's not permitted to shadow a template parameter name.
876 if (Previous.isSingleResult() &&
877 Previous.getFoundDecl()->isTemplateParameter()) {
878 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
879 Previous.clear();
880 }
881
882 QualType QT;
883 if (B.EllipsisLoc.isValid()) {
884 if (!cast<Decl>(DC)->isTemplated())
885 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
886 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
887 /*ExpectsPackInType=*/false);
888 }
889
890 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
891
892 ProcessDeclAttributeList(S, BD, *B.Attrs);
893
894 // Find the shadowed declaration before filtering for scope.
895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
897 : nullptr;
898
899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
902 /*AllowInlineNamespace*/false);
903
904 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 DC->isFunctionOrMethod() && VarName->isPlaceholder();
906 if (!Previous.empty()) {
907 if (IsPlaceholder) {
908 bool sameDC = (Previous.end() - 1)
909 ->getDeclContext()
910 ->getRedeclContext()
911 ->Equals(DC->getRedeclContext());
912 if (sameDC &&
913 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
914 Previous.clear();
916 }
917 } else {
918 auto *Old = Previous.getRepresentativeDecl();
919 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
920 Diag(Old->getLocation(), diag::note_previous_definition);
921 }
922 } else if (ShadowedDecl && !D.isRedeclaration()) {
923 CheckShadow(BD, ShadowedDecl, Previous);
924 }
925 PushOnScopeChains(BD, S, true);
926 Bindings.push_back(BD);
927 ParsingInitForAutoVars.insert(BD);
928 }
929
930 // There are no prior lookup results for the variable itself, because it
931 // is unnamed.
932 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
933 Decomp.getLSquareLoc());
936
937 // Build the variable that holds the non-decomposed object.
938 bool AddToScope = true;
939 NamedDecl *New =
940 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
941 MultiTemplateParamsArg(), AddToScope, Bindings);
942 if (AddToScope) {
943 S->AddDecl(New);
944 CurContext->addHiddenDecl(New);
945 }
946
947 if (OpenMP().isInOpenMPDeclareTargetContext())
948 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
949
950 return New;
951}
952
953// Check the arity of the structured bindings.
954// Create the resolved pack expr if needed.
956 QualType DecompType,
958 unsigned MemberCount) {
959 auto BindingWithPackItr = llvm::find_if(
960 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
961 bool HasPack = BindingWithPackItr != Bindings.end();
962 bool IsValid;
963 if (!HasPack) {
964 IsValid = Bindings.size() == MemberCount;
965 } else {
966 // There may not be more members than non-pack bindings.
967 IsValid = MemberCount >= Bindings.size() - 1;
968 }
969
970 if (IsValid && HasPack) {
971 // Create the pack expr and assign it to the binding.
972 unsigned PackSize = MemberCount - Bindings.size() + 1;
973
974 BindingDecl *BPack = *BindingWithPackItr;
975 BPack->setDecomposedDecl(DD);
976 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
977 // Create the nested BindingDecls.
978 for (unsigned I = 0; I < PackSize; ++I) {
980 S.Context, BPack->getDeclContext(), BPack->getLocation(),
981 BPack->getIdentifier(), QualType());
982 NestedBD->setDecomposedDecl(DD);
983 NestedBDs[I] = NestedBD;
984 }
985
987 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
988 auto *PackExpr = FunctionParmPackExpr::Create(
989 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
990 BPack->setBinding(PackType, PackExpr);
991 }
992
993 if (IsValid)
994 return false;
995
996 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
998 << (MemberCount < Bindings.size());
999 return true;
1000}
1001
1004 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1005 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1006 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1007 auto *DD = cast<DecompositionDecl>(Src);
1008
1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1010 return true;
1011
1012 unsigned I = 0;
1013 for (auto *B : DD->flat_bindings()) {
1014 SourceLocation Loc = B->getLocation();
1015 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1016 if (E.isInvalid())
1017 return true;
1018 E = GetInit(Loc, E.get(), I++);
1019 if (E.isInvalid())
1020 return true;
1021 B->setBinding(ElemType, E.get());
1022 }
1023
1024 return false;
1025}
1026
1029 ValueDecl *Src, QualType DecompType,
1030 const llvm::APSInt &NumElems,
1031 QualType ElemType) {
1033 S, Bindings, Src, DecompType, NumElems, ElemType,
1034 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1036 if (E.isInvalid())
1037 return ExprError();
1038 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1039 });
1040}
1041
1043 ValueDecl *Src, QualType DecompType,
1044 const ConstantArrayType *CAT) {
1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1046 llvm::APSInt(CAT->getSize()),
1047 CAT->getElementType());
1048}
1049
1051 ValueDecl *Src, QualType DecompType,
1052 const VectorType *VT) {
1054 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1056 DecompType.getQualifiers()));
1057}
1058
1061 ValueDecl *Src, QualType DecompType,
1062 const ComplexType *CT) {
1064 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1066 DecompType.getQualifiers()),
1067 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1068 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1069 });
1070}
1071
1074 const TemplateParameterList *Params) {
1076 llvm::raw_svector_ostream OS(SS);
1077 bool First = true;
1078 unsigned I = 0;
1079 for (auto &Arg : Args.arguments()) {
1080 if (!First)
1081 OS << ", ";
1082 Arg.getArgument().print(PrintingPolicy, OS,
1084 PrintingPolicy, Params, I));
1085 First = false;
1086 I++;
1087 }
1088 return std::string(OS.str());
1089}
1090
1091static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1092 TemplateArgumentListInfo &Args, unsigned DiagID) {
1093 auto DiagnoseMissing = [&] {
1094 if (DiagID)
1095 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1096 Args, /*Params*/ nullptr);
1097 return QualType();
1098 };
1099
1100 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1101 NamespaceDecl *Std = S.getStdNamespace();
1102 if (!Std)
1103 return DiagnoseMissing();
1104
1105 // Look up the trait itself, within namespace std. We can diagnose various
1106 // problems with this lookup even if we've been asked to not diagnose a
1107 // missing specialization, because this can only fail if the user has been
1108 // declaring their own names in namespace std or we don't support the
1109 // standard library implementation in use.
1110 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1112 if (!S.LookupQualifiedName(Result, Std))
1113 return DiagnoseMissing();
1114 if (Result.isAmbiguous())
1115 return QualType();
1116
1117 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1118 if (!TraitTD) {
1119 Result.suppressDiagnostics();
1120 NamedDecl *Found = *Result.begin();
1121 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1122 S.Diag(Found->getLocation(), diag::note_declared_at);
1123 return QualType();
1124 }
1125
1126 // Build the template-id.
1127 QualType TraitTy = S.CheckTemplateIdType(
1128 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1130 if (TraitTy.isNull())
1131 return QualType();
1132
1133 if (!S.isCompleteType(Loc, TraitTy)) {
1134 if (DiagID)
1136 Loc, TraitTy, DiagID,
1138 TraitTD->getTemplateParameters()));
1139 return QualType();
1140 }
1141 return TraitTy;
1142}
1143
1144static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1145 LookupResult &MemberLookup) {
1146 assert(RD && "specialization of class template is not a class?");
1147 S.LookupQualifiedName(MemberLookup, RD);
1148 return MemberLookup.isAmbiguous();
1149}
1150
1151static TemplateArgumentLoc
1153 uint64_t I) {
1155 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1156}
1157
1158static TemplateArgumentLoc
1162
1163namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1164
1165static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1166 unsigned &OutSize) {
1169
1170 // Form template argument list for tuple_size<T>.
1171 TemplateArgumentListInfo Args(Loc, Loc);
1173
1174 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1175 if (TraitTy.isNull())
1176 return IsTupleLike::NotTupleLike;
1177
1180
1181 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1182 // it's not tuple-like.
1183 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1184 return IsTupleLike::NotTupleLike;
1185
1186 // If we get this far, we've committed to the tuple interpretation, but
1187 // we can still fail if there actually isn't a usable ::value.
1188
1189 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1190 LookupResult &R;
1192 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1193 : R(R), Args(Args) {}
1194 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1195 SourceLocation Loc) override {
1196 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1198 /*Params*/ nullptr);
1199 }
1200 } Diagnoser(R, Args);
1201
1202 ExprResult E =
1203 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1204 if (E.isInvalid())
1205 return IsTupleLike::Error;
1206
1207 llvm::APSInt Size;
1208 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1209 if (E.isInvalid())
1210 return IsTupleLike::Error;
1211
1212 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1213 // an UnsignedOrNone.
1214 if (Size < 0 || Size >= UINT_MAX) {
1216 Size.toString(Str);
1217 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1219 /*Params=*/nullptr)
1220 << StringRef(Str.data(), Str.size());
1221 return IsTupleLike::Error;
1222 }
1223
1224 OutSize = Size.getExtValue();
1225 return IsTupleLike::TupleLike;
1226}
1227
1228/// \return std::tuple_element<I, T>::type.
1230 unsigned I, QualType T) {
1231 // Form template argument list for tuple_element<I, T>.
1232 TemplateArgumentListInfo Args(Loc, Loc);
1233 Args.addArgument(
1236
1237 QualType TraitTy =
1238 getStdTrait(S, Loc, "tuple_element", Args,
1239 diag::err_decomp_decl_std_tuple_element_not_specialized);
1240 if (TraitTy.isNull())
1241 return QualType();
1242
1243 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1245 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1246 return QualType();
1247
1248 auto *TD = R.getAsSingle<TypeDecl>();
1249 if (!TD) {
1251 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1253 /*Params*/ nullptr);
1254 if (!R.empty())
1255 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1256 return QualType();
1257 }
1258
1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1260 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1261}
1262
1263namespace {
1264struct InitializingBinding {
1265 Sema &S;
1266 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1267 Sema::CodeSynthesisContext Ctx;
1270 Ctx.Entity = BD;
1272 }
1273 ~InitializingBinding() {
1275 }
1276};
1277}
1278
1281 VarDecl *Src, QualType DecompType,
1282 unsigned NumElems) {
1283 auto *DD = cast<DecompositionDecl>(Src);
1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1285 return true;
1286
1287 if (Bindings.empty())
1288 return false;
1289
1290 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1291
1292 // [dcl.decomp]p3:
1293 // The unqualified-id get is looked up in the scope of E by class member
1294 // access lookup ...
1295 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1296 bool UseMemberGet = false;
1297 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1298 if (auto *RD = DecompType->getAsCXXRecordDecl())
1299 S.LookupQualifiedName(MemberGet, RD);
1300 if (MemberGet.isAmbiguous())
1301 return true;
1302 // ... and if that finds at least one declaration that is a function
1303 // template whose first template parameter is a non-type parameter ...
1304 for (NamedDecl *D : MemberGet) {
1305 if (FunctionTemplateDecl *FTD =
1306 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1307 TemplateParameterList *TPL = FTD->getTemplateParameters();
1308 if (TPL->size() != 0 &&
1310 // ... the initializer is e.get<i>().
1311 UseMemberGet = true;
1312 break;
1313 }
1314 }
1315 }
1316 }
1317
1318 unsigned I = 0;
1319 for (auto *B : DD->flat_bindings()) {
1320 InitializingBinding InitContext(S, B);
1321 SourceLocation Loc = B->getLocation();
1322
1323 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1324 if (E.isInvalid())
1325 return true;
1326
1327 // e is an lvalue if the type of the entity is an lvalue reference and
1328 // an xvalue otherwise
1329 if (!Src->getType()->isLValueReferenceType())
1330 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1331 E.get(), nullptr, VK_XValue,
1333
1334 TemplateArgumentListInfo Args(Loc, Loc);
1335 Args.addArgument(
1337
1338 if (UseMemberGet) {
1339 // if [lookup of member get] finds at least one declaration, the
1340 // initializer is e.get<i-1>().
1341 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1342 CXXScopeSpec(), SourceLocation(), nullptr,
1343 MemberGet, &Args, nullptr);
1344 if (E.isInvalid())
1345 return true;
1346
1347 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1348 } else {
1349 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1350 // in the associated namespaces.
1353 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1356
1357 Expr *Arg = E.get();
1358 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1359 }
1360 if (E.isInvalid())
1361 return true;
1362 Expr *Init = E.get();
1363
1364 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1365 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1366 if (T.isNull())
1367 return true;
1368
1369 // each vi is a variable of type "reference to T" initialized with the
1370 // initializer, where the reference is an lvalue reference if the
1371 // initializer is an lvalue and an rvalue reference otherwise
1372 QualType RefType =
1373 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1374 if (RefType.isNull())
1375 return true;
1376
1377 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1378 // entity and this type was never written in source code.
1379 auto *RefVD =
1380 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1381 B->getDeclName().getAsIdentifierInfo(), RefType,
1382 /*TInfo=*/nullptr, Src->getStorageClass());
1383 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1384 RefVD->setTSCSpec(Src->getTSCSpec());
1385 RefVD->setImplicit();
1386 if (Src->isInlineSpecified())
1387 RefVD->setInlineSpecified();
1388 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1389
1392 InitializationSequence Seq(S, Entity, Kind, Init);
1393 E = Seq.Perform(S, Entity, Kind, Init);
1394 if (E.isInvalid())
1395 return true;
1396 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1397 if (E.isInvalid())
1398 return true;
1399 RefVD->setInit(E.get());
1401
1403 DeclarationNameInfo(B->getDeclName(), Loc),
1404 RefVD);
1405 if (E.isInvalid())
1406 return true;
1407
1408 B->setBinding(T, E.get());
1409 I++;
1410 }
1411
1412 return false;
1413}
1414
1415/// Find the base class to decompose in a built-in decomposition of a class type.
1416/// This base class search is, unfortunately, not quite like any other that we
1417/// perform anywhere else in C++.
1419 const CXXRecordDecl *RD,
1420 CXXCastPath &BasePath) {
1421 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1422 CXXBasePath &Path) {
1423 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1424 };
1425
1426 const CXXRecordDecl *ClassWithFields = nullptr;
1428 if (RD->hasDirectFields())
1429 // [dcl.decomp]p4:
1430 // Otherwise, all of E's non-static data members shall be public direct
1431 // members of E ...
1432 ClassWithFields = RD;
1433 else {
1434 // ... or of ...
1435 CXXBasePaths Paths;
1436 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1437 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1438 // If no classes have fields, just decompose RD itself. (This will work
1439 // if and only if zero bindings were provided.)
1440 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1441 }
1442
1443 CXXBasePath *BestPath = nullptr;
1444 for (auto &P : Paths) {
1445 if (!BestPath)
1446 BestPath = &P;
1447 else if (!S.Context.hasSameType(P.back().Base->getType(),
1448 BestPath->back().Base->getType())) {
1449 // ... the same ...
1450 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1451 << false << RD << BestPath->back().Base->getType()
1452 << P.back().Base->getType();
1453 return DeclAccessPair();
1454 } else if (P.Access < BestPath->Access) {
1455 BestPath = &P;
1456 }
1457 }
1458
1459 // ... unambiguous ...
1460 QualType BaseType = BestPath->back().Base->getType();
1461 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1462 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1463 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1464 return DeclAccessPair();
1465 }
1466
1467 // ... [accessible, implied by other rules] base class of E.
1468 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1469 *BestPath, diag::err_decomp_decl_inaccessible_base);
1470 AS = BestPath->Access;
1471
1472 ClassWithFields = BaseType->getAsCXXRecordDecl();
1473 S.BuildBasePathArray(Paths, BasePath);
1474 }
1475
1476 // The above search did not check whether the selected class itself has base
1477 // classes with fields, so check that now.
1478 CXXBasePaths Paths;
1479 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1480 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1481 << (ClassWithFields == RD) << RD << ClassWithFields
1482 << Paths.front().back().Base->getType();
1483 return DeclAccessPair();
1484 }
1485
1486 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1487}
1488
1490 const CXXRecordDecl *OrigRD,
1491 QualType DecompType,
1492 DeclAccessPair BasePair) {
1493 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1494 if (!RD)
1495 return true;
1496
1497 for (auto *FD : RD->fields()) {
1498 if (FD->isUnnamedBitField())
1499 continue;
1500
1501 // All the non-static data members are required to be nameable, so they
1502 // must all have names.
1503 if (!FD->getDeclName()) {
1504 if (RD->isLambda()) {
1505 S.Diag(Loc, diag::err_decomp_decl_lambda);
1506 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1507 return true;
1508 }
1509
1510 if (FD->isAnonymousStructOrUnion()) {
1511 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1512 << DecompType << FD->getType()->isUnionType();
1513 S.Diag(FD->getLocation(), diag::note_declared_at);
1514 return true;
1515 }
1516
1517 // FIXME: Are there any other ways we could have an anonymous member?
1518 }
1519 // The field must be accessible in the context of the structured binding.
1520 // We already checked that the base class is accessible.
1521 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1522 // const_cast here.
1524 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1526 BasePair.getAccess(), FD->getAccess())));
1527 }
1528 return false;
1529}
1530
1532 ValueDecl *Src, QualType DecompType,
1533 const CXXRecordDecl *OrigRD) {
1534 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1535 diag::err_incomplete_type))
1536 return true;
1537
1538 CXXCastPath BasePath;
1539 DeclAccessPair BasePair =
1540 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1541 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1542 if (!RD)
1543 return true;
1544 QualType BaseType = S.Context.getQualifiedType(
1545 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1546
1547 auto *DD = cast<DecompositionDecl>(Src);
1548 unsigned NumFields = llvm::count_if(
1549 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1551 return true;
1552
1553 // all of E's non-static data members shall be [...] well-formed
1554 // when named as e.name in the context of the structured binding,
1555 // E shall not have an anonymous union member, ...
1556 auto FlatBindings = DD->flat_bindings();
1557 assert(llvm::range_size(FlatBindings) == NumFields);
1558 auto FlatBindingsItr = FlatBindings.begin();
1559
1560 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1561 BasePair))
1562 return true;
1563
1564 for (auto *FD : RD->fields()) {
1565 if (FD->isUnnamedBitField())
1566 continue;
1567
1568 // We have a real field to bind.
1569 assert(FlatBindingsItr != FlatBindings.end());
1570 BindingDecl *B = *(FlatBindingsItr++);
1571 SourceLocation Loc = B->getLocation();
1572
1573 // Initialize the binding to Src.FD.
1574 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1575 if (E.isInvalid())
1576 return true;
1577 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1578 VK_LValue, &BasePath);
1579 if (E.isInvalid())
1580 return true;
1581 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1582 CXXScopeSpec(), FD,
1584 DeclarationNameInfo(FD->getDeclName(), Loc));
1585 if (E.isInvalid())
1586 return true;
1587
1588 // If the type of the member is T, the referenced type is cv T, where cv is
1589 // the cv-qualification of the decomposition expression.
1590 //
1591 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1592 // 'const' to the type of the field.
1593 Qualifiers Q = DecompType.getQualifiers();
1594 if (FD->isMutable())
1595 Q.removeConst();
1596 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1597 }
1598
1599 return false;
1600}
1601
1603 QualType DecompType = DD->getType();
1604
1605 // If the type of the decomposition is dependent, then so is the type of
1606 // each binding.
1607 if (DecompType->isDependentType()) {
1608 // Note that all of the types are still Null or PackExpansionType.
1609 for (auto *B : DD->bindings()) {
1610 // Do not overwrite any pack type.
1611 if (B->getType().isNull())
1612 B->setType(Context.DependentTy);
1613 }
1614 return;
1615 }
1616
1617 DecompType = DecompType.getNonReferenceType();
1619
1620 // C++1z [dcl.decomp]/2:
1621 // If E is an array type [...]
1622 // As an extension, we also support decomposition of built-in complex and
1623 // vector types.
1624 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1625 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1626 DD->setInvalidDecl();
1627 return;
1628 }
1629 if (auto *VT = DecompType->getAs<VectorType>()) {
1630 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1631 DD->setInvalidDecl();
1632 return;
1633 }
1634 if (auto *CT = DecompType->getAs<ComplexType>()) {
1635 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1636 DD->setInvalidDecl();
1637 return;
1638 }
1639
1640 // C++1z [dcl.decomp]/3:
1641 // if the expression std::tuple_size<E>::value is a well-formed integral
1642 // constant expression, [...]
1643 unsigned TupleSize;
1644 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1645 case IsTupleLike::Error:
1646 DD->setInvalidDecl();
1647 return;
1648
1649 case IsTupleLike::TupleLike:
1650 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1651 DD->setInvalidDecl();
1652 return;
1653
1654 case IsTupleLike::NotTupleLike:
1655 break;
1656 }
1657
1658 // C++1z [dcl.dcl]/8:
1659 // [E shall be of array or non-union class type]
1660 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1661 if (!RD || RD->isUnion()) {
1662 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1663 << DD << !RD << DecompType;
1664 DD->setInvalidDecl();
1665 return;
1666 }
1667
1668 // C++1z [dcl.decomp]/4:
1669 // all of E's non-static data members shall be [...] direct members of
1670 // E or of the same unambiguous public base class of E, ...
1671 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1672 DD->setInvalidDecl();
1673}
1674
1676 SourceLocation Loc) {
1677 const ASTContext &Ctx = getASTContext();
1678 assert(!T->isDependentType());
1679
1680 Qualifiers Quals;
1681 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1682 Quals.removeCVRQualifiers();
1683 T = Context.getQualifiedType(Unqual, Quals);
1684
1685 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1686 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1687 if (auto *VT = T->getAs<VectorType>())
1688 return VT->getNumElements();
1689 if (T->getAs<ComplexType>())
1690 return 2u;
1691
1692 unsigned TupleSize;
1693 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1694 case IsTupleLike::Error:
1695 return std::nullopt;
1696 case IsTupleLike::TupleLike:
1697 return TupleSize;
1698 case IsTupleLike::NotTupleLike:
1699 break;
1700 }
1701
1702 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1703 if (!OrigRD || OrigRD->isUnion())
1704 return std::nullopt;
1705
1706 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1707 return std::nullopt;
1708
1709 CXXCastPath BasePath;
1710 DeclAccessPair BasePair =
1711 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1712 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1713 if (!RD)
1714 return std::nullopt;
1715
1716 unsigned NumFields = llvm::count_if(
1717 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1718
1719 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1720 return std::nullopt;
1721
1722 return NumFields;
1723}
1724
1726 // Shortcut if exceptions are disabled.
1727 if (!getLangOpts().CXXExceptions)
1728 return;
1729
1730 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1731 "Should only be called if types are otherwise the same.");
1732
1733 QualType NewType = New->getType();
1734 QualType OldType = Old->getType();
1735
1736 // We're only interested in pointers and references to functions, as well
1737 // as pointers to member functions.
1738 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1739 NewType = R->getPointeeType();
1740 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1741 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1742 NewType = P->getPointeeType();
1743 OldType = OldType->castAs<PointerType>()->getPointeeType();
1744 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1745 NewType = M->getPointeeType();
1746 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1747 }
1748
1749 if (!NewType->isFunctionProtoType())
1750 return;
1751
1752 // There's lots of special cases for functions. For function pointers, system
1753 // libraries are hopefully not as broken so that we don't need these
1754 // workarounds.
1756 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1757 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1758 New->setInvalidDecl();
1759 }
1760}
1761
1762/// CheckCXXDefaultArguments - Verify that the default arguments for a
1763/// function declaration are well-formed according to C++
1764/// [dcl.fct.default].
1766 // This checking doesn't make sense for explicit specializations; their
1767 // default arguments are determined by the declaration we're specializing,
1768 // not by FD.
1770 return;
1771 if (auto *FTD = FD->getDescribedFunctionTemplate())
1772 if (FTD->isMemberSpecialization())
1773 return;
1774
1775 unsigned NumParams = FD->getNumParams();
1776 unsigned ParamIdx = 0;
1777
1778 // Find first parameter with a default argument
1779 for (; ParamIdx < NumParams; ++ParamIdx) {
1780 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1781 if (Param->hasDefaultArg())
1782 break;
1783 }
1784
1785 // C++20 [dcl.fct.default]p4:
1786 // In a given function declaration, each parameter subsequent to a parameter
1787 // with a default argument shall have a default argument supplied in this or
1788 // a previous declaration, unless the parameter was expanded from a
1789 // parameter pack, or shall be a function parameter pack.
1790 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1791 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1794 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1795 continue;
1796 if (Param->isInvalidDecl())
1797 /* We already complained about this parameter. */;
1798 else if (Param->getIdentifier())
1799 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1800 << Param->getIdentifier();
1801 else
1802 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1803 }
1804}
1805
1806/// Check that the given type is a literal type. Issue a diagnostic if not,
1807/// if Kind is Diagnose.
1808/// \return \c true if a problem has been found (and optionally diagnosed).
1809template <typename... Ts>
1811 SourceLocation Loc, QualType T, unsigned DiagID,
1812 Ts &&...DiagArgs) {
1813 if (T->isDependentType())
1814 return false;
1815
1816 switch (Kind) {
1818 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1819 std::forward<Ts>(DiagArgs)...);
1820
1822 return !T->isLiteralType(SemaRef.Context);
1823 }
1824
1825 llvm_unreachable("unknown CheckConstexprKind");
1826}
1827
1828/// Determine whether a destructor cannot be constexpr due to
1830 const CXXDestructorDecl *DD,
1832 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1833 "this check is obsolete for C++23");
1834 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1835 const CXXRecordDecl *RD =
1836 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1837 if (!RD || RD->hasConstexprDestructor())
1838 return true;
1839
1841 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1842 << static_cast<int>(DD->getConstexprKind()) << !FD
1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1844 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1845 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1846 }
1847 return false;
1848 };
1849
1850 const CXXRecordDecl *RD = DD->getParent();
1851 for (const CXXBaseSpecifier &B : RD->bases())
1852 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1853 return false;
1854 for (const FieldDecl *FD : RD->fields())
1855 if (!Check(FD->getLocation(), FD->getType(), FD))
1856 return false;
1857 return true;
1858}
1859
1860/// Check whether a function's parameter types are all literal types. If so,
1861/// return true. If not, produce a suitable diagnostic and return false.
1863 const FunctionDecl *FD,
1865 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1866 "this check is obsolete for C++23");
1867 unsigned ArgIndex = 0;
1868 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1869 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1870 e = FT->param_type_end();
1871 i != e; ++i, ++ArgIndex) {
1872 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1873 assert(PD && "null in a parameter list");
1874 SourceLocation ParamLoc = PD->getLocation();
1875 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1876 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1878 FD->isConsteval()))
1879 return false;
1880 }
1881 return true;
1882}
1883
1884/// Check whether a function's return type is a literal type. If so, return
1885/// true. If not, produce a suitable diagnostic and return false.
1886static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1888 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1889 "this check is obsolete for C++23");
1890 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1891 diag::err_constexpr_non_literal_return,
1892 FD->isConsteval()))
1893 return false;
1894 return true;
1895}
1896
1897/// Get diagnostic %select index for tag kind for
1898/// record diagnostic message.
1899/// WARNING: Indexes apply to particular diagnostics only!
1900///
1901/// \returns diagnostic %select index.
1903 switch (Tag) {
1905 return 0;
1907 return 1;
1908 case TagTypeKind::Class:
1909 return 2;
1910 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1911 }
1912}
1913
1914static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1915 Stmt *Body,
1917static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1918
1920 CheckConstexprKind Kind) {
1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1922 if (MD && MD->isInstance()) {
1923 // C++11 [dcl.constexpr]p4:
1924 // The definition of a constexpr constructor shall satisfy the following
1925 // constraints:
1926 // - the class shall not have any virtual base classes;
1927 //
1928 // FIXME: This only applies to constructors and destructors, not arbitrary
1929 // member functions.
1930 const CXXRecordDecl *RD = MD->getParent();
1931 if (RD->getNumVBases()) {
1933 return false;
1934
1935 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1936 << isa<CXXConstructorDecl>(NewFD)
1938 for (const auto &I : RD->vbases())
1939 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1940 << I.getSourceRange();
1941 return false;
1942 }
1943 }
1944
1945 if (!isa<CXXConstructorDecl>(NewFD)) {
1946 // C++11 [dcl.constexpr]p3:
1947 // The definition of a constexpr function shall satisfy the following
1948 // constraints:
1949 // - it shall not be virtual; (removed in C++20)
1950 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1951 if (Method && Method->isVirtual()) {
1952 if (getLangOpts().CPlusPlus20) {
1953 if (Kind == CheckConstexprKind::Diagnose)
1954 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1955 } else {
1957 return false;
1958
1959 Method = Method->getCanonicalDecl();
1960 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1961
1962 // If it's not obvious why this function is virtual, find an overridden
1963 // function which uses the 'virtual' keyword.
1964 const CXXMethodDecl *WrittenVirtual = Method;
1965 while (!WrittenVirtual->isVirtualAsWritten())
1966 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1967 if (WrittenVirtual != Method)
1968 Diag(WrittenVirtual->getLocation(),
1969 diag::note_overridden_virtual_function);
1970 return false;
1971 }
1972 }
1973
1974 // - its return type shall be a literal type; (removed in C++23)
1975 if (!getLangOpts().CPlusPlus23 &&
1976 !CheckConstexprReturnType(*this, NewFD, Kind))
1977 return false;
1978 }
1979
1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1981 // A destructor can be constexpr only if the defaulted destructor could be;
1982 // we don't need to check the members and bases if we already know they all
1983 // have constexpr destructors. (removed in C++23)
1984 if (!getLangOpts().CPlusPlus23 &&
1985 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1987 return false;
1988 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1989 return false;
1990 }
1991 }
1992
1993 // - each of its parameter types shall be a literal type; (removed in C++23)
1994 if (!getLangOpts().CPlusPlus23 &&
1995 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1996 return false;
1997
1998 Stmt *Body = NewFD->getBody();
1999 assert(Body &&
2000 "CheckConstexprFunctionDefinition called on function with no body");
2001 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2002}
2003
2004/// Check the given declaration statement is legal within a constexpr function
2005/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2006///
2007/// \return true if the body is OK (maybe only as an extension), false if we
2008/// have diagnosed a problem.
2009static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2010 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2012 // C++11 [dcl.constexpr]p3 and p4:
2013 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2014 // contain only
2015 for (const auto *DclIt : DS->decls()) {
2016 switch (DclIt->getKind()) {
2017 case Decl::StaticAssert:
2018 case Decl::Using:
2019 case Decl::UsingShadow:
2020 case Decl::UsingDirective:
2021 case Decl::UnresolvedUsingTypename:
2022 case Decl::UnresolvedUsingValue:
2023 case Decl::UsingEnum:
2024 // - static_assert-declarations
2025 // - using-declarations,
2026 // - using-directives,
2027 // - using-enum-declaration
2028 continue;
2029
2030 case Decl::Typedef:
2031 case Decl::TypeAlias: {
2032 // - typedef declarations and alias-declarations that do not define
2033 // classes or enumerations,
2034 const auto *TN = cast<TypedefNameDecl>(DclIt);
2035 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2036 // Don't allow variably-modified types in constexpr functions.
2038 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2039 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2040 << TL.getSourceRange() << TL.getType()
2042 }
2043 return false;
2044 }
2045 continue;
2046 }
2047
2048 case Decl::Enum:
2049 case Decl::CXXRecord:
2050 // C++1y allows types to be defined, not just declared.
2051 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2053 SemaRef.DiagCompat(DS->getBeginLoc(),
2054 diag_compat::constexpr_type_definition)
2056 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2057 return false;
2058 }
2059 }
2060 continue;
2061
2062 case Decl::EnumConstant:
2063 case Decl::IndirectField:
2064 case Decl::ParmVar:
2065 // These can only appear with other declarations which are banned in
2066 // C++11 and permitted in C++1y, so ignore them.
2067 continue;
2068
2069 case Decl::Var:
2070 case Decl::Decomposition: {
2071 // C++1y [dcl.constexpr]p3 allows anything except:
2072 // a definition of a variable of non-literal type or of static or
2073 // thread storage duration or [before C++2a] for which no
2074 // initialization is performed.
2075 const auto *VD = cast<VarDecl>(DclIt);
2076 if (VD->isThisDeclarationADefinition()) {
2077 if (VD->isStaticLocal()) {
2079 SemaRef.DiagCompat(VD->getLocation(),
2080 diag_compat::constexpr_static_var)
2082 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2083 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2084 return false;
2085 }
2086 }
2087 if (SemaRef.LangOpts.CPlusPlus23) {
2088 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2089 diag::warn_cxx20_compat_constexpr_var,
2091 } else if (CheckLiteralType(
2092 SemaRef, Kind, VD->getLocation(), VD->getType(),
2093 diag::err_constexpr_local_var_non_literal_type,
2095 return false;
2096 }
2097 if (!VD->getType()->isDependentType() &&
2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2100 SemaRef.DiagCompat(VD->getLocation(),
2101 diag_compat::constexpr_local_var_no_init)
2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2104 return false;
2105 }
2106 continue;
2107 }
2108 }
2110 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2112 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2113 return false;
2114 }
2115 continue;
2116 }
2117
2118 case Decl::NamespaceAlias:
2119 case Decl::Function:
2120 // These are disallowed in C++11 and permitted in C++1y. Allow them
2121 // everywhere as an extension.
2122 if (!Cxx1yLoc.isValid())
2123 Cxx1yLoc = DS->getBeginLoc();
2124 continue;
2125
2126 default:
2128 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2129 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2130 }
2131 return false;
2132 }
2133 }
2134
2135 return true;
2136}
2137
2138/// Check that the given field is initialized within a constexpr constructor.
2139///
2140/// \param Dcl The constexpr constructor being checked.
2141/// \param Field The field being checked. This may be a member of an anonymous
2142/// struct or union nested within the class being checked.
2143/// \param Inits All declarations, including anonymous struct/union members and
2144/// indirect members, for which any initialization was provided.
2145/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2146/// multiple notes for different members to the same error.
2147/// \param Kind Whether we're diagnosing a constructor as written or determining
2148/// whether the formal requirements are satisfied.
2149/// \return \c false if we're checking for validity and the constructor does
2150/// not satisfy the requirements on a constexpr constructor.
2152 const FunctionDecl *Dcl,
2153 FieldDecl *Field,
2155 bool &Diagnosed,
2157 // In C++20 onwards, there's nothing to check for validity.
2159 SemaRef.getLangOpts().CPlusPlus20)
2160 return true;
2161
2162 if (Field->isInvalidDecl())
2163 return true;
2164
2165 if (Field->isUnnamedBitField())
2166 return true;
2167
2168 // Anonymous unions with no variant members and empty anonymous structs do not
2169 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2170 // indirect fields don't need initializing.
2171 if (Field->isAnonymousStructOrUnion() &&
2172 (Field->getType()->isUnionType()
2173 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2174 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2175 return true;
2176
2177 if (!Inits.count(Field)) {
2179 if (!Diagnosed) {
2180 SemaRef.DiagCompat(Dcl->getLocation(),
2181 diag_compat::constexpr_ctor_missing_init);
2182 Diagnosed = true;
2183 }
2184 SemaRef.Diag(Field->getLocation(),
2185 diag::note_constexpr_ctor_missing_init);
2186 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2187 return false;
2188 }
2189 } else if (Field->isAnonymousStructOrUnion()) {
2190 const auto *RD = Field->getType()->castAsRecordDecl();
2191 for (auto *I : RD->fields())
2192 // If an anonymous union contains an anonymous struct of which any member
2193 // is initialized, all members must be initialized.
2194 if (!RD->isUnion() || Inits.count(I))
2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2196 Kind))
2197 return false;
2198 }
2199 return true;
2200}
2201
2202/// Check the provided statement is allowed in a constexpr function
2203/// definition.
2204static bool
2207 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2208 SourceLocation &Cxx2bLoc,
2210 // - its function-body shall be [...] a compound-statement that contains only
2211 switch (S->getStmtClass()) {
2212 case Stmt::NullStmtClass:
2213 // - null statements,
2214 return true;
2215
2216 case Stmt::DeclStmtClass:
2217 // - static_assert-declarations
2218 // - using-declarations,
2219 // - using-directives,
2220 // - typedef declarations and alias-declarations that do not define
2221 // classes or enumerations,
2222 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2223 return false;
2224 return true;
2225
2226 case Stmt::ReturnStmtClass:
2227 // - and exactly one return statement;
2228 if (isa<CXXConstructorDecl>(Dcl)) {
2229 // C++1y allows return statements in constexpr constructors.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2235 ReturnStmts.push_back(S->getBeginLoc());
2236 return true;
2237
2238 case Stmt::AttributedStmtClass:
2239 // Attributes on a statement don't affect its formal kind and hence don't
2240 // affect its validity in a constexpr function.
2242 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2243 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2244
2245 case Stmt::CompoundStmtClass: {
2246 // C++1y allows compound-statements.
2247 if (!Cxx1yLoc.isValid())
2248 Cxx1yLoc = S->getBeginLoc();
2249
2250 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2251 for (auto *BodyIt : CompStmt->body()) {
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254 return false;
2255 }
2256 return true;
2257 }
2258
2259 case Stmt::IfStmtClass: {
2260 // C++1y allows if-statements.
2261 if (!Cxx1yLoc.isValid())
2262 Cxx1yLoc = S->getBeginLoc();
2263
2264 IfStmt *If = cast<IfStmt>(S);
2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2267 return false;
2268 if (If->getElse() &&
2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2271 return false;
2272 return true;
2273 }
2274
2275 case Stmt::WhileStmtClass:
2276 case Stmt::DoStmtClass:
2277 case Stmt::ForStmtClass:
2278 case Stmt::CXXForRangeStmtClass:
2279 case Stmt::ContinueStmtClass:
2280 // C++1y allows all of these. We don't allow them as extensions in C++11,
2281 // because they don't make sense without variable mutation.
2282 if (!SemaRef.getLangOpts().CPlusPlus14)
2283 break;
2284 if (!Cxx1yLoc.isValid())
2285 Cxx1yLoc = S->getBeginLoc();
2286 for (Stmt *SubStmt : S->children()) {
2287 if (SubStmt &&
2288 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2289 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2290 return false;
2291 }
2292 return true;
2293
2294 case Stmt::SwitchStmtClass:
2295 case Stmt::CaseStmtClass:
2296 case Stmt::DefaultStmtClass:
2297 case Stmt::BreakStmtClass:
2298 // C++1y allows switch-statements, and since they don't need variable
2299 // mutation, we can reasonably allow them in C++11 as an extension.
2300 if (!Cxx1yLoc.isValid())
2301 Cxx1yLoc = S->getBeginLoc();
2302 for (Stmt *SubStmt : S->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308 return true;
2309
2310 case Stmt::LabelStmtClass:
2311 case Stmt::GotoStmtClass:
2312 if (Cxx2bLoc.isInvalid())
2313 Cxx2bLoc = S->getBeginLoc();
2314 for (Stmt *SubStmt : S->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320 return true;
2321
2322 case Stmt::GCCAsmStmtClass:
2323 case Stmt::MSAsmStmtClass:
2324 // C++2a allows inline assembly statements.
2325 case Stmt::CXXTryStmtClass:
2326 if (Cxx2aLoc.isInvalid())
2327 Cxx2aLoc = S->getBeginLoc();
2328 for (Stmt *SubStmt : S->children()) {
2329 if (SubStmt &&
2330 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2332 return false;
2333 }
2334 return true;
2335
2336 case Stmt::CXXCatchStmtClass:
2337 // Do not bother checking the language mode (already covered by the
2338 // try block check).
2340 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 return true;
2344
2345 default:
2346 if (!isa<Expr>(S))
2347 break;
2348
2349 // C++1y allows expression-statements.
2350 if (!Cxx1yLoc.isValid())
2351 Cxx1yLoc = S->getBeginLoc();
2352 return true;
2353 }
2354
2356 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2357 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2358 }
2359 return false;
2360}
2361
2362/// Check the body for the given constexpr function declaration only contains
2363/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2364///
2365/// \return true if the body is OK, false if we have found or diagnosed a
2366/// problem.
2367static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2368 Stmt *Body,
2371
2372 if (isa<CXXTryStmt>(Body)) {
2373 // C++11 [dcl.constexpr]p3:
2374 // The definition of a constexpr function shall satisfy the following
2375 // constraints: [...]
2376 // - its function-body shall be = delete, = default, or a
2377 // compound-statement
2378 //
2379 // C++11 [dcl.constexpr]p4:
2380 // In the definition of a constexpr constructor, [...]
2381 // - its function-body shall not be a function-try-block;
2382 //
2383 // This restriction is lifted in C++2a, as long as inner statements also
2384 // apply the general constexpr rules.
2385 switch (Kind) {
2387 if (!SemaRef.getLangOpts().CPlusPlus20)
2388 return false;
2389 break;
2390
2392 SemaRef.DiagCompat(Body->getBeginLoc(),
2393 diag_compat::constexpr_function_try_block)
2395 break;
2396 }
2397 }
2398
2399 // - its function-body shall be [...] a compound-statement that contains only
2400 // [... list of cases ...]
2401 //
2402 // Note that walking the children here is enough to properly check for
2403 // CompoundStmt and CXXTryStmt body.
2404 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2405 for (Stmt *SubStmt : Body->children()) {
2406 if (SubStmt &&
2407 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2408 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2409 return false;
2410 }
2411
2413 // If this is only valid as an extension, report that we don't satisfy the
2414 // constraints of the current language.
2415 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2416 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2417 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2418 return false;
2419 } else if (Cxx2bLoc.isValid()) {
2420 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2422 } else if (Cxx2aLoc.isValid()) {
2423 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2425 } else if (Cxx1yLoc.isValid()) {
2426 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2428 }
2429
2431 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2432 const CXXRecordDecl *RD = Constructor->getParent();
2433 // DR1359:
2434 // - every non-variant non-static data member and base class sub-object
2435 // shall be initialized;
2436 // DR1460:
2437 // - if the class is a union having variant members, exactly one of them
2438 // shall be initialized;
2439 if (RD->isUnion()) {
2440 if (Constructor->getNumCtorInitializers() == 0 &&
2441 RD->hasVariantMembers()) {
2443 SemaRef.DiagCompat(Dcl->getLocation(),
2444 diag_compat::constexpr_union_ctor_no_init);
2445 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2446 return false;
2447 }
2448 }
2449 } else if (!Constructor->isDependentContext() &&
2450 !Constructor->isDelegatingConstructor()) {
2451 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2452
2453 // Skip detailed checking if we have enough initializers, and we would
2454 // allow at most one initializer per member.
2455 bool AnyAnonStructUnionMembers = false;
2456 unsigned Fields = 0;
2458 E = RD->field_end(); I != E; ++I, ++Fields) {
2459 if (I->isAnonymousStructOrUnion()) {
2460 AnyAnonStructUnionMembers = true;
2461 break;
2462 }
2463 }
2464 // DR1460:
2465 // - if the class is a union-like class, but is not a union, for each of
2466 // its anonymous union members having variant members, exactly one of
2467 // them shall be initialized;
2468 if (AnyAnonStructUnionMembers ||
2469 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2470 // Check initialization of non-static data members. Base classes are
2471 // always initialized so do not need to be checked. Dependent bases
2472 // might not have initializers in the member initializer list.
2474 for (const auto *I: Constructor->inits()) {
2475 if (FieldDecl *FD = I->getMember())
2476 Inits.insert(FD);
2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2478 Inits.insert(ID->chain_begin(), ID->chain_end());
2479 }
2480
2481 bool Diagnosed = false;
2482 for (auto *I : RD->fields())
2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2484 Kind))
2485 return false;
2486 }
2487 }
2488 } else {
2489 if (ReturnStmts.empty()) {
2490 switch (Kind) {
2492 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2493 return false;
2494 break;
2495
2497 // The formal requirements don't include this rule in C++14, even
2498 // though the "must be able to produce a constant expression" rules
2499 // still imply it in some cases.
2500 if (!SemaRef.getLangOpts().CPlusPlus14)
2501 return false;
2502 break;
2503 }
2504 } else if (ReturnStmts.size() > 1) {
2505 switch (Kind) {
2507 SemaRef.DiagCompat(ReturnStmts.back(),
2508 diag_compat::constexpr_body_multiple_return);
2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2510 SemaRef.Diag(ReturnStmts[I],
2511 diag::note_constexpr_body_previous_return);
2512 break;
2513
2515 if (!SemaRef.getLangOpts().CPlusPlus14)
2516 return false;
2517 break;
2518 }
2519 }
2520 }
2521
2522 // C++11 [dcl.constexpr]p5:
2523 // if no function argument values exist such that the function invocation
2524 // substitution would produce a constant expression, the program is
2525 // ill-formed; no diagnostic required.
2526 // C++11 [dcl.constexpr]p3:
2527 // - every constructor call and implicit conversion used in initializing the
2528 // return value shall be one of those allowed in a constant expression.
2529 // C++11 [dcl.constexpr]p4:
2530 // - every constructor involved in initializing non-static data members and
2531 // base class sub-objects shall be a constexpr constructor.
2532 //
2533 // Note that this rule is distinct from the "requirements for a constexpr
2534 // function", so is not checked in CheckValid mode. Because the check for
2535 // constexpr potential is expensive, skip the check if the diagnostic is
2536 // disabled, the function is declared in a system header, or we're in C++23
2537 // or later mode (see https://wg21.link/P2448).
2538 bool SkipCheck =
2539 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2540 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2541 SemaRef.getDiagnostics().isIgnored(
2542 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2545 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2546 SemaRef.Diag(Dcl->getLocation(),
2547 diag::ext_constexpr_function_never_constant_expr)
2548 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2549 << Dcl->getNameInfo().getSourceRange();
2550 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2551 SemaRef.Diag(Diags[I].first, Diags[I].second);
2552 // Don't return false here: we allow this for compatibility in
2553 // system headers.
2554 }
2555
2556 return true;
2557}
2558
2560 const FunctionDecl *Dcl) {
2561 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2563 // Skip emitting a missing return error diagnostic for non-void functions
2564 // since C++23 no longer mandates constexpr functions to yield constant
2565 // expressions.
2566 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2567 return true;
2568
2569 // C++14 doesn't require constexpr functions to contain a 'return'
2570 // statement. We still do, unless the return type might be void, because
2571 // otherwise if there's no return statement, the function cannot
2572 // be used in a core constant expression.
2573 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2574 SemaRef.Diag(Dcl->getLocation(),
2575 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2576 : diag::err_constexpr_body_no_return)
2577 << Dcl->isConsteval();
2578 return OK;
2579}
2580
2582 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2584 return true;
2588 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2589 if (it != UndefinedButUsed.end()) {
2590 Diag(it->second, diag::err_immediate_function_used_before_definition)
2591 << it->first;
2592 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2593 if (FD->isImmediateFunction() && !FD->isConsteval())
2595 return false;
2596 }
2597 }
2598 return true;
2599}
2600
2602 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2603 "expected an immediate function");
2604 assert(FD->hasBody() && "expected the function to have a body");
2605 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2606 Sema &SemaRef;
2607
2608 const FunctionDecl *ImmediateFn;
2609 bool ImmediateFnIsConstructor;
2610 CXXConstructorDecl *CurrentConstructor = nullptr;
2611 CXXCtorInitializer *CurrentInit = nullptr;
2612
2613 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2614 : SemaRef(SemaRef), ImmediateFn(FD),
2615 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2616 ShouldVisitImplicitCode = true;
2617 ShouldVisitLambdaBody = false;
2618 }
2619
2620 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2621 SourceLocation Loc = E->getBeginLoc();
2622 SourceRange Range = E->getSourceRange();
2623 if (CurrentConstructor && CurrentInit) {
2624 Loc = CurrentConstructor->getLocation();
2625 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2626 : SourceRange();
2627 }
2628
2629 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2630
2631 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2633 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2634 << (InitializedField != nullptr)
2635 << (CurrentInit && !CurrentInit->isWritten())
2636 << InitializedField << Range;
2637 }
2638 bool TraverseCallExpr(CallExpr *E) override {
2639 if (const auto *DR =
2640 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2641 DR && DR->isImmediateEscalating()) {
2642 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2643 return false;
2644 }
2645
2646 for (Expr *A : E->arguments())
2647 if (!TraverseStmt(A))
2648 return false;
2649
2650 return true;
2651 }
2652
2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2655 ReferencedFn && E->isImmediateEscalating()) {
2656 Diag(E, ReferencedFn, /*IsCall=*/false);
2657 return false;
2658 }
2659
2660 return true;
2661 }
2662
2663 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2665 if (E->isImmediateEscalating()) {
2666 Diag(E, D, /*IsCall=*/true);
2667 return false;
2668 }
2669 return true;
2670 }
2671
2672 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2673 llvm::SaveAndRestore RAII(CurrentInit, Init);
2675 }
2676
2677 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2678 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2679 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2680 }
2681
2682 bool TraverseType(QualType T, bool TraverseQualifier) override {
2683 return true;
2684 }
2685 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2686
2687 } Visitor(*this, FD);
2688 Visitor.TraverseDecl(FD);
2689}
2690
2692 assert(getLangOpts().CPlusPlus && "No class names in C!");
2693
2694 if (SS && SS->isInvalid())
2695 return nullptr;
2696
2697 if (SS && SS->isNotEmpty()) {
2698 DeclContext *DC = computeDeclContext(*SS, true);
2699 return dyn_cast_or_null<CXXRecordDecl>(DC);
2700 }
2701
2702 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2703}
2704
2706 const CXXScopeSpec *SS) {
2707 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2708 return CurDecl && &II == CurDecl->getIdentifier();
2709}
2710
2712 assert(getLangOpts().CPlusPlus && "No class names in C!");
2713
2714 if (!getLangOpts().SpellChecking)
2715 return false;
2716
2717 CXXRecordDecl *CurDecl;
2718 if (SS && SS->isSet() && !SS->isInvalid()) {
2719 DeclContext *DC = computeDeclContext(*SS, true);
2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2721 } else
2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2723
2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2725 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2726 < II->getLength()) {
2727 II = CurDecl->getIdentifier();
2728 return true;
2729 }
2730
2731 return false;
2732}
2733
2735 SourceRange SpecifierRange,
2736 bool Virtual, AccessSpecifier Access,
2737 TypeSourceInfo *TInfo,
2738 SourceLocation EllipsisLoc) {
2739 QualType BaseType = TInfo->getType();
2740 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2741 if (BaseType->containsErrors()) {
2742 // Already emitted a diagnostic when parsing the error type.
2743 return nullptr;
2744 }
2745
2746 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2747 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2748 << TInfo->getTypeLoc().getSourceRange();
2749 EllipsisLoc = SourceLocation();
2750 }
2751
2752 auto *BaseDecl =
2753 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2754 // C++ [class.derived.general]p2:
2755 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2756 // that is not an incompletely defined class; any cv-qualifiers are
2757 // ignored.
2758 if (BaseDecl) {
2759 // C++ [class.union.general]p4:
2760 // [...] A union shall not be used as a base class.
2761 if (BaseDecl->isUnion()) {
2762 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2763 return nullptr;
2764 }
2765
2766 if (BaseType.hasQualifiers()) {
2767 std::string Quals =
2768 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2769 Diag(BaseLoc, diag::warn_qual_base_type)
2770 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2771 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2772 }
2773
2774 // For the MS ABI, propagate DLL attributes to base class templates.
2775 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2776 Context.getTargetInfo().getTriple().isPS()) {
2777 if (Attr *ClassAttr = getDLLAttr(Class)) {
2778 if (auto *BaseSpec =
2779 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2781 BaseLoc);
2782 }
2783 }
2784 }
2785
2786 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2787 SpecifierRange)) {
2788 Class->setInvalidDecl();
2789 return nullptr;
2790 }
2791
2792 BaseDecl = BaseDecl->getDefinition();
2793 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2794
2795 // Microsoft docs say:
2796 // "If a base-class has a code_seg attribute, derived classes must have the
2797 // same attribute."
2798 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2799 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2800 if ((DerivedCSA || BaseCSA) &&
2801 (!BaseCSA || !DerivedCSA ||
2802 BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2804 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2805 << BaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as
2810 // a base class:
2811 // - If the layout determines that a base comes before another base,
2812 // the flexible array member would index into the subsequent base.
2813 // - If the layout determines that base comes before the derived class,
2814 // the flexible array member would index into the derived class.
2815 if (BaseDecl->hasFlexibleArrayMember()) {
2816 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2817 << BaseDecl->getDeclName();
2818 return nullptr;
2819 }
2820
2821 // C++ [class]p3:
2822 // If a class is marked final and it appears as a base-type-specifier in
2823 // base-clause, the program is ill-formed.
2824 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2825 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2827 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2828 << BaseDecl->getDeclName() << FA->getRange();
2829 return nullptr;
2830 }
2831
2832 // If the base class is invalid the derived class is as well.
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835 } else if (BaseType->isDependentType()) {
2836 // Make sure that we don't make an ill-formed AST where the type of the
2837 // Class is non-dependent and its attached base class specifier is an
2838 // dependent type, which violates invariants in many clang code paths (e.g.
2839 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2840 // explicitly mark the Class decl invalid. The diagnostic was already
2841 // emitted.
2842 if (!Class->isDependentContext())
2843 Class->setInvalidDecl();
2844 } else {
2845 // The base class is some non-dependent non-class type.
2846 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2847 return nullptr;
2848 }
2849
2850 // In HLSL, unspecified class access is public rather than private.
2851 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2852 Access == AS_none)
2853 Access = AS_public;
2854
2855 // Create the base specifier.
2856 return new (Context) CXXBaseSpecifier(
2857 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2858 Access, TInfo, EllipsisLoc);
2859}
2860
2862 const ParsedAttributesView &Attributes,
2863 bool Virtual, AccessSpecifier Access,
2864 ParsedType basetype, SourceLocation BaseLoc,
2865 SourceLocation EllipsisLoc) {
2866 if (!classdecl)
2867 return true;
2868
2869 AdjustDeclIfTemplate(classdecl);
2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2871 if (!Class)
2872 return true;
2873
2874 // We haven't yet attached the base specifiers.
2875 Class->setIsParsingBaseSpecifiers();
2876
2877 // We do not support any C++11 attributes on base-specifiers yet.
2878 // Diagnose any attributes we see.
2879 for (const ParsedAttr &AL : Attributes) {
2880 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2881 continue;
2882 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2884 else
2885 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2887 }
2888
2889 TypeSourceInfo *TInfo = nullptr;
2890 GetTypeFromParser(basetype, &TInfo);
2891
2892 if (EllipsisLoc.isInvalid() &&
2893 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2895 return true;
2896
2897 // C++ [class.union.general]p4:
2898 // [...] A union shall not have base classes.
2899 if (Class->isUnion()) {
2900 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2901 << SpecifierRange;
2902 return true;
2903 }
2904
2905 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2906 Virtual, Access, TInfo,
2907 EllipsisLoc))
2908 return BaseSpec;
2909
2910 Class->setInvalidDecl();
2911 return true;
2912}
2913
2914/// Use small set to collect indirect bases. As this is only used
2915/// locally, there's no need to abstract the small size parameter.
2917
2918/// Recursively add the bases of Type. Don't add Type itself.
2919static void
2921 const QualType &Type)
2922{
2923 // Even though the incoming type is a base, it might not be
2924 // a class -- it could be a template parm, for instance.
2925 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2926 // Iterate over its bases.
2927 for (const auto &BaseSpec : Decl->bases()) {
2928 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2929 .getUnqualifiedType();
2930 if (Set.insert(Base).second)
2931 // If we've not already seen it, recurse.
2932 NoteIndirectBases(Context, Set, Base);
2933 }
2934 }
2935}
2936
2939 if (Bases.empty())
2940 return false;
2941
2942 // Used to keep track of which base types we have already seen, so
2943 // that we can properly diagnose redundant direct base types. Note
2944 // that the key is always the unqualified canonical type of the base
2945 // class.
2946 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2947
2948 // Used to track indirect bases so we can see if a direct base is
2949 // ambiguous.
2950 IndirectBaseSet IndirectBaseTypes;
2951
2952 // Copy non-redundant base specifiers into permanent storage.
2953 unsigned NumGoodBases = 0;
2954 bool Invalid = false;
2955 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2956 QualType NewBaseType
2957 = Context.getCanonicalType(Bases[idx]->getType());
2958 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2959
2960 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2961 if (KnownBase) {
2962 // C++ [class.mi]p3:
2963 // A class shall not be specified as a direct base class of a
2964 // derived class more than once.
2965 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2966 << KnownBase->getType() << Bases[idx]->getSourceRange();
2967
2968 // Delete the duplicate base class specifier; we're going to
2969 // overwrite its pointer later.
2970 Context.Deallocate(Bases[idx]);
2971
2972 Invalid = true;
2973 } else {
2974 // Okay, add this new base class.
2975 KnownBase = Bases[idx];
2976 Bases[NumGoodBases++] = Bases[idx];
2977
2978 if (NewBaseType->isDependentType())
2979 continue;
2980 // Note this base's direct & indirect bases, if there could be ambiguity.
2981 if (Bases.size() > 1)
2982 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2983
2984 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
2985 if (Class->isInterface() &&
2986 (!RD->isInterfaceLike() ||
2987 KnownBase->getAccessSpecifier() != AS_public)) {
2988 // The Microsoft extension __interface does not permit bases that
2989 // are not themselves public interfaces.
2990 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2991 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2992 << RD->getSourceRange();
2993 Invalid = true;
2994 }
2995 if (RD->hasAttr<WeakAttr>())
2996 Class->addAttr(WeakAttr::CreateImplicit(Context));
2997 }
2998 }
2999 }
3000
3001 // Attach the remaining base class specifiers to the derived class.
3002 Class->setBases(Bases.data(), NumGoodBases);
3003
3004 // Check that the only base classes that are duplicate are virtual.
3005 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3006 // Check whether this direct base is inaccessible due to ambiguity.
3007 QualType BaseType = Bases[idx]->getType();
3008
3009 // Skip all dependent types in templates being used as base specifiers.
3010 // Checks below assume that the base specifier is a CXXRecord.
3011 if (BaseType->isDependentType())
3012 continue;
3013
3014 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3015 .getUnqualifiedType();
3016
3017 if (IndirectBaseTypes.count(CanonicalBase)) {
3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3019 /*DetectVirtual=*/true);
3020 bool found
3021 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3022 assert(found);
3023 (void)found;
3024
3025 if (Paths.isAmbiguous(CanonicalBase))
3026 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3027 << BaseType << getAmbiguousPathsDisplayString(Paths)
3028 << Bases[idx]->getSourceRange();
3029 else
3030 assert(Bases[idx]->isVirtual());
3031 }
3032
3033 // Delete the base class specifier, since its data has been copied
3034 // into the CXXRecordDecl.
3035 Context.Deallocate(Bases[idx]);
3036 }
3037
3038 return Invalid;
3039}
3040
3043 if (!ClassDecl || Bases.empty())
3044 return;
3045
3046 AdjustDeclIfTemplate(ClassDecl);
3047 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3048}
3049
3051 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3052 if (!getLangOpts().CPlusPlus)
3053 return false;
3054
3055 if (!Base || !Derived)
3056 return false;
3057
3058 // If either the base or the derived type is invalid, don't try to
3059 // check whether one is derived from the other.
3060 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3061 return false;
3062
3063 // FIXME: In a modules build, do we need the entire path to be visible for us
3064 // to be able to use the inheritance relationship?
3065 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3066 !Derived->isBeingDefined())
3067 return false;
3068
3069 return Derived->isDerivedFrom(Base, Paths);
3070}
3071
3074 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3075 /*DetectVirtual=*/false);
3076 return IsDerivedFrom(Loc, Derived, Base, Paths);
3077}
3078
3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3081 /*DetectVirtual=*/false);
3082 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3083 Base->getAsCXXRecordDecl(), Paths);
3084}
3085
3087 CXXBasePaths &Paths) {
3088 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3089 Base->getAsCXXRecordDecl(), Paths);
3090}
3091
3092static void BuildBasePathArray(const CXXBasePath &Path,
3093 CXXCastPath &BasePathArray) {
3094 // We first go backward and check if we have a virtual base.
3095 // FIXME: It would be better if CXXBasePath had the base specifier for
3096 // the nearest virtual base.
3097 unsigned Start = 0;
3098 for (unsigned I = Path.size(); I != 0; --I) {
3099 if (Path[I - 1].Base->isVirtual()) {
3100 Start = I - 1;
3101 break;
3102 }
3103 }
3104
3105 // Now add all bases.
3106 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3107 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3108}
3109
3110
3112 CXXCastPath &BasePathArray) {
3113 assert(BasePathArray.empty() && "Base path array must be empty!");
3114 assert(Paths.isRecordingPaths() && "Must record paths!");
3115 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3116}
3117
3118bool
3120 unsigned InaccessibleBaseID,
3121 unsigned AmbiguousBaseConvID,
3122 SourceLocation Loc, SourceRange Range,
3123 DeclarationName Name,
3124 CXXCastPath *BasePath,
3125 bool IgnoreAccess) {
3126 // First, determine whether the path from Derived to Base is
3127 // ambiguous. This is slightly more expensive than checking whether
3128 // the Derived to Base conversion exists, because here we need to
3129 // explore multiple paths to determine if there is an ambiguity.
3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131 /*DetectVirtual=*/false);
3132 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3133 if (!DerivationOkay)
3134 return true;
3135
3136 const CXXBasePath *Path = nullptr;
3137 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3138 Path = &Paths.front();
3139
3140 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3141 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3142 // user to access such bases.
3143 if (!Path && getLangOpts().MSVCCompat) {
3144 for (const CXXBasePath &PossiblePath : Paths) {
3145 if (PossiblePath.size() == 1) {
3146 Path = &PossiblePath;
3147 if (AmbiguousBaseConvID)
3148 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3149 << Base << Derived << Range;
3150 break;
3151 }
3152 }
3153 }
3154
3155 if (Path) {
3156 if (!IgnoreAccess) {
3157 // Check that the base class can be accessed.
3158 switch (
3159 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3160 case AR_inaccessible:
3161 return true;
3162 case AR_accessible:
3163 case AR_dependent:
3164 case AR_delayed:
3165 break;
3166 }
3167 }
3168
3169 // Build a base path if necessary.
3170 if (BasePath)
3171 ::BuildBasePathArray(*Path, *BasePath);
3172 return false;
3173 }
3174
3175 if (AmbiguousBaseConvID) {
3176 // We know that the derived-to-base conversion is ambiguous, and
3177 // we're going to produce a diagnostic. Perform the derived-to-base
3178 // search just one more time to compute all of the possible paths so
3179 // that we can print them out. This is more expensive than any of
3180 // the previous derived-to-base checks we've done, but at this point
3181 // performance isn't as much of an issue.
3182 Paths.clear();
3183 Paths.setRecordingPaths(true);
3184 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3185 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3186 (void)StillOkay;
3187
3188 // Build up a textual representation of the ambiguous paths, e.g.,
3189 // D -> B -> A, that will be used to illustrate the ambiguous
3190 // conversions in the diagnostic. We only print one of the paths
3191 // to each base class subobject.
3192 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3193
3194 Diag(Loc, AmbiguousBaseConvID)
3195 << Derived << Base << PathDisplayStr << Range << Name;
3196 }
3197 return true;
3198}
3199
3200bool
3202 SourceLocation Loc, SourceRange Range,
3203 CXXCastPath *BasePath,
3204 bool IgnoreAccess) {
3206 Derived, Base, diag::err_upcast_to_inaccessible_base,
3207 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3208 BasePath, IgnoreAccess);
3209}
3210
3212 std::string PathDisplayStr;
3213 std::set<unsigned> DisplayedPaths;
3214 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3215 Path != Paths.end(); ++Path) {
3216 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3217 // We haven't displayed a path to this particular base
3218 // class subobject yet.
3219 PathDisplayStr += "\n ";
3220 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3221 .getAsString();
3222 for (CXXBasePath::const_iterator Element = Path->begin();
3223 Element != Path->end(); ++Element)
3224 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3225 }
3226 }
3227
3228 return PathDisplayStr;
3229}
3230
3231//===----------------------------------------------------------------------===//
3232// C++ class member Handling
3233//===----------------------------------------------------------------------===//
3234
3236 SourceLocation ColonLoc,
3237 const ParsedAttributesView &Attrs) {
3238 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3240 ASLoc, ColonLoc);
3241 CurContext->addHiddenDecl(ASDecl);
3242 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3243}
3244
3246 if (D->isInvalidDecl())
3247 return;
3248
3249 // We only care about "override" and "final" declarations.
3250 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3251 return;
3252
3253 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3254
3255 // We can't check dependent instance methods.
3256 if (MD && MD->isInstance() &&
3257 (MD->getParent()->hasAnyDependentBases() ||
3258 MD->getType()->isDependentType()))
3259 return;
3260
3261 if (MD && !MD->isVirtual()) {
3262 // If we have a non-virtual method, check if it hides a virtual method.
3263 // (In that case, it's most likely the method has the wrong type.)
3264 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3265 FindHiddenVirtualMethods(MD, OverloadedMethods);
3266
3267 if (!OverloadedMethods.empty()) {
3268 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3269 Diag(OA->getLocation(),
3270 diag::override_keyword_hides_virtual_member_function)
3271 << "override" << (OverloadedMethods.size() > 1);
3272 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3273 Diag(FA->getLocation(),
3274 diag::override_keyword_hides_virtual_member_function)
3275 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3276 << (OverloadedMethods.size() > 1);
3277 }
3278 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3279 MD->setInvalidDecl();
3280 return;
3281 }
3282 // Fall through into the general case diagnostic.
3283 // FIXME: We might want to attempt typo correction here.
3284 }
3285
3286 if (!MD || !MD->isVirtual()) {
3287 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3288 Diag(OA->getLocation(),
3289 diag::override_keyword_only_allowed_on_virtual_member_functions)
3290 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3291 D->dropAttr<OverrideAttr>();
3292 }
3293 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3294 Diag(FA->getLocation(),
3295 diag::override_keyword_only_allowed_on_virtual_member_functions)
3296 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3297 << FixItHint::CreateRemoval(FA->getLocation());
3298 D->dropAttr<FinalAttr>();
3299 }
3300 return;
3301 }
3302
3303 // C++11 [class.virtual]p5:
3304 // If a function is marked with the virt-specifier override and
3305 // does not override a member function of a base class, the program is
3306 // ill-formed.
3307 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3308 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3309 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3310 << MD->getDeclName();
3311}
3312
3314 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3315 return;
3316 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3317 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3318 return;
3319
3320 SourceLocation Loc = MD->getLocation();
3321 SourceLocation SpellingLoc = Loc;
3322 if (getSourceManager().isMacroArgExpansion(Loc))
3323 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3324 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3325 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3326 return;
3327
3328 if (MD->size_overridden_methods() > 0) {
3329 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3330 unsigned DiagID =
3331 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3332 ? DiagInconsistent
3333 : DiagSuggest;
3334 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3335 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3336 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3337 };
3338 if (isa<CXXDestructorDecl>(MD))
3339 EmitDiag(
3340 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3341 diag::warn_suggest_destructor_marked_not_override_overriding);
3342 else
3343 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3344 diag::warn_suggest_function_marked_not_override_overriding);
3345 }
3346}
3347
3349 const CXXMethodDecl *Old) {
3350 FinalAttr *FA = Old->getAttr<FinalAttr>();
3351 if (!FA)
3352 return false;
3353
3354 Diag(New->getLocation(), diag::err_final_function_overridden)
3355 << New->getDeclName()
3356 << FA->isSpelledAsSealed();
3357 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3358 return true;
3359}
3360
3362 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3363 // FIXME: Destruction of ObjC lifetime types has side-effects.
3364 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3365 return !RD->isCompleteDefinition() ||
3366 !RD->hasTrivialDefaultConstructor() ||
3367 !RD->hasTrivialDestructor();
3368 return false;
3369}
3370
3371void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3372 DeclarationName FieldName,
3373 const CXXRecordDecl *RD,
3374 bool DeclIsField) {
3375 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3376 return;
3377
3378 // To record a shadowed field in a base
3379 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3380 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3381 CXXBasePath &Path) {
3382 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3383 // Record an ambiguous path directly
3384 if (Bases.find(Base) != Bases.end())
3385 return true;
3386 for (const auto Field : Base->lookup(FieldName)) {
3387 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3388 Field->getAccess() != AS_private) {
3389 assert(Field->getAccess() != AS_none);
3390 assert(Bases.find(Base) == Bases.end());
3391 Bases[Base] = Field;
3392 return true;
3393 }
3394 }
3395 return false;
3396 };
3397
3398 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3399 /*DetectVirtual=*/true);
3400 if (!RD->lookupInBases(FieldShadowed, Paths))
3401 return;
3402
3403 for (const auto &P : Paths) {
3404 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3405 auto It = Bases.find(Base);
3406 // Skip duplicated bases
3407 if (It == Bases.end())
3408 continue;
3409 auto BaseField = It->second;
3410 assert(BaseField->getAccess() != AS_private);
3411 if (AS_none !=
3412 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3413 Diag(Loc, diag::warn_shadow_field)
3414 << FieldName << RD << Base << DeclIsField;
3415 Diag(BaseField->getLocation(), diag::note_shadow_field);
3416 Bases.erase(It);
3417 }
3418 }
3419}
3420
3421template <typename AttrType>
3422inline static bool HasAttribute(const QualType &T) {
3423 if (const TagDecl *TD = T->getAsTagDecl())
3424 return TD->hasAttr<AttrType>();
3425 if (const TypedefType *TDT = T->getAs<TypedefType>())
3426 return TDT->getDecl()->hasAttr<AttrType>();
3427 return false;
3428}
3429
3430static bool IsUnusedPrivateField(const FieldDecl *FD) {
3431 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3432 QualType FieldType = FD->getType();
3433 if (HasAttribute<WarnUnusedAttr>(FieldType))
3434 return true;
3435
3436 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3437 !FD->getParent()->isDependentContext() &&
3438 !HasAttribute<UnusedAttr>(FieldType) &&
3440 }
3441 return false;
3442}
3443
3444NamedDecl *
3446 MultiTemplateParamsArg TemplateParameterLists,
3447 Expr *BitWidth, const VirtSpecifiers &VS,
3448 InClassInitStyle InitStyle) {
3449 const DeclSpec &DS = D.getDeclSpec();
3451 DeclarationName Name = NameInfo.getName();
3452 SourceLocation Loc = NameInfo.getLoc();
3453
3454 // For anonymous bitfields, the location should point to the type.
3455 if (Loc.isInvalid())
3456 Loc = D.getBeginLoc();
3457
3459 assert(!DS.isFriendSpecified());
3460
3461 bool isFunc = D.isDeclarationOfFunction();
3462 const ParsedAttr *MSPropertyAttr =
3464
3465 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3466 // The Microsoft extension __interface only permits public member functions
3467 // and prohibits constructors, destructors, operators, non-public member
3468 // functions, static methods and data members.
3469 unsigned InvalidDecl;
3470 bool ShowDeclName = true;
3471 if (!isFunc &&
3472 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3473 InvalidDecl = 0;
3474 else if (!isFunc)
3475 InvalidDecl = 1;
3476 else if (AS != AS_public)
3477 InvalidDecl = 2;
3479 InvalidDecl = 3;
3480 else switch (Name.getNameKind()) {
3482 InvalidDecl = 4;
3483 ShowDeclName = false;
3484 break;
3485
3487 InvalidDecl = 5;
3488 ShowDeclName = false;
3489 break;
3490
3493 InvalidDecl = 6;
3494 break;
3495
3496 default:
3497 InvalidDecl = 0;
3498 break;
3499 }
3500
3501 if (InvalidDecl) {
3502 if (ShowDeclName)
3503 Diag(Loc, diag::err_invalid_member_in_interface)
3504 << (InvalidDecl-1) << Name;
3505 else
3506 Diag(Loc, diag::err_invalid_member_in_interface)
3507 << (InvalidDecl-1) << "";
3508 return nullptr;
3509 }
3510 }
3511
3512 // C++ 9.2p6: A member shall not be declared to have automatic storage
3513 // duration (auto, register) or with the extern storage-class-specifier.
3514 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3515 // data members and cannot be applied to names declared const or static,
3516 // and cannot be applied to reference members.
3517 switch (DS.getStorageClassSpec()) {
3521 break;
3523 if (isFunc) {
3524 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3525
3526 // FIXME: It would be nicer if the keyword was ignored only for this
3527 // declarator. Otherwise we could get follow-up errors.
3529 }
3530 break;
3531 default:
3533 diag::err_storageclass_invalid_for_member);
3535 break;
3536 }
3537
3538 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3540 !isFunc && TemplateParameterLists.empty();
3541
3542 if (DS.hasConstexprSpecifier() && isInstField) {
3544 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3545 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3546 if (InitStyle == ICIS_NoInit) {
3547 B << 0 << 0;
3549 B << FixItHint::CreateRemoval(ConstexprLoc);
3550 else {
3551 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3553 const char *PrevSpec;
3554 unsigned DiagID;
3555 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3556 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3557 (void)Failed;
3558 assert(!Failed && "Making a constexpr member const shouldn't fail");
3559 }
3560 } else {
3561 B << 1;
3562 const char *PrevSpec;
3563 unsigned DiagID;
3565 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3566 Context.getPrintingPolicy())) {
3568 "This is the only DeclSpec that should fail to be applied");
3569 B << 1;
3570 } else {
3571 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3572 isInstField = false;
3573 }
3574 }
3575 }
3576
3578 if (isInstField) {
3579 CXXScopeSpec &SS = D.getCXXScopeSpec();
3580
3581 // Data members must have identifiers for names.
3582 if (!Name.isIdentifier()) {
3583 Diag(Loc, diag::err_bad_variable_name)
3584 << Name;
3585 return nullptr;
3586 }
3587
3590 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3591 << II
3595 D.SetIdentifier(II, Loc);
3596 }
3597
3598 if (SS.isSet() && !SS.isInvalid()) {
3599 // The user provided a superfluous scope specifier inside a class
3600 // definition:
3601 //
3602 // class X {
3603 // int X::member;
3604 // };
3605 if (DeclContext *DC = computeDeclContext(SS, false)) {
3606 TemplateIdAnnotation *TemplateId =
3608 ? D.getName().TemplateId
3609 : nullptr;
3611 TemplateId,
3612 /*IsMemberSpecialization=*/false);
3613 } else {
3614 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3615 << Name << SS.getRange();
3616 }
3617 SS.clear();
3618 }
3619
3620 if (MSPropertyAttr) {
3622 BitWidth, InitStyle, AS, *MSPropertyAttr);
3623 if (!Member)
3624 return nullptr;
3625 isInstField = false;
3626 } else {
3628 BitWidth, InitStyle, AS);
3629 if (!Member)
3630 return nullptr;
3631 }
3632
3633 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3634 } else {
3635 Member = HandleDeclarator(S, D, TemplateParameterLists);
3636 if (!Member)
3637 return nullptr;
3638
3639 // Non-instance-fields can't have a bitfield.
3640 if (BitWidth) {
3641 if (Member->isInvalidDecl()) {
3642 // don't emit another diagnostic.
3644 // C++ 9.6p3: A bit-field shall not be a static member.
3645 // "static member 'A' cannot be a bit-field"
3646 Diag(Loc, diag::err_static_not_bitfield)
3647 << Name << BitWidth->getSourceRange();
3648 } else if (isa<TypedefDecl>(Member)) {
3649 // "typedef member 'x' cannot be a bit-field"
3650 Diag(Loc, diag::err_typedef_not_bitfield)
3651 << Name << BitWidth->getSourceRange();
3652 } else {
3653 // A function typedef ("typedef int f(); f a;").
3654 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3655 Diag(Loc, diag::err_not_integral_type_bitfield)
3656 << Name << cast<ValueDecl>(Member)->getType()
3657 << BitWidth->getSourceRange();
3658 }
3659
3660 BitWidth = nullptr;
3661 Member->setInvalidDecl();
3662 }
3663
3664 NamedDecl *NonTemplateMember = Member;
3665 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3666 NonTemplateMember = FunTmpl->getTemplatedDecl();
3667 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3668 NonTemplateMember = VarTmpl->getTemplatedDecl();
3669
3670 Member->setAccess(AS);
3671
3672 // If we have declared a member function template or static data member
3673 // template, set the access of the templated declaration as well.
3674 if (NonTemplateMember != Member)
3675 NonTemplateMember->setAccess(AS);
3676
3677 // C++ [temp.deduct.guide]p3:
3678 // A deduction guide [...] for a member class template [shall be
3679 // declared] with the same access [as the template].
3680 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3681 auto *TD = DG->getDeducedTemplate();
3682 // Access specifiers are only meaningful if both the template and the
3683 // deduction guide are from the same scope.
3684 if (AS != TD->getAccess() &&
3685 TD->getDeclContext()->getRedeclContext()->Equals(
3686 DG->getDeclContext()->getRedeclContext())) {
3687 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3688 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3689 << TD->getAccess();
3690 const AccessSpecDecl *LastAccessSpec = nullptr;
3691 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3692 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3693 LastAccessSpec = AccessSpec;
3694 }
3695 assert(LastAccessSpec && "differing access with no access specifier");
3696 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3697 << AS;
3698 }
3699 }
3700 }
3701
3702 if (VS.isOverrideSpecified())
3703 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3704 if (VS.isFinalSpecified())
3705 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3707 ? FinalAttr::Keyword_sealed
3708 : FinalAttr::Keyword_final));
3709
3710 if (VS.getLastLocation().isValid()) {
3711 // Update the end location of a method that has a virt-specifiers.
3712 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3713 MD->setRangeEnd(VS.getLastLocation());
3714 }
3715
3717
3718 assert((Name || isInstField) && "No identifier for non-field ?");
3719
3720 if (isInstField) {
3722 FieldCollector->Add(FD);
3723
3724 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3726 // Remember all explicit private FieldDecls that have a name, no side
3727 // effects and are not part of a dependent type declaration.
3728 UnusedPrivateFields.insert(FD);
3729 }
3730 }
3731
3732 return Member;
3733}
3734
3735namespace {
3736 class UninitializedFieldVisitor
3737 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3738 Sema &S;
3739 // List of Decls to generate a warning on. Also remove Decls that become
3740 // initialized.
3741 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3742 // List of base classes of the record. Classes are removed after their
3743 // initializers.
3744 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3745 // Vector of decls to be removed from the Decl set prior to visiting the
3746 // nodes. These Decls may have been initialized in the prior initializer.
3748 // If non-null, add a note to the warning pointing back to the constructor.
3750 // Variables to hold state when processing an initializer list. When
3751 // InitList is true, special case initialization of FieldDecls matching
3752 // InitListFieldDecl.
3753 bool InitList;
3754 FieldDecl *InitListFieldDecl;
3755 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3756
3757 public:
3759 UninitializedFieldVisitor(Sema &S,
3760 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3761 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3762 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3763 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3764
3765 // Returns true if the use of ME is not an uninitialized use.
3766 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3767 bool CheckReferenceOnly) {
3769 bool ReferenceField = false;
3770 while (ME) {
3771 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3772 if (!FD)
3773 return false;
3774 Fields.push_back(FD);
3775 if (FD->getType()->isReferenceType())
3776 ReferenceField = true;
3777 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3778 }
3779
3780 // Binding a reference to an uninitialized field is not an
3781 // uninitialized use.
3782 if (CheckReferenceOnly && !ReferenceField)
3783 return true;
3784
3785 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3786 // Discard the first field since it is the field decl that is being
3787 // initialized.
3788 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3789 UsedFieldIndex.push_back(FD->getFieldIndex());
3790
3791 for (auto UsedIter = UsedFieldIndex.begin(),
3792 UsedEnd = UsedFieldIndex.end(),
3793 OrigIter = InitFieldIndex.begin(),
3794 OrigEnd = InitFieldIndex.end();
3795 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3796 if (*UsedIter < *OrigIter)
3797 return true;
3798 if (*UsedIter > *OrigIter)
3799 break;
3800 }
3801
3802 return false;
3803 }
3804
3805 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3806 bool AddressOf) {
3808 return;
3809
3810 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3811 // or union.
3812 MemberExpr *FieldME = ME;
3813
3814 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3815
3816 Expr *Base = ME;
3817 while (MemberExpr *SubME =
3818 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3819
3820 if (isa<VarDecl>(SubME->getMemberDecl()))
3821 return;
3822
3823 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3824 if (!FD->isAnonymousStructOrUnion())
3825 FieldME = SubME;
3826
3827 if (!FieldME->getType().isPODType(S.Context))
3828 AllPODFields = false;
3829
3830 Base = SubME->getBase();
3831 }
3832
3833 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3834 Visit(Base);
3835 return;
3836 }
3837
3838 if (AddressOf && AllPODFields)
3839 return;
3840
3841 ValueDecl* FoundVD = FieldME->getMemberDecl();
3842
3843 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3844 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3845 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3846 }
3847
3848 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3849 QualType T = BaseCast->getType();
3850 if (T->isPointerType() &&
3851 BaseClasses.count(T->getPointeeType())) {
3852 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3853 << T->getPointeeType() << FoundVD;
3854 }
3855 }
3856 }
3857
3858 if (!Decls.count(FoundVD))
3859 return;
3860
3861 const bool IsReference = FoundVD->getType()->isReferenceType();
3862
3863 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3864 // Special checking for initializer lists.
3865 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3866 return;
3867 }
3868 } else {
3869 // Prevent double warnings on use of unbounded references.
3870 if (CheckReferenceOnly && !IsReference)
3871 return;
3872 }
3873
3874 unsigned diag = IsReference
3875 ? diag::warn_reference_field_is_uninit
3876 : diag::warn_field_is_uninit;
3877 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3878 if (Constructor)
3879 S.Diag(Constructor->getLocation(),
3880 diag::note_uninit_in_this_constructor)
3881 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3882
3883 }
3884
3885 void HandleValue(Expr *E, bool AddressOf) {
3886 E = E->IgnoreParens();
3887
3888 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3889 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3890 AddressOf /*AddressOf*/);
3891 return;
3892 }
3893
3894 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3895 Visit(CO->getCond());
3896 HandleValue(CO->getTrueExpr(), AddressOf);
3897 HandleValue(CO->getFalseExpr(), AddressOf);
3898 return;
3899 }
3900
3901 if (BinaryConditionalOperator *BCO =
3902 dyn_cast<BinaryConditionalOperator>(E)) {
3903 Visit(BCO->getCond());
3904 HandleValue(BCO->getFalseExpr(), AddressOf);
3905 return;
3906 }
3907
3908 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3909 HandleValue(OVE->getSourceExpr(), AddressOf);
3910 return;
3911 }
3912
3913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3914 switch (BO->getOpcode()) {
3915 default:
3916 break;
3917 case(BO_PtrMemD):
3918 case(BO_PtrMemI):
3919 HandleValue(BO->getLHS(), AddressOf);
3920 Visit(BO->getRHS());
3921 return;
3922 case(BO_Comma):
3923 Visit(BO->getLHS());
3924 HandleValue(BO->getRHS(), AddressOf);
3925 return;
3926 }
3927 }
3928
3929 Visit(E);
3930 }
3931
3932 void CheckInitListExpr(InitListExpr *ILE) {
3933 InitFieldIndex.push_back(0);
3934 for (auto *Child : ILE->children()) {
3935 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3936 CheckInitListExpr(SubList);
3937 } else {
3938 Visit(Child);
3939 }
3940 ++InitFieldIndex.back();
3941 }
3942 InitFieldIndex.pop_back();
3943 }
3944
3945 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3946 FieldDecl *Field, const Type *BaseClass) {
3947 // Remove Decls that may have been initialized in the previous
3948 // initializer.
3949 for (ValueDecl* VD : DeclsToRemove)
3950 Decls.erase(VD);
3951 DeclsToRemove.clear();
3952
3953 Constructor = FieldConstructor;
3954 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3955
3956 if (ILE && Field) {
3957 InitList = true;
3958 InitListFieldDecl = Field;
3959 InitFieldIndex.clear();
3960 CheckInitListExpr(ILE);
3961 } else {
3962 InitList = false;
3963 Visit(E);
3964 }
3965
3966 if (Field)
3967 Decls.erase(Field);
3968 if (BaseClass)
3969 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3970 }
3971
3972 void VisitMemberExpr(MemberExpr *ME) {
3973 // All uses of unbounded reference fields will warn.
3974 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3975 }
3976
3977 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3978 if (E->getCastKind() == CK_LValueToRValue) {
3979 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3980 return;
3981 }
3982
3983 Inherited::VisitImplicitCastExpr(E);
3984 }
3985
3986 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3987 if (E->getConstructor()->isCopyConstructor()) {
3988 Expr *ArgExpr = E->getArg(0);
3989 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3990 if (ILE->getNumInits() == 1)
3991 ArgExpr = ILE->getInit(0);
3992 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3993 if (ICE->getCastKind() == CK_NoOp)
3994 ArgExpr = ICE->getSubExpr();
3995 HandleValue(ArgExpr, false /*AddressOf*/);
3996 return;
3997 }
3998 Inherited::VisitCXXConstructExpr(E);
3999 }
4000
4001 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4002 Expr *Callee = E->getCallee();
4003 if (isa<MemberExpr>(Callee)) {
4004 HandleValue(Callee, false /*AddressOf*/);
4005 for (auto *Arg : E->arguments())
4006 Visit(Arg);
4007 return;
4008 }
4009
4010 Inherited::VisitCXXMemberCallExpr(E);
4011 }
4012
4013 void VisitCallExpr(CallExpr *E) {
4014 // Treat std::move as a use.
4015 if (E->isCallToStdMove()) {
4016 HandleValue(E->getArg(0), /*AddressOf=*/false);
4017 return;
4018 }
4019
4020 Inherited::VisitCallExpr(E);
4021 }
4022
4023 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4024 Expr *Callee = E->getCallee();
4025
4026 if (isa<UnresolvedLookupExpr>(Callee))
4027 return Inherited::VisitCXXOperatorCallExpr(E);
4028
4029 Visit(Callee);
4030 for (auto *Arg : E->arguments())
4031 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4032 }
4033
4034 void VisitBinaryOperator(BinaryOperator *E) {
4035 // If a field assignment is detected, remove the field from the
4036 // uninitiailized field set.
4037 if (E->getOpcode() == BO_Assign)
4038 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4039 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4040 if (!FD->getType()->isReferenceType())
4041 DeclsToRemove.push_back(FD);
4042
4043 if (E->isCompoundAssignmentOp()) {
4044 HandleValue(E->getLHS(), false /*AddressOf*/);
4045 Visit(E->getRHS());
4046 return;
4047 }
4048
4049 Inherited::VisitBinaryOperator(E);
4050 }
4051
4052 void VisitUnaryOperator(UnaryOperator *E) {
4053 if (E->isIncrementDecrementOp()) {
4054 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4055 return;
4056 }
4057 if (E->getOpcode() == UO_AddrOf) {
4058 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4059 HandleValue(ME->getBase(), true /*AddressOf*/);
4060 return;
4061 }
4062 }
4063
4064 Inherited::VisitUnaryOperator(E);
4065 }
4066 };
4067
4068 // Diagnose value-uses of fields to initialize themselves, e.g.
4069 // foo(foo)
4070 // where foo is not also a parameter to the constructor.
4071 // Also diagnose across field uninitialized use such as
4072 // x(y), y(x)
4073 // TODO: implement -Wuninitialized and fold this into that framework.
4074 static void DiagnoseUninitializedFields(
4075 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4076
4077 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4078 Constructor->getLocation())) {
4079 return;
4080 }
4081
4082 if (Constructor->isInvalidDecl())
4083 return;
4084
4085 const CXXRecordDecl *RD = Constructor->getParent();
4086
4087 if (RD->isDependentContext())
4088 return;
4089
4090 // Holds fields that are uninitialized.
4091 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4092
4093 // At the beginning, all fields are uninitialized.
4094 for (auto *I : RD->decls()) {
4095 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4096 UninitializedFields.insert(FD);
4097 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4098 UninitializedFields.insert(IFD->getAnonField());
4099 }
4100 }
4101
4102 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4103 for (const auto &I : RD->bases())
4104 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4105
4106 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4107 return;
4108
4109 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4110 UninitializedFields,
4111 UninitializedBaseClasses);
4112
4113 for (const auto *FieldInit : Constructor->inits()) {
4114 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4115 break;
4116
4117 Expr *InitExpr = FieldInit->getInit();
4118 if (!InitExpr)
4119 continue;
4120
4121 if (CXXDefaultInitExpr *Default =
4122 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4123 InitExpr = Default->getExpr();
4124 if (!InitExpr)
4125 continue;
4126 // In class initializers will point to the constructor.
4127 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4128 FieldInit->getAnyMember(),
4129 FieldInit->getBaseClass());
4130 } else {
4131 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4132 FieldInit->getAnyMember(),
4133 FieldInit->getBaseClass());
4134 }
4135 }
4136 }
4137} // namespace
4138
4140 // Create a synthetic function scope to represent the call to the constructor
4141 // that notionally surrounds a use of this initializer.
4143}
4144
4146 if (!D.isFunctionDeclarator())
4147 return;
4148 auto &FTI = D.getFunctionTypeInfo();
4149 if (!FTI.Params)
4150 return;
4151 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4152 FTI.NumParams)) {
4153 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4154 if (ParamDecl->getDeclName())
4155 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4156 }
4157}
4158
4160 return ActOnRequiresClause(ConstraintExpr);
4161}
4162
4164 if (ConstraintExpr.isInvalid())
4165 return ExprError();
4166
4167 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4169 return ExprError();
4170
4171 return ConstraintExpr;
4172}
4173
4175 Expr *InitExpr,
4176 SourceLocation InitLoc) {
4177 InitializedEntity Entity =
4179 InitializationKind Kind =
4182 InitExpr->getBeginLoc(),
4183 InitExpr->getEndLoc())
4184 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4185 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4186 return Seq.Perform(*this, Entity, Kind, InitExpr);
4187}
4188
4190 SourceLocation InitLoc,
4191 ExprResult InitExpr) {
4192 // Pop the notional constructor scope we created earlier.
4193 PopFunctionScopeInfo(nullptr, D);
4194
4195 // Microsoft C++'s property declaration cannot have a default member
4196 // initializer.
4197 if (isa<MSPropertyDecl>(D)) {
4198 D->setInvalidDecl();
4199 return;
4200 }
4201
4202 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4203 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4204 "must set init style when field is created");
4205
4206 if (!InitExpr.isUsable() ||
4208 FD->setInvalidDecl();
4209 ExprResult RecoveryInit =
4210 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4211 if (RecoveryInit.isUsable())
4212 FD->setInClassInitializer(RecoveryInit.get());
4213 return;
4214 }
4215
4216 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4217 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4218 // C++11 [class.base.init]p7:
4219 // The initialization of each base and member constitutes a
4220 // full-expression.
4221 if (!InitExpr.isInvalid())
4222 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4223 if (InitExpr.isInvalid()) {
4224 FD->setInvalidDecl();
4225 return;
4226 }
4227 }
4228
4229 FD->setInClassInitializer(InitExpr.get());
4230}
4231
4232/// Find the direct and/or virtual base specifiers that
4233/// correspond to the given base type, for use in base initialization
4234/// within a constructor.
4235static bool FindBaseInitializer(Sema &SemaRef,
4236 CXXRecordDecl *ClassDecl,
4237 QualType BaseType,
4238 const CXXBaseSpecifier *&DirectBaseSpec,
4239 const CXXBaseSpecifier *&VirtualBaseSpec) {
4240 // First, check for a direct base class.
4241 DirectBaseSpec = nullptr;
4242 for (const auto &Base : ClassDecl->bases()) {
4243 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4244 // We found a direct base of this type. That's what we're
4245 // initializing.
4246 DirectBaseSpec = &Base;
4247 break;
4248 }
4249 }
4250
4251 // Check for a virtual base class.
4252 // FIXME: We might be able to short-circuit this if we know in advance that
4253 // there are no virtual bases.
4254 VirtualBaseSpec = nullptr;
4255 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4256 // We haven't found a base yet; search the class hierarchy for a
4257 // virtual base class.
4258 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4259 /*DetectVirtual=*/false);
4260 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4261 SemaRef.Context.getCanonicalTagType(ClassDecl),
4262 BaseType, Paths)) {
4263 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4264 Path != Paths.end(); ++Path) {
4265 if (Path->back().Base->isVirtual()) {
4266 VirtualBaseSpec = Path->back().Base;
4267 break;
4268 }
4269 }
4270 }
4271 }
4272
4273 return DirectBaseSpec || VirtualBaseSpec;
4274}
4275
4278 Scope *S,
4279 CXXScopeSpec &SS,
4280 IdentifierInfo *MemberOrBase,
4281 ParsedType TemplateTypeTy,
4282 const DeclSpec &DS,
4283 SourceLocation IdLoc,
4284 Expr *InitList,
4285 SourceLocation EllipsisLoc) {
4286 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4287 DS, IdLoc, InitList,
4288 EllipsisLoc);
4289}
4290
4293 Scope *S,
4294 CXXScopeSpec &SS,
4295 IdentifierInfo *MemberOrBase,
4296 ParsedType TemplateTypeTy,
4297 const DeclSpec &DS,
4298 SourceLocation IdLoc,
4299 SourceLocation LParenLoc,
4300 ArrayRef<Expr *> Args,
4301 SourceLocation RParenLoc,
4302 SourceLocation EllipsisLoc) {
4303 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4304 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4305 DS, IdLoc, List, EllipsisLoc);
4306}
4307
4308namespace {
4309
4310// Callback to only accept typo corrections that can be a valid C++ member
4311// initializer: either a non-static field member or a base class.
4312class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4313public:
4314 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4315 : ClassDecl(ClassDecl) {}
4316
4317 bool ValidateCandidate(const TypoCorrection &candidate) override {
4318 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4319 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4320 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4321 return isa<TypeDecl>(ND);
4322 }
4323 return false;
4324 }
4325
4326 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4327 return std::make_unique<MemInitializerValidatorCCC>(*this);
4328 }
4329
4330private:
4331 CXXRecordDecl *ClassDecl;
4332};
4333
4334}
4335
4337 RecordDecl *ClassDecl,
4338 const IdentifierInfo *Name) {
4339 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4341 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4342 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4344 });
4345 // We did not find a placeholder variable
4346 if (Found == Result.end())
4347 return false;
4348 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4349 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4350 const NamedDecl *ND = *It;
4351 if (ND->getDeclContext() != ND->getDeclContext())
4352 break;
4355 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4356 }
4357 return true;
4358}
4359
4360ValueDecl *
4362 const IdentifierInfo *MemberOrBase) {
4363 ValueDecl *ND = nullptr;
4364 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4366 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4367 if (ND) {
4368 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4369 return nullptr;
4370 break;
4371 }
4372 if (!IsPlaceholder)
4373 return cast<ValueDecl>(D);
4374 ND = cast<ValueDecl>(D);
4375 }
4376 }
4377 return ND;
4378}
4379
4381 CXXScopeSpec &SS,
4382 ParsedType TemplateTypeTy,
4383 IdentifierInfo *MemberOrBase) {
4384 if (SS.getScopeRep() || TemplateTypeTy)
4385 return nullptr;
4386 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4387}
4388
4391 Scope *S,
4392 CXXScopeSpec &SS,
4393 IdentifierInfo *MemberOrBase,
4394 ParsedType TemplateTypeTy,
4395 const DeclSpec &DS,
4396 SourceLocation IdLoc,
4397 Expr *Init,
4398 SourceLocation EllipsisLoc) {
4399 if (!ConstructorD || !Init)
4400 return true;
4401
4402 AdjustDeclIfTemplate(ConstructorD);
4403
4405 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4406 if (!Constructor) {
4407 // The user wrote a constructor initializer on a function that is
4408 // not a C++ constructor. Ignore the error for now, because we may
4409 // have more member initializers coming; we'll diagnose it just
4410 // once in ActOnMemInitializers.
4411 return true;
4412 }
4413
4414 CXXRecordDecl *ClassDecl = Constructor->getParent();
4415
4416 // C++ [class.base.init]p2:
4417 // Names in a mem-initializer-id are looked up in the scope of the
4418 // constructor's class and, if not found in that scope, are looked
4419 // up in the scope containing the constructor's definition.
4420 // [Note: if the constructor's class contains a member with the
4421 // same name as a direct or virtual base class of the class, a
4422 // mem-initializer-id naming the member or base class and composed
4423 // of a single identifier refers to the class member. A
4424 // mem-initializer-id for the hidden base class may be specified
4425 // using a qualified name. ]
4426
4427 // Look for a member, first.
4429 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4430 if (EllipsisLoc.isValid())
4431 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4432 << MemberOrBase
4433 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4434
4435 return BuildMemberInitializer(Member, Init, IdLoc);
4436 }
4437 // It didn't name a member, so see if it names a class.
4438 QualType BaseType;
4439 TypeSourceInfo *TInfo = nullptr;
4440
4441 if (TemplateTypeTy) {
4442 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4443 if (BaseType.isNull())
4444 return true;
4445 } else if (DS.getTypeSpecType() == TST_decltype) {
4446 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4447 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4448 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4449 return true;
4450 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4451 BaseType =
4453 DS.getBeginLoc(), DS.getEllipsisLoc());
4454 } else {
4455 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4456 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4457
4458 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4459 if (!TyD) {
4460 if (R.isAmbiguous()) return true;
4461
4462 // We don't want access-control diagnostics here.
4464
4465 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4466 bool NotUnknownSpecialization = false;
4467 DeclContext *DC = computeDeclContext(SS, false);
4468 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4469 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4470
4471 if (!NotUnknownSpecialization) {
4472 // When the scope specifier can refer to a member of an unknown
4473 // specialization, we take it as a type name.
4474 BaseType = CheckTypenameType(
4476 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4477 if (BaseType.isNull())
4478 return true;
4479
4480 TInfo = Context.CreateTypeSourceInfo(BaseType);
4483 if (!TL.isNull()) {
4484 TL.setNameLoc(IdLoc);
4487 }
4488
4489 R.clear();
4490 R.setLookupName(MemberOrBase);
4491 }
4492 }
4493
4494 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4495 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4496 auto *TempSpec = cast<TemplateSpecializationType>(
4497 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4498 TemplateName TN = TempSpec->getTemplateName();
4499 for (auto const &Base : ClassDecl->bases()) {
4500 auto BaseTemplate =
4501 Base.getType()->getAs<TemplateSpecializationType>();
4502 if (BaseTemplate &&
4503 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4504 /*IgnoreDeduced=*/true)) {
4505 Diag(IdLoc, diag::ext_unqualified_base_class)
4506 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4507 BaseType = Base.getType();
4508 break;
4509 }
4510 }
4511 }
4512 }
4513
4514 // If no results were found, try to correct typos.
4515 TypoCorrection Corr;
4516 MemInitializerValidatorCCC CCC(ClassDecl);
4517 if (R.empty() && BaseType.isNull() &&
4518 (Corr =
4520 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4522 // We have found a non-static data member with a similar
4523 // name to what was typed; complain and initialize that
4524 // member.
4525 diagnoseTypo(Corr,
4526 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4527 << MemberOrBase << true);
4528 return BuildMemberInitializer(Member, Init, IdLoc);
4529 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4530 const CXXBaseSpecifier *DirectBaseSpec;
4531 const CXXBaseSpecifier *VirtualBaseSpec;
4532 if (FindBaseInitializer(*this, ClassDecl,
4533 Context.getTypeDeclType(Type),
4534 DirectBaseSpec, VirtualBaseSpec)) {
4535 // We have found a direct or virtual base class with a
4536 // similar name to what was typed; complain and initialize
4537 // that base class.
4538 diagnoseTypo(Corr,
4539 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4540 << MemberOrBase << false,
4541 PDiag() /*Suppress note, we provide our own.*/);
4542
4543 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4544 : VirtualBaseSpec;
4545 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4546 << BaseSpec->getType() << BaseSpec->getSourceRange();
4547
4548 TyD = Type;
4549 }
4550 }
4551 }
4552
4553 if (!TyD && BaseType.isNull()) {
4554 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4555 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4556 return true;
4557 }
4558 }
4559
4560 if (BaseType.isNull()) {
4561 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4562
4563 TypeLocBuilder TLB;
4564 // FIXME: This is missing building the UsingType for TyD, if any.
4565 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4566 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4567 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4568 auto TL = TLB.push<TagTypeLoc>(BaseType);
4570 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4571 TL.setNameLoc(IdLoc);
4572 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4573 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4574 SS.getScopeRep(), TN);
4575 TLB.push<TypedefTypeLoc>(BaseType).set(
4576 /*ElaboratedKeywordLoc=*/SourceLocation(),
4577 SS.getWithLocInContext(Context), IdLoc);
4578 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4579 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4580 SS.getScopeRep(), UD);
4581 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4582 /*ElaboratedKeywordLoc=*/SourceLocation(),
4583 SS.getWithLocInContext(Context), IdLoc);
4584 } else {
4585 // FIXME: What else can appear here?
4586 assert(SS.isEmpty());
4587 BaseType = Context.getTypeDeclType(TyD);
4588 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4589 }
4590 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4591 }
4592 }
4593
4594 if (!TInfo)
4595 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4596
4597 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4598}
4599
4602 SourceLocation IdLoc) {
4603 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4604 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4605 assert((DirectMember || IndirectMember) &&
4606 "Member must be a FieldDecl or IndirectFieldDecl");
4607
4609 return true;
4610
4611 if (Member->isInvalidDecl())
4612 return true;
4613
4614 MultiExprArg Args;
4615 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4616 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4617 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4618 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4619 } else {
4620 // Template instantiation doesn't reconstruct ParenListExprs for us.
4621 Args = Init;
4622 }
4623
4624 SourceRange InitRange = Init->getSourceRange();
4625
4626 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4627 // Can't check initialization for a member of dependent type or when
4628 // any of the arguments are type-dependent expressions.
4630 } else {
4631 bool InitList = false;
4632 if (isa<InitListExpr>(Init)) {
4633 InitList = true;
4634 Args = Init;
4635 }
4636
4637 // Initialize the member.
4638 InitializedEntity MemberEntity =
4639 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4640 : InitializedEntity::InitializeMember(IndirectMember,
4641 nullptr);
4642 InitializationKind Kind =
4644 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4645 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4646 InitRange.getEnd());
4647
4648 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4649 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4650 nullptr);
4651 if (!MemberInit.isInvalid()) {
4652 // C++11 [class.base.init]p7:
4653 // The initialization of each base and member constitutes a
4654 // full-expression.
4655 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4656 /*DiscardedValue*/ false);
4657 }
4658
4659 if (MemberInit.isInvalid()) {
4660 // Args were sensible expressions but we couldn't initialize the member
4661 // from them. Preserve them in a RecoveryExpr instead.
4662 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4663 Member->getType())
4664 .get();
4665 if (!Init)
4666 return true;
4667 } else {
4668 Init = MemberInit.get();
4669 }
4670 }
4671
4672 if (DirectMember) {
4673 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4674 InitRange.getBegin(), Init,
4675 InitRange.getEnd());
4676 } else {
4677 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4678 InitRange.getBegin(), Init,
4679 InitRange.getEnd());
4680 }
4681}
4682
4685 CXXRecordDecl *ClassDecl) {
4686 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4687 if (!LangOpts.CPlusPlus11)
4688 return Diag(NameLoc, diag::err_delegating_ctor)
4689 << TInfo->getTypeLoc().getSourceRange();
4690 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4691
4692 bool InitList = true;
4693 MultiExprArg Args = Init;
4694 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4695 InitList = false;
4696 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4697 }
4698
4699 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4700
4701 SourceRange InitRange = Init->getSourceRange();
4702 // Initialize the object.
4703 InitializedEntity DelegationEntity =
4705 InitializationKind Kind =
4707 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4708 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4709 InitRange.getEnd());
4710 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4711 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4712 Args, nullptr);
4713 if (!DelegationInit.isInvalid()) {
4714 assert((DelegationInit.get()->containsErrors() ||
4715 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4716 "Delegating constructor with no target?");
4717
4718 // C++11 [class.base.init]p7:
4719 // The initialization of each base and member constitutes a
4720 // full-expression.
4721 DelegationInit = ActOnFinishFullExpr(
4722 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4723 }
4724
4725 if (DelegationInit.isInvalid()) {
4726 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4727 InitRange.getEnd(), Args, ClassType);
4728 if (DelegationInit.isInvalid())
4729 return true;
4730 } else {
4731 // If we are in a dependent context, template instantiation will
4732 // perform this type-checking again. Just save the arguments that we
4733 // received in a ParenListExpr.
4734 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4735 // of the information that we have about the base
4736 // initializer. However, deconstructing the ASTs is a dicey process,
4737 // and this approach is far more likely to get the corner cases right.
4738 if (CurContext->isDependentContext())
4739 DelegationInit = Init;
4740 }
4741
4742 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4743 DelegationInit.getAs<Expr>(),
4744 InitRange.getEnd());
4745}
4746
4749 Expr *Init, CXXRecordDecl *ClassDecl,
4750 SourceLocation EllipsisLoc) {
4751 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4752
4753 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4754 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4755 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4756
4757 // C++ [class.base.init]p2:
4758 // [...] Unless the mem-initializer-id names a nonstatic data
4759 // member of the constructor's class or a direct or virtual base
4760 // of that class, the mem-initializer is ill-formed. A
4761 // mem-initializer-list can initialize a base class using any
4762 // name that denotes that base class type.
4763
4764 // We can store the initializers in "as-written" form and delay analysis until
4765 // instantiation if the constructor is dependent. But not for dependent
4766 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4767 bool Dependent = CurContext->isDependentContext() &&
4768 (BaseType->isDependentType() || Init->isTypeDependent());
4769
4770 SourceRange InitRange = Init->getSourceRange();
4771 if (EllipsisLoc.isValid()) {
4772 // This is a pack expansion.
4773 if (!BaseType->containsUnexpandedParameterPack()) {
4774 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4775 << SourceRange(BaseLoc, InitRange.getEnd());
4776
4777 EllipsisLoc = SourceLocation();
4778 }
4779 } else {
4780 // Check for any unexpanded parameter packs.
4781 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4782 return true;
4783
4785 return true;
4786 }
4787
4788 // Check for direct and virtual base classes.
4789 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4790 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4791 if (!Dependent) {
4792 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4793 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4794
4795 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4796 VirtualBaseSpec);
4797
4798 // C++ [base.class.init]p2:
4799 // Unless the mem-initializer-id names a nonstatic data member of the
4800 // constructor's class or a direct or virtual base of that class, the
4801 // mem-initializer is ill-formed.
4802 if (!DirectBaseSpec && !VirtualBaseSpec) {
4803 // If the class has any dependent bases, then it's possible that
4804 // one of those types will resolve to the same type as
4805 // BaseType. Therefore, just treat this as a dependent base
4806 // class initialization. FIXME: Should we try to check the
4807 // initialization anyway? It seems odd.
4808 if (ClassDecl->hasAnyDependentBases())
4809 Dependent = true;
4810 else
4811 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4812 << BaseType << Context.getCanonicalTagType(ClassDecl)
4813 << BaseTInfo->getTypeLoc().getSourceRange();
4814 }
4815 }
4816
4817 if (Dependent) {
4819
4820 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4821 /*IsVirtual=*/false,
4822 InitRange.getBegin(), Init,
4823 InitRange.getEnd(), EllipsisLoc);
4824 }
4825
4826 // C++ [base.class.init]p2:
4827 // If a mem-initializer-id is ambiguous because it designates both
4828 // a direct non-virtual base class and an inherited virtual base
4829 // class, the mem-initializer is ill-formed.
4830 if (DirectBaseSpec && VirtualBaseSpec)
4831 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4832 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4833
4834 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4835 if (!BaseSpec)
4836 BaseSpec = VirtualBaseSpec;
4837
4838 // Initialize the base.
4839 bool InitList = true;
4840 MultiExprArg Args = Init;
4841 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4842 InitList = false;
4843 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4844 }
4845
4846 InitializedEntity BaseEntity =
4847 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4848 InitializationKind Kind =
4849 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4850 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4851 InitRange.getEnd());
4852 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4853 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4854 if (!BaseInit.isInvalid()) {
4855 // C++11 [class.base.init]p7:
4856 // The initialization of each base and member constitutes a
4857 // full-expression.
4858 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4859 /*DiscardedValue*/ false);
4860 }
4861
4862 if (BaseInit.isInvalid()) {
4863 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4864 Args, BaseType);
4865 if (BaseInit.isInvalid())
4866 return true;
4867 } else {
4868 // If we are in a dependent context, template instantiation will
4869 // perform this type-checking again. Just save the arguments that we
4870 // received in a ParenListExpr.
4871 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4872 // of the information that we have about the base
4873 // initializer. However, deconstructing the ASTs is a dicey process,
4874 // and this approach is far more likely to get the corner cases right.
4875 if (CurContext->isDependentContext())
4876 BaseInit = Init;
4877 }
4878
4879 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4880 BaseSpec->isVirtual(),
4881 InitRange.getBegin(),
4882 BaseInit.getAs<Expr>(),
4883 InitRange.getEnd(), EllipsisLoc);
4884}
4885
4886// Create a static_cast<T&&>(expr).
4887static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4888 QualType TargetType =
4889 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4891 SourceLocation ExprLoc = E->getBeginLoc();
4892 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4893 TargetType, ExprLoc);
4894
4895 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4896 SourceRange(ExprLoc, ExprLoc),
4897 E->getSourceRange()).get();
4898}
4899
4900/// ImplicitInitializerKind - How an implicit base or member initializer should
4901/// initialize its base or member.
4908
4909static bool
4911 ImplicitInitializerKind ImplicitInitKind,
4912 CXXBaseSpecifier *BaseSpec,
4913 bool IsInheritedVirtualBase,
4914 CXXCtorInitializer *&CXXBaseInit) {
4915 InitializedEntity InitEntity
4916 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4917 IsInheritedVirtualBase);
4918
4919 ExprResult BaseInit;
4920
4921 switch (ImplicitInitKind) {
4922 case IIK_Inherit:
4923 case IIK_Default: {
4924 InitializationKind InitKind
4926 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4927 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4928 break;
4929 }
4930
4931 case IIK_Move:
4932 case IIK_Copy: {
4933 bool Moving = ImplicitInitKind == IIK_Move;
4934 ParmVarDecl *Param = Constructor->getParamDecl(0);
4935 QualType ParamType = Param->getType().getNonReferenceType();
4936
4937 Expr *CopyCtorArg =
4939 SourceLocation(), Param, false,
4940 Constructor->getLocation(), ParamType,
4941 VK_LValue, nullptr);
4942
4943 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4944
4945 // Cast to the base class to avoid ambiguities.
4946 QualType ArgTy =
4947 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4948 ParamType.getQualifiers());
4949
4950 if (Moving) {
4951 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4952 }
4953
4954 CXXCastPath BasePath;
4955 BasePath.push_back(BaseSpec);
4956 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4957 CK_UncheckedDerivedToBase,
4958 Moving ? VK_XValue : VK_LValue,
4959 &BasePath).get();
4960
4961 InitializationKind InitKind
4964 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4965 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4966 break;
4967 }
4968 }
4969
4970 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4971 if (BaseInit.isInvalid())
4972 return true;
4973
4974 CXXBaseInit =
4975 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4976 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4977 SourceLocation()),
4978 BaseSpec->isVirtual(),
4980 BaseInit.getAs<Expr>(),
4982 SourceLocation());
4983
4984 return false;
4985}
4986
4987static bool RefersToRValueRef(Expr *MemRef) {
4988 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4989 return Referenced->getType()->isRValueReferenceType();
4990}
4991
4992static bool
4994 ImplicitInitializerKind ImplicitInitKind,
4995 FieldDecl *Field, IndirectFieldDecl *Indirect,
4996 CXXCtorInitializer *&CXXMemberInit) {
4997 if (Field->isInvalidDecl())
4998 return true;
4999
5000 SourceLocation Loc = Constructor->getLocation();
5001
5002 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5003 bool Moving = ImplicitInitKind == IIK_Move;
5004 ParmVarDecl *Param = Constructor->getParamDecl(0);
5005 QualType ParamType = Param->getType().getNonReferenceType();
5006
5007 // Suppress copying zero-width bitfields.
5008 if (Field->isZeroLengthBitField())
5009 return false;
5010
5011 Expr *MemberExprBase =
5013 SourceLocation(), Param, false,
5014 Loc, ParamType, VK_LValue, nullptr);
5015
5016 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5017
5018 if (Moving) {
5019 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5020 }
5021
5022 // Build a reference to this field within the parameter.
5023 CXXScopeSpec SS;
5024 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5026 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5027 : cast<ValueDecl>(Field), AS_public);
5028 MemberLookup.resolveKind();
5029 ExprResult CtorArg
5030 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5031 ParamType, Loc,
5032 /*IsArrow=*/false,
5033 SS,
5034 /*TemplateKWLoc=*/SourceLocation(),
5035 /*FirstQualifierInScope=*/nullptr,
5036 MemberLookup,
5037 /*TemplateArgs=*/nullptr,
5038 /*S*/nullptr);
5039 if (CtorArg.isInvalid())
5040 return true;
5041
5042 // C++11 [class.copy]p15:
5043 // - if a member m has rvalue reference type T&&, it is direct-initialized
5044 // with static_cast<T&&>(x.m);
5045 if (RefersToRValueRef(CtorArg.get())) {
5046 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5047 }
5048
5049 InitializedEntity Entity =
5050 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5051 /*Implicit*/ true)
5052 : InitializedEntity::InitializeMember(Field, nullptr,
5053 /*Implicit*/ true);
5054
5055 // Direct-initialize to use the copy constructor.
5056 InitializationKind InitKind =
5058
5059 Expr *CtorArgE = CtorArg.getAs<Expr>();
5060 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5061 ExprResult MemberInit =
5062 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5063 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5064 if (MemberInit.isInvalid())
5065 return true;
5066
5067 if (Indirect)
5068 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5069 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5070 else
5071 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5072 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5073 return false;
5074 }
5075
5076 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5077 "Unhandled implicit init kind!");
5078
5079 QualType FieldBaseElementType =
5080 SemaRef.Context.getBaseElementType(Field->getType());
5081
5082 if (FieldBaseElementType->isRecordType()) {
5083 InitializedEntity InitEntity =
5084 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5085 /*Implicit*/ true)
5086 : InitializedEntity::InitializeMember(Field, nullptr,
5087 /*Implicit*/ true);
5088 InitializationKind InitKind =
5090
5091 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5092 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5093
5094 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5095 if (MemberInit.isInvalid())
5096 return true;
5097
5098 if (Indirect)
5099 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5100 Indirect, Loc,
5101 Loc,
5102 MemberInit.get(),
5103 Loc);
5104 else
5105 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5106 Field, Loc, Loc,
5107 MemberInit.get(),
5108 Loc);
5109 return false;
5110 }
5111
5112 if (!Field->getParent()->isUnion()) {
5113 if (FieldBaseElementType->isReferenceType()) {
5114 SemaRef.Diag(Constructor->getLocation(),
5115 diag::err_uninitialized_member_in_ctor)
5116 << (int)Constructor->isImplicit()
5117 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5118 << Field->getDeclName();
5119 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5120 return true;
5121 }
5122
5123 if (FieldBaseElementType.isConstQualified()) {
5124 SemaRef.Diag(Constructor->getLocation(),
5125 diag::err_uninitialized_member_in_ctor)
5126 << (int)Constructor->isImplicit()
5127 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5128 << Field->getDeclName();
5129 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5130 return true;
5131 }
5132 }
5133
5134 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5135 // ARC and Weak:
5136 // Default-initialize Objective-C pointers to NULL.
5137 CXXMemberInit
5138 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5139 Loc, Loc,
5140 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5141 Loc);
5142 return false;
5143 }
5144
5145 // Nothing to initialize.
5146 CXXMemberInit = nullptr;
5147 return false;
5148}
5149
5150namespace {
5151struct BaseAndFieldInfo {
5152 Sema &S;
5153 CXXConstructorDecl *Ctor;
5154 bool AnyErrorsInInits;
5156 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5157 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5158 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5159
5160 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5161 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5162 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5163 if (Ctor->getInheritedConstructor())
5164 IIK = IIK_Inherit;
5165 else if (Generated && Ctor->isCopyConstructor())
5166 IIK = IIK_Copy;
5167 else if (Generated && Ctor->isMoveConstructor())
5168 IIK = IIK_Move;
5169 else
5170 IIK = IIK_Default;
5171 }
5172
5173 bool isImplicitCopyOrMove() const {
5174 switch (IIK) {
5175 case IIK_Copy:
5176 case IIK_Move:
5177 return true;
5178
5179 case IIK_Default:
5180 case IIK_Inherit:
5181 return false;
5182 }
5183
5184 llvm_unreachable("Invalid ImplicitInitializerKind!");
5185 }
5186
5187 bool addFieldInitializer(CXXCtorInitializer *Init) {
5188 AllToInit.push_back(Init);
5189
5190 // Check whether this initializer makes the field "used".
5191 if (Init->getInit()->HasSideEffects(S.Context))
5192 S.UnusedPrivateFields.remove(Init->getAnyMember());
5193
5194 return false;
5195 }
5196
5197 bool isInactiveUnionMember(FieldDecl *Field) {
5198 RecordDecl *Record = Field->getParent();
5199 if (!Record->isUnion())
5200 return false;
5201
5202 if (FieldDecl *Active =
5203 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5204 return Active != Field->getCanonicalDecl();
5205
5206 // In an implicit copy or move constructor, ignore any in-class initializer.
5207 if (isImplicitCopyOrMove())
5208 return true;
5209
5210 // If there's no explicit initialization, the field is active only if it
5211 // has an in-class initializer...
5212 if (Field->hasInClassInitializer())
5213 return false;
5214 // ... or it's an anonymous struct or union whose class has an in-class
5215 // initializer.
5216 if (!Field->isAnonymousStructOrUnion())
5217 return true;
5218 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5219 return !FieldRD->hasInClassInitializer();
5220 }
5221
5222 /// Determine whether the given field is, or is within, a union member
5223 /// that is inactive (because there was an initializer given for a different
5224 /// member of the union, or because the union was not initialized at all).
5225 bool isWithinInactiveUnionMember(FieldDecl *Field,
5226 IndirectFieldDecl *Indirect) {
5227 if (!Indirect)
5228 return isInactiveUnionMember(Field);
5229
5230 for (auto *C : Indirect->chain()) {
5231 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5232 if (Field && isInactiveUnionMember(Field))
5233 return true;
5234 }
5235 return false;
5236 }
5237};
5238}
5239
5240/// Determine whether the given type is an incomplete or zero-lenfgth
5241/// array type.
5243 if (T->isIncompleteArrayType())
5244 return true;
5245
5246 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5247 if (ArrayT->isZeroSize())
5248 return true;
5249
5250 T = ArrayT->getElementType();
5251 }
5252
5253 return false;
5254}
5255
5256static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5257 FieldDecl *Field,
5258 IndirectFieldDecl *Indirect = nullptr) {
5259 if (Field->isInvalidDecl())
5260 return false;
5261
5262 // Overwhelmingly common case: we have a direct initializer for this field.
5264 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5265 return Info.addFieldInitializer(Init);
5266
5267 // C++11 [class.base.init]p8:
5268 // if the entity is a non-static data member that has a
5269 // brace-or-equal-initializer and either
5270 // -- the constructor's class is a union and no other variant member of that
5271 // union is designated by a mem-initializer-id or
5272 // -- the constructor's class is not a union, and, if the entity is a member
5273 // of an anonymous union, no other member of that union is designated by
5274 // a mem-initializer-id,
5275 // the entity is initialized as specified in [dcl.init].
5276 //
5277 // We also apply the same rules to handle anonymous structs within anonymous
5278 // unions.
5279 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5280 return false;
5281
5282 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5283 ExprResult DIE =
5284 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5285 if (DIE.isInvalid())
5286 return true;
5287
5288 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5289 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5290
5292 if (Indirect)
5293 Init = new (SemaRef.Context)
5294 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5295 SourceLocation(), DIE.get(), SourceLocation());
5296 else
5297 Init = new (SemaRef.Context)
5298 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5299 SourceLocation(), DIE.get(), SourceLocation());
5300 return Info.addFieldInitializer(Init);
5301 }
5302
5303 // Don't initialize incomplete or zero-length arrays.
5304 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5305 return false;
5306
5307 // Don't try to build an implicit initializer if there were semantic
5308 // errors in any of the initializers (and therefore we might be
5309 // missing some that the user actually wrote).
5310 if (Info.AnyErrorsInInits)
5311 return false;
5312
5313 CXXCtorInitializer *Init = nullptr;
5314 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5315 Indirect, Init))
5316 return true;
5317
5318 if (!Init)
5319 return false;
5320
5321 return Info.addFieldInitializer(Init);
5322}
5323
5324bool
5327 assert(Initializer->isDelegatingInitializer());
5328 Constructor->setNumCtorInitializers(1);
5329 CXXCtorInitializer **initializer =
5330 new (Context) CXXCtorInitializer*[1];
5331 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5332 Constructor->setCtorInitializers(initializer);
5333
5334 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5335 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5336 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5337 }
5338
5340
5341 DiagnoseUninitializedFields(*this, Constructor);
5342
5343 return false;
5344}
5345
5347 CXXRecordDecl *Class) {
5348 if (Class->isInvalidDecl())
5349 return nullptr;
5350 if (Class->hasIrrelevantDestructor())
5351 return nullptr;
5352
5353 // Dtor might still be missing, e.g because it's invalid.
5354 return S.LookupDestructor(Class);
5355}
5356
5358 FieldDecl *Field) {
5359 if (Field->isInvalidDecl())
5360 return;
5361
5362 // Don't destroy incomplete or zero-length arrays.
5363 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5364 return;
5365
5366 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5367
5368 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5369 if (!FieldClassDecl)
5370 return;
5371
5372 // The destructor for an implicit anonymous union member is never invoked.
5373 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5374 return;
5375
5376 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5377 if (!Dtor)
5378 return;
5379
5380 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5381 S.PDiag(diag::err_access_dtor_field)
5382 << Field->getDeclName() << FieldType);
5383
5384 S.MarkFunctionReferenced(Location, Dtor);
5385 S.DiagnoseUseOfDecl(Dtor, Location);
5386}
5387
5389 CXXRecordDecl *ClassDecl) {
5390 if (ClassDecl->isDependentContext())
5391 return;
5392
5393 // We only potentially invoke the destructors of potentially constructed
5394 // subobjects.
5395 bool VisitVirtualBases = !ClassDecl->isAbstract();
5396
5397 // If the destructor exists and has already been marked used in the MS ABI,
5398 // then virtual base destructors have already been checked and marked used.
5399 // Skip checking them again to avoid duplicate diagnostics.
5401 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5402 if (Dtor && Dtor->isUsed())
5403 VisitVirtualBases = false;
5404 }
5405
5407
5408 // Bases.
5409 for (const auto &Base : ClassDecl->bases()) {
5410 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5411 if (!BaseClassDecl)
5412 continue;
5413
5414 // Remember direct virtual bases.
5415 if (Base.isVirtual()) {
5416 if (!VisitVirtualBases)
5417 continue;
5418 DirectVirtualBases.insert(BaseClassDecl);
5419 }
5420
5421 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5422 if (!Dtor)
5423 continue;
5424
5425 // FIXME: caret should be on the start of the class name
5426 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5427 S.PDiag(diag::err_access_dtor_base)
5428 << Base.getType() << Base.getSourceRange(),
5429 S.Context.getCanonicalTagType(ClassDecl));
5430
5431 S.MarkFunctionReferenced(Location, Dtor);
5432 S.DiagnoseUseOfDecl(Dtor, Location);
5433 }
5434
5435 if (VisitVirtualBases)
5436 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5437 &DirectVirtualBases);
5438}
5439
5441 ArrayRef<CXXCtorInitializer *> Initializers) {
5442 if (Constructor->isDependentContext()) {
5443 // Just store the initializers as written, they will be checked during
5444 // instantiation.
5445 if (!Initializers.empty()) {
5446 Constructor->setNumCtorInitializers(Initializers.size());
5447 CXXCtorInitializer **baseOrMemberInitializers =
5448 new (Context) CXXCtorInitializer*[Initializers.size()];
5449 memcpy(baseOrMemberInitializers, Initializers.data(),
5450 Initializers.size() * sizeof(CXXCtorInitializer*));
5451 Constructor->setCtorInitializers(baseOrMemberInitializers);
5452 }
5453
5454 // Let template instantiation know whether we had errors.
5455 if (AnyErrors)
5456 Constructor->setInvalidDecl();
5457
5458 return false;
5459 }
5460
5461 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5462
5463 // We need to build the initializer AST according to order of construction
5464 // and not what user specified in the Initializers list.
5465 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5466 if (!ClassDecl)
5467 return true;
5468
5469 bool HadError = false;
5470
5471 for (unsigned i = 0; i < Initializers.size(); i++) {
5472 CXXCtorInitializer *Member = Initializers[i];
5473
5474 if (Member->isBaseInitializer())
5475 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5476 Member;
5477 else {
5478 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5479
5480 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5481 for (auto *C : F->chain()) {
5482 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5483 if (FD && FD->getParent()->isUnion())
5484 Info.ActiveUnionMember.insert(std::make_pair(
5486 }
5487 } else if (FieldDecl *FD = Member->getMember()) {
5488 if (FD->getParent()->isUnion())
5489 Info.ActiveUnionMember.insert(std::make_pair(
5491 }
5492 }
5493 }
5494
5495 // Keep track of the direct virtual bases.
5497 for (auto &I : ClassDecl->bases()) {
5498 if (I.isVirtual())
5499 DirectVBases.insert(&I);
5500 }
5501
5502 // Push virtual bases before others.
5503 for (auto &VBase : ClassDecl->vbases()) {
5504 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5505 VBase.getType()->getAsCanonical<RecordType>())) {
5506 // [class.base.init]p7, per DR257:
5507 // A mem-initializer where the mem-initializer-id names a virtual base
5508 // class is ignored during execution of a constructor of any class that
5509 // is not the most derived class.
5510 if (ClassDecl->isAbstract()) {
5511 // FIXME: Provide a fixit to remove the base specifier. This requires
5512 // tracking the location of the associated comma for a base specifier.
5513 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5514 << VBase.getType() << ClassDecl;
5515 DiagnoseAbstractType(ClassDecl);
5516 }
5517
5518 Info.AllToInit.push_back(Value);
5519 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5520 // [class.base.init]p8, per DR257:
5521 // If a given [...] base class is not named by a mem-initializer-id
5522 // [...] and the entity is not a virtual base class of an abstract
5523 // class, then [...] the entity is default-initialized.
5524 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5525 CXXCtorInitializer *CXXBaseInit;
5526 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5527 &VBase, IsInheritedVirtualBase,
5528 CXXBaseInit)) {
5529 HadError = true;
5530 continue;
5531 }
5532
5533 Info.AllToInit.push_back(CXXBaseInit);
5534 }
5535 }
5536
5537 // Non-virtual bases.
5538 for (auto &Base : ClassDecl->bases()) {
5539 // Virtuals are in the virtual base list and already constructed.
5540 if (Base.isVirtual())
5541 continue;
5542
5543 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5544 Base.getType()->getAsCanonical<RecordType>())) {
5545 Info.AllToInit.push_back(Value);
5546 } else if (!AnyErrors) {
5547 CXXCtorInitializer *CXXBaseInit;
5548 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5549 &Base, /*IsInheritedVirtualBase=*/false,
5550 CXXBaseInit)) {
5551 HadError = true;
5552 continue;
5553 }
5554
5555 Info.AllToInit.push_back(CXXBaseInit);
5556 }
5557 }
5558
5559 // Fields.
5560 for (auto *Mem : ClassDecl->decls()) {
5561 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5562 // C++ [class.bit]p2:
5563 // A declaration for a bit-field that omits the identifier declares an
5564 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5565 // initialized.
5566 if (F->isUnnamedBitField())
5567 continue;
5568
5569 // If we're not generating the implicit copy/move constructor, then we'll
5570 // handle anonymous struct/union fields based on their individual
5571 // indirect fields.
5572 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5573 continue;
5574
5575 if (CollectFieldInitializer(*this, Info, F))
5576 HadError = true;
5577 continue;
5578 }
5579
5580 // Beyond this point, we only consider default initialization.
5581 if (Info.isImplicitCopyOrMove())
5582 continue;
5583
5584 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5585 if (F->getType()->isIncompleteArrayType()) {
5586 assert(ClassDecl->hasFlexibleArrayMember() &&
5587 "Incomplete array type is not valid");
5588 continue;
5589 }
5590
5591 // Initialize each field of an anonymous struct individually.
5592 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5593 HadError = true;
5594
5595 continue;
5596 }
5597 }
5598
5599 unsigned NumInitializers = Info.AllToInit.size();
5600 if (NumInitializers > 0) {
5601 Constructor->setNumCtorInitializers(NumInitializers);
5602 CXXCtorInitializer **baseOrMemberInitializers =
5603 new (Context) CXXCtorInitializer*[NumInitializers];
5604 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5605 NumInitializers * sizeof(CXXCtorInitializer*));
5606 Constructor->setCtorInitializers(baseOrMemberInitializers);
5607
5608 SourceLocation Location = Constructor->getLocation();
5609
5610 // Constructors implicitly reference the base and member
5611 // destructors.
5612
5613 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5614 FieldDecl *Field = Initializer->getAnyMember();
5615 if (!Field)
5616 continue;
5617
5618 // C++ [class.base.init]p12:
5619 // In a non-delegating constructor, the destructor for each
5620 // potentially constructed subobject of class type is potentially
5621 // invoked.
5622 MarkFieldDestructorReferenced(*this, Location, Field);
5623 }
5624
5625 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5626 }
5627
5628 return HadError;
5629}
5630
5632 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5633 const RecordDecl *RD = RT->getOriginalDecl();
5634 if (RD->isAnonymousStructOrUnion()) {
5635 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5636 PopulateKeysForFields(Field, IdealInits);
5637 return;
5638 }
5639 }
5640 IdealInits.push_back(Field->getCanonicalDecl());
5641}
5642
5643static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5644 return Context.getCanonicalType(BaseType).getTypePtr();
5645}
5646
5647static const void *GetKeyForMember(ASTContext &Context,
5649 if (!Member->isAnyMemberInitializer())
5650 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5651
5652 return Member->getAnyMember()->getCanonicalDecl();
5653}
5654
5657 const CXXCtorInitializer *Current) {
5658 if (Previous->isAnyMemberInitializer())
5659 Diag << 0 << Previous->getAnyMember();
5660 else
5661 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5662
5663 if (Current->isAnyMemberInitializer())
5664 Diag << 0 << Current->getAnyMember();
5665 else
5666 Diag << 1 << Current->getTypeSourceInfo()->getType();
5667}
5668
5670 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5672 if (Constructor->getDeclContext()->isDependentContext())
5673 return;
5674
5675 // Don't check initializers order unless the warning is enabled at the
5676 // location of at least one initializer.
5677 bool ShouldCheckOrder = false;
5678 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5679 CXXCtorInitializer *Init = Inits[InitIndex];
5680 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5681 Init->getSourceLocation())) {
5682 ShouldCheckOrder = true;
5683 break;
5684 }
5685 }
5686 if (!ShouldCheckOrder)
5687 return;
5688
5689 // Build the list of bases and members in the order that they'll
5690 // actually be initialized. The explicit initializers should be in
5691 // this same order but may be missing things.
5692 SmallVector<const void*, 32> IdealInitKeys;
5693
5694 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5695
5696 // 1. Virtual bases.
5697 for (const auto &VBase : ClassDecl->vbases())
5698 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5699
5700 // 2. Non-virtual bases.
5701 for (const auto &Base : ClassDecl->bases()) {
5702 if (Base.isVirtual())
5703 continue;
5704 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5705 }
5706
5707 // 3. Direct fields.
5708 for (auto *Field : ClassDecl->fields()) {
5709 if (Field->isUnnamedBitField())
5710 continue;
5711
5712 PopulateKeysForFields(Field, IdealInitKeys);
5713 }
5714
5715 unsigned NumIdealInits = IdealInitKeys.size();
5716 unsigned IdealIndex = 0;
5717
5718 // Track initializers that are in an incorrect order for either a warning or
5719 // note if multiple ones occur.
5720 SmallVector<unsigned> WarnIndexes;
5721 // Correlates the index of an initializer in the init-list to the index of
5722 // the field/base in the class.
5723 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5724
5725 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5726 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5727
5728 // Scan forward to try to find this initializer in the idealized
5729 // initializers list.
5730 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5731 if (InitKey == IdealInitKeys[IdealIndex])
5732 break;
5733
5734 // If we didn't find this initializer, it must be because we
5735 // scanned past it on a previous iteration. That can only
5736 // happen if we're out of order; emit a warning.
5737 if (IdealIndex == NumIdealInits && InitIndex) {
5738 WarnIndexes.push_back(InitIndex);
5739
5740 // Move back to the initializer's location in the ideal list.
5741 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5742 if (InitKey == IdealInitKeys[IdealIndex])
5743 break;
5744
5745 assert(IdealIndex < NumIdealInits &&
5746 "initializer not found in initializer list");
5747 }
5748 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5749 }
5750
5751 if (WarnIndexes.empty())
5752 return;
5753
5754 // Sort based on the ideal order, first in the pair.
5755 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5756
5757 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5758 // emit the diagnostic before we can try adding notes.
5759 {
5761 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5762 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5763 : diag::warn_some_initializers_out_of_order);
5764
5765 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5766 if (CorrelatedInitOrder[I].second == I)
5767 continue;
5768 // Ideally we would be using InsertFromRange here, but clang doesn't
5769 // appear to handle InsertFromRange correctly when the source range is
5770 // modified by another fix-it.
5772 Inits[I]->getSourceRange(),
5775 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5776 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5777 }
5778
5779 // If there is only 1 item out of order, the warning expects the name and
5780 // type of each being added to it.
5781 if (WarnIndexes.size() == 1) {
5782 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5783 Inits[WarnIndexes.front()]);
5784 return;
5785 }
5786 }
5787 // More than 1 item to warn, create notes letting the user know which ones
5788 // are bad.
5789 for (unsigned WarnIndex : WarnIndexes) {
5790 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5791 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5792 diag::note_initializer_out_of_order);
5793 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5794 D << PrevInit->getSourceRange();
5795 }
5796}
5797
5798namespace {
5799bool CheckRedundantInit(Sema &S,
5800 CXXCtorInitializer *Init,
5801 CXXCtorInitializer *&PrevInit) {
5802 if (!PrevInit) {
5803 PrevInit = Init;
5804 return false;
5805 }
5806
5807 if (FieldDecl *Field = Init->getAnyMember())
5808 S.Diag(Init->getSourceLocation(),
5809 diag::err_multiple_mem_initialization)
5810 << Field->getDeclName()
5811 << Init->getSourceRange();
5812 else {
5813 const Type *BaseClass = Init->getBaseClass();
5814 assert(BaseClass && "neither field nor base");
5815 S.Diag(Init->getSourceLocation(),
5816 diag::err_multiple_base_initialization)
5817 << QualType(BaseClass, 0)
5818 << Init->getSourceRange();
5819 }
5820 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5821 << 0 << PrevInit->getSourceRange();
5822
5823 return true;
5824}
5825
5826typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5827typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5828
5829bool CheckRedundantUnionInit(Sema &S,
5830 CXXCtorInitializer *Init,
5831 RedundantUnionMap &Unions) {
5832 FieldDecl *Field = Init->getAnyMember();
5833 RecordDecl *Parent = Field->getParent();
5834 NamedDecl *Child = Field;
5835
5836 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5837 if (Parent->isUnion()) {
5838 UnionEntry &En = Unions[Parent];
5839 if (En.first && En.first != Child) {
5840 S.Diag(Init->getSourceLocation(),
5841 diag::err_multiple_mem_union_initialization)
5842 << Field->getDeclName()
5843 << Init->getSourceRange();
5844 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5845 << 0 << En.second->getSourceRange();
5846 return true;
5847 }
5848 if (!En.first) {
5849 En.first = Child;
5850 En.second = Init;
5851 }
5852 if (!Parent->isAnonymousStructOrUnion())
5853 return false;
5854 }
5855
5856 Child = Parent;
5857 Parent = cast<RecordDecl>(Parent->getDeclContext());
5858 }
5859
5860 return false;
5861}
5862} // namespace
5863
5864void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5865 SourceLocation ColonLoc,
5867 bool AnyErrors) {
5868 if (!ConstructorDecl)
5869 return;
5870
5871 AdjustDeclIfTemplate(ConstructorDecl);
5872
5874 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5875
5876 if (!Constructor) {
5877 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5878 return;
5879 }
5880
5881 // Mapping for the duplicate initializers check.
5882 // For member initializers, this is keyed with a FieldDecl*.
5883 // For base initializers, this is keyed with a Type*.
5884 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5885
5886 // Mapping for the inconsistent anonymous-union initializers check.
5887 RedundantUnionMap MemberUnions;
5888
5889 bool HadError = false;
5890 for (unsigned i = 0; i < MemInits.size(); i++) {
5891 CXXCtorInitializer *Init = MemInits[i];
5892
5893 // Set the source order index.
5894 Init->setSourceOrder(i);
5895
5896 if (Init->isAnyMemberInitializer()) {
5897 const void *Key = GetKeyForMember(Context, Init);
5898 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5899 CheckRedundantUnionInit(*this, Init, MemberUnions))
5900 HadError = true;
5901 } else if (Init->isBaseInitializer()) {
5902 const void *Key = GetKeyForMember(Context, Init);
5903 if (CheckRedundantInit(*this, Init, Members[Key]))
5904 HadError = true;
5905 } else {
5906 assert(Init->isDelegatingInitializer());
5907 // This must be the only initializer
5908 if (MemInits.size() != 1) {
5909 Diag(Init->getSourceLocation(),
5910 diag::err_delegating_initializer_alone)
5911 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5912 // We will treat this as being the only initializer.
5913 }
5915 // Return immediately as the initializer is set.
5916 return;
5917 }
5918 }
5919
5920 if (HadError)
5921 return;
5922
5924
5925 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5926
5927 DiagnoseUninitializedFields(*this, Constructor);
5928}
5929
5931 CXXRecordDecl *ClassDecl) {
5932 // Ignore dependent contexts. Also ignore unions, since their members never
5933 // have destructors implicitly called.
5934 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5935 return;
5936
5937 // FIXME: all the access-control diagnostics are positioned on the
5938 // field/base declaration. That's probably good; that said, the
5939 // user might reasonably want to know why the destructor is being
5940 // emitted, and we currently don't say.
5941
5942 // Non-static data members.
5943 for (auto *Field : ClassDecl->fields()) {
5944 MarkFieldDestructorReferenced(*this, Location, Field);
5945 }
5946
5947 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5948}
5949
5951 SourceLocation Location, CXXRecordDecl *ClassDecl,
5952 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5953 // Virtual bases.
5954 for (const auto &VBase : ClassDecl->vbases()) {
5955 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5956 if (!BaseClassDecl)
5957 continue;
5958
5959 // Ignore already visited direct virtual bases.
5960 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5961 continue;
5962
5963 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5964 if (!Dtor)
5965 continue;
5966
5967 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
5968 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
5969 PDiag(diag::err_access_dtor_vbase)
5970 << CT << VBase.getType(),
5971 CT) == AR_accessible) {
5973 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
5974 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
5975 }
5976
5977 MarkFunctionReferenced(Location, Dtor);
5978 DiagnoseUseOfDecl(Dtor, Location);
5979 }
5980}
5981
5983 if (!CDtorDecl)
5984 return;
5985
5987 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5988 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5989 !ClassDecl || ClassDecl->isInvalidDecl()) {
5990 return;
5991 }
5992 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5993 DiagnoseUninitializedFields(*this, Constructor);
5994 }
5995}
5996
5998 if (!getLangOpts().CPlusPlus)
5999 return false;
6000
6001 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6002 if (!RD)
6003 return false;
6004
6005 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6006 // class template specialization here, but doing so breaks a lot of code.
6007
6008 // We can't answer whether something is abstract until it has a
6009 // definition. If it's currently being defined, we'll walk back
6010 // over all the declarations when we have a full definition.
6011 const CXXRecordDecl *Def = RD->getDefinition();
6012 if (!Def || Def->isBeingDefined())
6013 return false;
6014
6015 return RD->isAbstract();
6016}
6017
6019 TypeDiagnoser &Diagnoser) {
6020 if (!isAbstractType(Loc, T))
6021 return false;
6022
6023 T = Context.getBaseElementType(T);
6024 Diagnoser.diagnose(*this, Loc, T);
6025 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6026 return true;
6027}
6028
6030 // Check if we've already emitted the list of pure virtual functions
6031 // for this class.
6033 return;
6034
6035 // If the diagnostic is suppressed, don't emit the notes. We're only
6036 // going to emit them once, so try to attach them to a diagnostic we're
6037 // actually going to show.
6038 if (Diags.isLastDiagnosticIgnored())
6039 return;
6040
6041 CXXFinalOverriderMap FinalOverriders;
6042 RD->getFinalOverriders(FinalOverriders);
6043
6044 // Keep a set of seen pure methods so we won't diagnose the same method
6045 // more than once.
6047
6048 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6049 MEnd = FinalOverriders.end();
6050 M != MEnd;
6051 ++M) {
6052 for (OverridingMethods::iterator SO = M->second.begin(),
6053 SOEnd = M->second.end();
6054 SO != SOEnd; ++SO) {
6055 // C++ [class.abstract]p4:
6056 // A class is abstract if it contains or inherits at least one
6057 // pure virtual function for which the final overrider is pure
6058 // virtual.
6059
6060 //
6061 if (SO->second.size() != 1)
6062 continue;
6063
6064 if (!SO->second.front().Method->isPureVirtual())
6065 continue;
6066
6067 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6068 continue;
6069
6070 Diag(SO->second.front().Method->getLocation(),
6071 diag::note_pure_virtual_function)
6072 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6073 }
6074 }
6075
6078 PureVirtualClassDiagSet->insert(RD);
6079}
6080
6081namespace {
6082struct AbstractUsageInfo {
6083 Sema &S;
6085 CanQualType AbstractType;
6086 bool Invalid;
6087
6088 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6089 : S(S), Record(Record),
6090 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6091
6092 void DiagnoseAbstractType() {
6093 if (Invalid) return;
6095 Invalid = true;
6096 }
6097
6098 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6099};
6100
6101struct CheckAbstractUsage {
6102 AbstractUsageInfo &Info;
6103 const NamedDecl *Ctx;
6104
6105 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6106 : Info(Info), Ctx(Ctx) {}
6107
6108 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6109 switch (TL.getTypeLocClass()) {
6110#define ABSTRACT_TYPELOC(CLASS, PARENT)
6111#define TYPELOC(CLASS, PARENT) \
6112 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6113#include "clang/AST/TypeLocNodes.def"
6114 }
6115 }
6116
6117 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6119 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6120 if (!TL.getParam(I))
6121 continue;
6122
6123 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6124 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6125 }
6126 }
6127
6128 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6130 }
6131
6132 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6133 // Visit the type parameters from a permissive context.
6134 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6135 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6137 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6138 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6139 // TODO: other template argument types?
6140 }
6141 }
6142
6143 // Visit pointee types from a permissive context.
6144#define CheckPolymorphic(Type) \
6145 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6146 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6147 }
6153
6154 /// Handle all the types we haven't given a more specific
6155 /// implementation for above.
6156 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6157 // Every other kind of type that we haven't called out already
6158 // that has an inner type is either (1) sugar or (2) contains that
6159 // inner type in some way as a subobject.
6160 if (TypeLoc Next = TL.getNextTypeLoc())
6161 return Visit(Next, Sel);
6162
6163 // If there's no inner type and we're in a permissive context,
6164 // don't diagnose.
6165 if (Sel == Sema::AbstractNone) return;
6166
6167 // Check whether the type matches the abstract type.
6168 QualType T = TL.getType();
6169 if (T->isArrayType()) {
6171 T = Info.S.Context.getBaseElementType(T);
6172 }
6173 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6174 if (CT != Info.AbstractType) return;
6175
6176 // It matched; do some magic.
6177 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6178 if (Sel == Sema::AbstractArrayType) {
6179 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6180 << T << TL.getSourceRange();
6181 } else {
6182 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6183 << Sel << T << TL.getSourceRange();
6184 }
6185 Info.DiagnoseAbstractType();
6186 }
6187};
6188
6189void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6191 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6192}
6193
6194}
6195
6196/// Check for invalid uses of an abstract type in a function declaration.
6197static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6198 FunctionDecl *FD) {
6199 // Only definitions are required to refer to complete and
6200 // non-abstract types.
6202 return;
6203
6204 // For safety's sake, just ignore it if we don't have type source
6205 // information. This should never happen for non-implicit methods,
6206 // but...
6207 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6208 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6209}
6210
6211/// Check for invalid uses of an abstract type in a variable0 declaration.
6212static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6213 VarDecl *VD) {
6214 // No need to do the check on definitions, which require that
6215 // the type is complete.
6217 return;
6218
6219 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6221}
6222
6223/// Check for invalid uses of an abstract type within a class definition.
6224static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6225 CXXRecordDecl *RD) {
6226 for (auto *D : RD->decls()) {
6227 if (D->isImplicit()) continue;
6228
6229 // Step through friends to the befriended declaration.
6230 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6231 D = FD->getFriendDecl();
6232 if (!D) continue;
6233 }
6234
6235 // Functions and function templates.
6236 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6237 CheckAbstractClassUsage(Info, FD);
6238 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6239 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6240
6241 // Fields and static variables.
6242 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6243 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6244 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6245 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6246 CheckAbstractClassUsage(Info, VD);
6247 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6248 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6249
6250 // Nested classes and class templates.
6251 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6252 CheckAbstractClassUsage(Info, RD);
6253 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6254 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6255 }
6256 }
6257}
6258
6260 Attr *ClassAttr = getDLLAttr(Class);
6261 if (!ClassAttr)
6262 return;
6263
6264 assert(ClassAttr->getKind() == attr::DLLExport);
6265
6266 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6267
6269 // Don't go any further if this is just an explicit instantiation
6270 // declaration.
6271 return;
6272
6273 // Add a context note to explain how we got to any diagnostics produced below.
6274 struct MarkingClassDllexported {
6275 Sema &S;
6276 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6277 SourceLocation AttrLoc)
6278 : S(S) {
6281 Ctx.PointOfInstantiation = AttrLoc;
6282 Ctx.Entity = Class;
6284 }
6285 ~MarkingClassDllexported() {
6287 }
6288 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6289
6290 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6291 S.MarkVTableUsed(Class->getLocation(), Class, true);
6292
6293 for (Decl *Member : Class->decls()) {
6294 // Skip members that were not marked exported.
6295 if (!Member->hasAttr<DLLExportAttr>())
6296 continue;
6297
6298 // Defined static variables that are members of an exported base
6299 // class must be marked export too.
6300 auto *VD = dyn_cast<VarDecl>(Member);
6301 if (VD && VD->getStorageClass() == SC_Static &&
6303 S.MarkVariableReferenced(VD->getLocation(), VD);
6304
6305 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6306 if (!MD)
6307 continue;
6308
6309 if (MD->isUserProvided()) {
6310 // Instantiate non-default class member functions ...
6311
6312 // .. except for certain kinds of template specializations.
6313 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6314 continue;
6315
6316 // If this is an MS ABI dllexport default constructor, instantiate any
6317 // default arguments.
6319 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6320 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6322 }
6323 }
6324
6325 S.MarkFunctionReferenced(Class->getLocation(), MD);
6326
6327 // The function will be passed to the consumer when its definition is
6328 // encountered.
6329 } else if (MD->isExplicitlyDefaulted()) {
6330 // Synthesize and instantiate explicitly defaulted methods.
6331 S.MarkFunctionReferenced(Class->getLocation(), MD);
6332
6334 // Except for explicit instantiation defs, we will not see the
6335 // definition again later, so pass it to the consumer now.
6337 }
6338 } else if (!MD->isTrivial() ||
6339 MD->isCopyAssignmentOperator() ||
6340 MD->isMoveAssignmentOperator()) {
6341 // Synthesize and instantiate non-trivial implicit methods, and the copy
6342 // and move assignment operators. The latter are exported even if they
6343 // are trivial, because the address of an operator can be taken and
6344 // should compare equal across libraries.
6345 S.MarkFunctionReferenced(Class->getLocation(), MD);
6346
6347 // There is no later point when we will see the definition of this
6348 // function, so pass it to the consumer now.
6350 }
6351 }
6352}
6353
6355 CXXRecordDecl *Class) {
6356 // Only the MS ABI has default constructor closures, so we don't need to do
6357 // this semantic checking anywhere else.
6359 return;
6360
6361 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6362 for (Decl *Member : Class->decls()) {
6363 // Look for exported default constructors.
6364 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6365 if (!CD || !CD->isDefaultConstructor())
6366 continue;
6367 auto *Attr = CD->getAttr<DLLExportAttr>();
6368 if (!Attr)
6369 continue;
6370
6371 // If the class is non-dependent, mark the default arguments as ODR-used so
6372 // that we can properly codegen the constructor closure.
6373 if (!Class->isDependentContext()) {
6374 for (ParmVarDecl *PD : CD->parameters()) {
6375 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6377 }
6378 }
6379
6380 if (LastExportedDefaultCtor) {
6381 S.Diag(LastExportedDefaultCtor->getLocation(),
6382 diag::err_attribute_dll_ambiguous_default_ctor)
6383 << Class;
6384 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6385 << CD->getDeclName();
6386 return;
6387 }
6388 LastExportedDefaultCtor = CD;
6389 }
6390}
6391
6393 CXXRecordDecl *Class) {
6394 bool ErrorReported = false;
6395 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6396 ClassTemplateDecl *TD) {
6397 if (ErrorReported)
6398 return;
6399 S.Diag(TD->getLocation(),
6400 diag::err_cuda_device_builtin_surftex_cls_template)
6401 << /*surface*/ 0 << TD;
6402 ErrorReported = true;
6403 };
6404
6405 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6406 if (!TD) {
6407 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6408 if (!SD) {
6409 S.Diag(Class->getLocation(),
6410 diag::err_cuda_device_builtin_surftex_ref_decl)
6411 << /*surface*/ 0 << Class;
6412 S.Diag(Class->getLocation(),
6413 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6414 << Class;
6415 return;
6416 }
6417 TD = SD->getSpecializedTemplate();
6418 }
6419
6421 unsigned N = Params->size();
6422
6423 if (N != 2) {
6424 reportIllegalClassTemplate(S, TD);
6425 S.Diag(TD->getLocation(),
6426 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6427 << TD << 2;
6428 }
6429 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6430 reportIllegalClassTemplate(S, TD);
6431 S.Diag(TD->getLocation(),
6432 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6433 << TD << /*1st*/ 0 << /*type*/ 0;
6434 }
6435 if (N > 1) {
6436 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6437 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6438 reportIllegalClassTemplate(S, TD);
6439 S.Diag(TD->getLocation(),
6440 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6441 << TD << /*2nd*/ 1 << /*integer*/ 1;
6442 }
6443 }
6444}
6445
6447 CXXRecordDecl *Class) {
6448 bool ErrorReported = false;
6449 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6450 ClassTemplateDecl *TD) {
6451 if (ErrorReported)
6452 return;
6453 S.Diag(TD->getLocation(),
6454 diag::err_cuda_device_builtin_surftex_cls_template)
6455 << /*texture*/ 1 << TD;
6456 ErrorReported = true;
6457 };
6458
6459 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6460 if (!TD) {
6461 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6462 if (!SD) {
6463 S.Diag(Class->getLocation(),
6464 diag::err_cuda_device_builtin_surftex_ref_decl)
6465 << /*texture*/ 1 << Class;
6466 S.Diag(Class->getLocation(),
6467 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6468 << Class;
6469 return;
6470 }
6471 TD = SD->getSpecializedTemplate();
6472 }
6473
6475 unsigned N = Params->size();
6476
6477 if (N != 3) {
6478 reportIllegalClassTemplate(S, TD);
6479 S.Diag(TD->getLocation(),
6480 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6481 << TD << 3;
6482 }
6483 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6484 reportIllegalClassTemplate(S, TD);
6485 S.Diag(TD->getLocation(),
6486 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6487 << TD << /*1st*/ 0 << /*type*/ 0;
6488 }
6489 if (N > 1) {
6490 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6491 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6492 reportIllegalClassTemplate(S, TD);
6493 S.Diag(TD->getLocation(),
6494 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6495 << TD << /*2nd*/ 1 << /*integer*/ 1;
6496 }
6497 }
6498 if (N > 2) {
6499 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6500 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6501 reportIllegalClassTemplate(S, TD);
6502 S.Diag(TD->getLocation(),
6503 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6504 << TD << /*3rd*/ 2 << /*integer*/ 1;
6505 }
6506 }
6507}
6508
6510 // Mark any compiler-generated routines with the implicit code_seg attribute.
6511 for (auto *Method : Class->methods()) {
6512 if (Method->isUserProvided())
6513 continue;
6514 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6515 Method->addAttr(A);
6516 }
6517}
6518
6520 Attr *ClassAttr = getDLLAttr(Class);
6521
6522 // MSVC inherits DLL attributes to partial class template specializations.
6523 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6524 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6525 if (Attr *TemplateAttr =
6526 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6527 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6528 A->setInherited(true);
6529 ClassAttr = A;
6530 }
6531 }
6532 }
6533
6534 if (!ClassAttr)
6535 return;
6536
6537 // MSVC allows imported or exported template classes that have UniqueExternal
6538 // linkage. This occurs when the template class has been instantiated with
6539 // a template parameter which itself has internal linkage.
6540 // We drop the attribute to avoid exporting or importing any members.
6541 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6542 Context.getTargetInfo().getTriple().isPS()) &&
6543 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6544 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6545 return;
6546 }
6547
6548 if (!Class->isExternallyVisible()) {
6549 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6550 << Class << ClassAttr;
6551 return;
6552 }
6553
6554 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6555 !ClassAttr->isInherited()) {
6556 // Diagnose dll attributes on members of class with dll attribute.
6557 for (Decl *Member : Class->decls()) {
6559 continue;
6560 InheritableAttr *MemberAttr = getDLLAttr(Member);
6561 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6562 continue;
6563
6564 Diag(MemberAttr->getLocation(),
6565 diag::err_attribute_dll_member_of_dll_class)
6566 << MemberAttr << ClassAttr;
6567 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6568 Member->setInvalidDecl();
6569 }
6570 }
6571
6572 if (Class->getDescribedClassTemplate())
6573 // Don't inherit dll attribute until the template is instantiated.
6574 return;
6575
6576 // The class is either imported or exported.
6577 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6578
6579 // Check if this was a dllimport attribute propagated from a derived class to
6580 // a base class template specialization. We don't apply these attributes to
6581 // static data members.
6582 const bool PropagatedImport =
6583 !ClassExported &&
6584 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6585
6586 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6587
6588 // Ignore explicit dllexport on explicit class template instantiation
6589 // declarations, except in MinGW mode.
6590 if (ClassExported && !ClassAttr->isInherited() &&
6592 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6593 Class->dropAttr<DLLExportAttr>();
6594 return;
6595 }
6596
6597 // Force declaration of implicit members so they can inherit the attribute.
6599
6600 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6601 // seem to be true in practice?
6602
6603 for (Decl *Member : Class->decls()) {
6604 VarDecl *VD = dyn_cast<VarDecl>(Member);
6605 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6606
6607 // Only methods and static fields inherit the attributes.
6608 if (!VD && !MD)
6609 continue;
6610
6611 if (MD) {
6612 // Don't process deleted methods.
6613 if (MD->isDeleted())
6614 continue;
6615
6616 if (MD->isInlined()) {
6617 // MinGW does not import or export inline methods. But do it for
6618 // template instantiations.
6619 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6622 continue;
6623
6624 // MSVC versions before 2015 don't export the move assignment operators
6625 // and move constructor, so don't attempt to import/export them if
6626 // we have a definition.
6627 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6628 if ((MD->isMoveAssignmentOperator() ||
6629 (Ctor && Ctor->isMoveConstructor())) &&
6630 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6631 continue;
6632
6633 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6634 // operator is exported anyway.
6635 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6636 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6637 continue;
6638 }
6639 }
6640
6641 // Don't apply dllimport attributes to static data members of class template
6642 // instantiations when the attribute is propagated from a derived class.
6643 if (VD && PropagatedImport)
6644 continue;
6645
6647 continue;
6648
6649 if (!getDLLAttr(Member)) {
6650 InheritableAttr *NewAttr = nullptr;
6651
6652 // Do not export/import inline function when -fno-dllexport-inlines is
6653 // passed. But add attribute for later local static var check.
6654 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6657 if (ClassExported) {
6658 NewAttr = ::new (getASTContext())
6659 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6660 } else {
6661 NewAttr = ::new (getASTContext())
6662 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6663 }
6664 } else {
6665 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6666 }
6667
6668 NewAttr->setInherited(true);
6669 Member->addAttr(NewAttr);
6670
6671 if (MD) {
6672 // Propagate DLLAttr to friend re-declarations of MD that have already
6673 // been constructed.
6674 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6675 FD = FD->getPreviousDecl()) {
6677 continue;
6678 assert(!getDLLAttr(FD) &&
6679 "friend re-decl should not already have a DLLAttr");
6680 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6681 NewAttr->setInherited(true);
6682 FD->addAttr(NewAttr);
6683 }
6684 }
6685 }
6686 }
6687
6688 if (ClassExported)
6689 DelayedDllExportClasses.push_back(Class);
6690}
6691
6693 CXXRecordDecl *Class, Attr *ClassAttr,
6694 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6695 if (getDLLAttr(
6696 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6697 // If the base class template has a DLL attribute, don't try to change it.
6698 return;
6699 }
6700
6701 auto TSK = BaseTemplateSpec->getSpecializationKind();
6702 if (!getDLLAttr(BaseTemplateSpec) &&
6704 TSK == TSK_ImplicitInstantiation)) {
6705 // The template hasn't been instantiated yet (or it has, but only as an
6706 // explicit instantiation declaration or implicit instantiation, which means
6707 // we haven't codegenned any members yet), so propagate the attribute.
6708 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6709 NewAttr->setInherited(true);
6710 BaseTemplateSpec->addAttr(NewAttr);
6711
6712 // If this was an import, mark that we propagated it from a derived class to
6713 // a base class template specialization.
6714 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6715 ImportAttr->setPropagatedToBaseTemplate();
6716
6717 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6718 // needs to be run again to work see the new attribute. Otherwise this will
6719 // get run whenever the template is instantiated.
6720 if (TSK != TSK_Undeclared)
6721 checkClassLevelDLLAttribute(BaseTemplateSpec);
6722
6723 return;
6724 }
6725
6726 if (getDLLAttr(BaseTemplateSpec)) {
6727 // The template has already been specialized or instantiated with an
6728 // attribute, explicitly or through propagation. We should not try to change
6729 // it.
6730 return;
6731 }
6732
6733 // The template was previously instantiated or explicitly specialized without
6734 // a dll attribute, It's too late for us to add an attribute, so warn that
6735 // this is unsupported.
6736 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6737 << BaseTemplateSpec->isExplicitSpecialization();
6738 Diag(ClassAttr->getLocation(), diag::note_attribute);
6739 if (BaseTemplateSpec->isExplicitSpecialization()) {
6740 Diag(BaseTemplateSpec->getLocation(),
6741 diag::note_template_class_explicit_specialization_was_here)
6742 << BaseTemplateSpec;
6743 } else {
6744 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6745 diag::note_template_class_instantiation_was_here)
6746 << BaseTemplateSpec;
6747 }
6748}
6749
6752 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6753 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6754 if (Ctor->isDefaultConstructor())
6756
6757 if (Ctor->isCopyConstructor())
6759
6760 if (Ctor->isMoveConstructor())
6762 }
6763
6764 if (MD->isCopyAssignmentOperator())
6766
6767 if (MD->isMoveAssignmentOperator())
6769
6770 if (isa<CXXDestructorDecl>(FD))
6772 }
6773
6774 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6775 case OO_EqualEqual:
6777
6778 case OO_ExclaimEqual:
6780
6781 case OO_Spaceship:
6782 // No point allowing this if <=> doesn't exist in the current language mode.
6783 if (!getLangOpts().CPlusPlus20)
6784 break;
6786
6787 case OO_Less:
6788 case OO_LessEqual:
6789 case OO_Greater:
6790 case OO_GreaterEqual:
6791 // No point allowing this if <=> doesn't exist in the current language mode.
6792 if (!getLangOpts().CPlusPlus20)
6793 break;
6795
6796 default:
6797 break;
6798 }
6799
6800 // Not defaultable.
6801 return DefaultedFunctionKind();
6802}
6803
6805 SourceLocation DefaultLoc) {
6807 if (DFK.isComparison())
6808 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6809
6810 switch (DFK.asSpecialMember()) {
6814 break;
6817 break;
6820 break;
6823 break;
6826 break;
6829 break;
6831 llvm_unreachable("Invalid special member.");
6832 }
6833}
6834
6835/// Determine whether a type is permitted to be passed or returned in
6836/// registers, per C++ [class.temporary]p3.
6839 if (D->isDependentType() || D->isInvalidDecl())
6840 return false;
6841
6842 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6843 // The PS4 platform ABI follows the behavior of Clang 3.2.
6845 return !D->hasNonTrivialDestructorForCall() &&
6847
6848 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6849 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6850 bool DtorIsTrivialForCall = false;
6851
6852 // If a class has at least one eligible, trivial copy constructor, it
6853 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6854 //
6855 // Note: This permits classes with non-trivial copy or move ctors to be
6856 // passed in registers, so long as they *also* have a trivial copy ctor,
6857 // which is non-conforming.
6861 CopyCtorIsTrivial = true;
6863 CopyCtorIsTrivialForCall = true;
6864 }
6865 } else {
6866 for (const CXXConstructorDecl *CD : D->ctors()) {
6867 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6868 !CD->isIneligibleOrNotSelected()) {
6869 if (CD->isTrivial())
6870 CopyCtorIsTrivial = true;
6871 if (CD->isTrivialForCall())
6872 CopyCtorIsTrivialForCall = true;
6873 }
6874 }
6875 }
6876
6877 if (D->needsImplicitDestructor()) {
6878 if (!D->defaultedDestructorIsDeleted() &&
6880 DtorIsTrivialForCall = true;
6881 } else if (const auto *DD = D->getDestructor()) {
6882 if (!DD->isDeleted() && DD->isTrivialForCall())
6883 DtorIsTrivialForCall = true;
6884 }
6885
6886 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6887 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6888 return true;
6889
6890 // If a class has a destructor, we'd really like to pass it indirectly
6891 // because it allows us to elide copies. Unfortunately, MSVC makes that
6892 // impossible for small types, which it will pass in a single register or
6893 // stack slot. Most objects with dtors are large-ish, so handle that early.
6894 // We can't call out all large objects as being indirect because there are
6895 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6896 // how we pass large POD types.
6897
6898 // Note: This permits small classes with nontrivial destructors to be
6899 // passed in registers, which is non-conforming.
6900 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6901 uint64_t TypeSize = isAArch64 ? 128 : 64;
6902
6903 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
6904 S.Context.getCanonicalTagType(D)) <= TypeSize)
6905 return true;
6906 return false;
6907 }
6908
6909 // Per C++ [class.temporary]p3, the relevant condition is:
6910 // each copy constructor, move constructor, and destructor of X is
6911 // either trivial or deleted, and X has at least one non-deleted copy
6912 // or move constructor
6913 bool HasNonDeletedCopyOrMove = false;
6914
6918 return false;
6919 HasNonDeletedCopyOrMove = true;
6920 }
6921
6922 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6925 return false;
6926 HasNonDeletedCopyOrMove = true;
6927 }
6928
6931 return false;
6932
6933 for (const CXXMethodDecl *MD : D->methods()) {
6934 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6935 continue;
6936
6937 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6938 if (CD && CD->isCopyOrMoveConstructor())
6939 HasNonDeletedCopyOrMove = true;
6940 else if (!isa<CXXDestructorDecl>(MD))
6941 continue;
6942
6943 if (!MD->isTrivialForCall())
6944 return false;
6945 }
6946
6947 return HasNonDeletedCopyOrMove;
6948}
6949
6950/// Report an error regarding overriding, along with any relevant
6951/// overridden methods.
6952///
6953/// \param DiagID the primary error to report.
6954/// \param MD the overriding method.
6955static bool
6956ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6957 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6958 bool IssuedDiagnostic = false;
6959 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6960 if (Report(O)) {
6961 if (!IssuedDiagnostic) {
6962 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6963 IssuedDiagnostic = true;
6964 }
6965 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6966 }
6967 }
6968 return IssuedDiagnostic;
6969}
6970
6972 if (!Record)
6973 return;
6974
6975 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6976 AbstractUsageInfo Info(*this, Record);
6978 }
6979
6980 // If this is not an aggregate type and has no user-declared constructor,
6981 // complain about any non-static data members of reference or const scalar
6982 // type, since they will never get initializers.
6983 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6984 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6985 !Record->isLambda()) {
6986 bool Complained = false;
6987 for (const auto *F : Record->fields()) {
6988 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6989 continue;
6990
6991 if (F->getType()->isReferenceType() ||
6992 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6993 if (!Complained) {
6994 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6995 << Record->getTagKind() << Record;
6996 Complained = true;
6997 }
6998
6999 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7000 << F->getType()->isReferenceType()
7001 << F->getDeclName();
7002 }
7003 }
7004 }
7005
7006 if (Record->getIdentifier()) {
7007 // C++ [class.mem]p13:
7008 // If T is the name of a class, then each of the following shall have a
7009 // name different from T:
7010 // - every member of every anonymous union that is a member of class T.
7011 //
7012 // C++ [class.mem]p14:
7013 // In addition, if class T has a user-declared constructor (12.1), every
7014 // non-static data member of class T shall have a name different from T.
7015 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7017 ++I) {
7018 NamedDecl *D = (*I)->getUnderlyingDecl();
7019 // Invalid IndirectFieldDecls have already been diagnosed with
7020 // err_anonymous_record_member_redecl in
7021 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7023 Record->hasUserDeclaredConstructor()) ||
7024 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7025 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7026 << D->getDeclName();
7027 break;
7028 }
7029 }
7030 }
7031
7032 // Warn if the class has virtual methods but non-virtual public destructor.
7033 if (Record->isPolymorphic() && !Record->isDependentType()) {
7034 CXXDestructorDecl *dtor = Record->getDestructor();
7035 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7036 !Record->hasAttr<FinalAttr>())
7037 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7038 diag::warn_non_virtual_dtor)
7039 << Context.getCanonicalTagType(Record);
7040 }
7041
7042 if (Record->isAbstract()) {
7043 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7044 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7045 << FA->isSpelledAsSealed();
7047 }
7048 }
7049
7050 // Warn if the class has a final destructor but is not itself marked final.
7051 if (!Record->hasAttr<FinalAttr>()) {
7052 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7053 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7054 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7055 << FA->isSpelledAsSealed()
7057 getLocForEndOfToken(Record->getLocation()),
7058 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7059 Diag(Record->getLocation(),
7060 diag::note_final_dtor_non_final_class_silence)
7061 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7062 }
7063 }
7064 }
7065
7066 // See if trivial_abi has to be dropped.
7067 if (Record->hasAttr<TrivialABIAttr>())
7069
7070 // Set HasTrivialSpecialMemberForCall if the record has attribute
7071 // "trivial_abi".
7072 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7073
7074 if (HasTrivialABI)
7075 Record->setHasTrivialSpecialMemberForCall();
7076
7077 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7078 // We check these last because they can depend on the properties of the
7079 // primary comparison functions (==, <=>).
7080 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7081
7082 // Perform checks that can't be done until we know all the properties of a
7083 // member function (whether it's defaulted, deleted, virtual, overriding,
7084 // ...).
7085 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7086 // A static function cannot override anything.
7087 if (MD->getStorageClass() == SC_Static) {
7088 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7089 [](const CXXMethodDecl *) { return true; }))
7090 return;
7091 }
7092
7093 // A deleted function cannot override a non-deleted function and vice
7094 // versa.
7095 if (ReportOverrides(*this,
7096 MD->isDeleted() ? diag::err_deleted_override
7097 : diag::err_non_deleted_override,
7098 MD, [&](const CXXMethodDecl *V) {
7099 return MD->isDeleted() != V->isDeleted();
7100 })) {
7101 if (MD->isDefaulted() && MD->isDeleted())
7102 // Explain why this defaulted function was deleted.
7104 return;
7105 }
7106
7107 // A consteval function cannot override a non-consteval function and vice
7108 // versa.
7109 if (ReportOverrides(*this,
7110 MD->isConsteval() ? diag::err_consteval_override
7111 : diag::err_non_consteval_override,
7112 MD, [&](const CXXMethodDecl *V) {
7113 return MD->isConsteval() != V->isConsteval();
7114 })) {
7115 if (MD->isDefaulted() && MD->isDeleted())
7116 // Explain why this defaulted function was deleted.
7118 return;
7119 }
7120 };
7121
7122 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7123 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7124 return false;
7125
7129 DefaultedSecondaryComparisons.push_back(FD);
7130 return true;
7131 }
7132
7134 return false;
7135 };
7136
7137 if (!Record->isInvalidDecl() &&
7138 Record->hasAttr<VTablePointerAuthenticationAttr>())
7140
7141 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7142 // Check whether the explicitly-defaulted members are valid.
7143 bool Incomplete = CheckForDefaultedFunction(M);
7144
7145 // Skip the rest of the checks for a member of a dependent class.
7146 if (Record->isDependentType())
7147 return;
7148
7149 // For an explicitly defaulted or deleted special member, we defer
7150 // determining triviality until the class is complete. That time is now!
7152 if (!M->isImplicit() && !M->isUserProvided()) {
7153 if (CSM != CXXSpecialMemberKind::Invalid) {
7154 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7155 // Inform the class that we've finished declaring this member.
7156 Record->finishedDefaultedOrDeletedMember(M);
7157 M->setTrivialForCall(
7158 HasTrivialABI ||
7161 Record->setTrivialForCallFlags(M);
7162 }
7163 }
7164
7165 // Set triviality for the purpose of calls if this is a user-provided
7166 // copy/move constructor or destructor.
7170 M->isUserProvided()) {
7171 M->setTrivialForCall(HasTrivialABI);
7172 Record->setTrivialForCallFlags(M);
7173 }
7174
7175 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7176 M->hasAttr<DLLExportAttr>()) {
7177 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7178 M->isTrivial() &&
7182 M->dropAttr<DLLExportAttr>();
7183
7184 if (M->hasAttr<DLLExportAttr>()) {
7185 // Define after any fields with in-class initializers have been parsed.
7187 }
7188 }
7189
7190 bool EffectivelyConstexprDestructor = true;
7191 // Avoid triggering vtable instantiation due to a dtor that is not
7192 // "effectively constexpr" for better compatibility.
7193 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7194 if (isa<CXXDestructorDecl>(M)) {
7195 llvm::SmallDenseSet<QualType> Visited;
7196 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7197 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7198 return false;
7199 const CXXRecordDecl *RD =
7200 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7201 if (!RD || !RD->isCompleteDefinition())
7202 return true;
7203
7204 if (!RD->hasConstexprDestructor())
7205 return false;
7206
7207 for (const CXXBaseSpecifier &B : RD->bases())
7208 if (!Check(B.getType(), Check))
7209 return false;
7210 for (const FieldDecl *FD : RD->fields())
7211 if (!Check(FD->getType(), Check))
7212 return false;
7213 return true;
7214 };
7215 EffectivelyConstexprDestructor =
7216 Check(Context.getCanonicalTagType(Record), Check);
7217 }
7218
7219 // Define defaulted constexpr virtual functions that override a base class
7220 // function right away.
7221 // FIXME: We can defer doing this until the vtable is marked as used.
7222 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7223 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7224 EffectivelyConstexprDestructor)
7225 DefineDefaultedFunction(*this, M, M->getLocation());
7226
7227 if (!Incomplete)
7228 CheckCompletedMemberFunction(M);
7229 };
7230
7231 // Check the destructor before any other member function. We need to
7232 // determine whether it's trivial in order to determine whether the claas
7233 // type is a literal type, which is a prerequisite for determining whether
7234 // other special member functions are valid and whether they're implicitly
7235 // 'constexpr'.
7236 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7237 CompleteMemberFunction(Dtor);
7238
7239 bool HasMethodWithOverrideControl = false,
7240 HasOverridingMethodWithoutOverrideControl = false;
7241 for (auto *D : Record->decls()) {
7242 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7243 // FIXME: We could do this check for dependent types with non-dependent
7244 // bases.
7245 if (!Record->isDependentType()) {
7246 // See if a method overloads virtual methods in a base
7247 // class without overriding any.
7248 if (!M->isStatic())
7250
7251 if (M->hasAttr<OverrideAttr>()) {
7252 HasMethodWithOverrideControl = true;
7253 } else if (M->size_overridden_methods() > 0) {
7254 HasOverridingMethodWithoutOverrideControl = true;
7255 } else {
7256 // Warn on newly-declared virtual methods in `final` classes
7257 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7258 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7259 << M;
7260 }
7261 }
7262 }
7263
7264 if (!isa<CXXDestructorDecl>(M))
7265 CompleteMemberFunction(M);
7266 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7267 CheckForDefaultedFunction(
7268 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7269 }
7270 }
7271
7272 if (HasOverridingMethodWithoutOverrideControl) {
7273 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7274 for (auto *M : Record->methods())
7275 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7276 }
7277
7278 // Check the defaulted secondary comparisons after any other member functions.
7279 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7281
7282 // If this is a member function, we deferred checking it until now.
7283 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7284 CheckCompletedMemberFunction(MD);
7285 }
7286
7287 // ms_struct is a request to use the same ABI rules as MSVC. Check
7288 // whether this class uses any C++ features that are implemented
7289 // completely differently in MSVC, and if so, emit a diagnostic.
7290 // That diagnostic defaults to an error, but we allow projects to
7291 // map it down to a warning (or ignore it). It's a fairly common
7292 // practice among users of the ms_struct pragma to mass-annotate
7293 // headers, sweeping up a bunch of types that the project doesn't
7294 // really rely on MSVC-compatible layout for. We must therefore
7295 // support "ms_struct except for C++ stuff" as a secondary ABI.
7296 // Don't emit this diagnostic if the feature was enabled as a
7297 // language option (as opposed to via a pragma or attribute), as
7298 // the option -mms-bitfields otherwise essentially makes it impossible
7299 // to build C++ code, unless this diagnostic is turned off.
7300 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7301 (Record->isPolymorphic() || Record->getNumBases())) {
7302 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7303 }
7304
7307
7308 bool ClangABICompat4 =
7309 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7311 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7312 bool CanPass = canPassInRegisters(*this, Record, CCK);
7313
7314 // Do not change ArgPassingRestrictions if it has already been set to
7315 // RecordArgPassingKind::CanNeverPassInRegs.
7316 if (Record->getArgPassingRestrictions() !=
7318 Record->setArgPassingRestrictions(
7321
7322 // If canPassInRegisters returns true despite the record having a non-trivial
7323 // destructor, the record is destructed in the callee. This happens only when
7324 // the record or one of its subobjects has a field annotated with trivial_abi
7325 // or a field qualified with ObjC __strong/__weak.
7326 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7327 Record->setParamDestroyedInCallee(true);
7328 else if (Record->hasNonTrivialDestructor())
7329 Record->setParamDestroyedInCallee(CanPass);
7330
7331 if (getLangOpts().ForceEmitVTables) {
7332 // If we want to emit all the vtables, we need to mark it as used. This
7333 // is especially required for cases like vtable assumption loads.
7334 MarkVTableUsed(Record->getInnerLocStart(), Record);
7335 }
7336
7337 if (getLangOpts().CUDA) {
7338 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7340 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7342 }
7343
7344 llvm::SmallDenseMap<OverloadedOperatorKind,
7346 TypeAwareDecls{{OO_New, {}},
7347 {OO_Array_New, {}},
7348 {OO_Delete, {}},
7349 {OO_Array_New, {}}};
7350 for (auto *D : Record->decls()) {
7351 const FunctionDecl *FnDecl = D->getAsFunction();
7352 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7353 continue;
7354 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7355 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7356 }
7357 auto CheckMismatchedTypeAwareAllocators =
7358 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7359 OverloadedOperatorKind DeleteKind) {
7360 auto &NewDecls = TypeAwareDecls[NewKind];
7361 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7362 if (NewDecls.empty() == DeleteDecls.empty())
7363 return;
7364 DeclarationName FoundOperator =
7365 Context.DeclarationNames.getCXXOperatorName(
7366 NewDecls.empty() ? DeleteKind : NewKind);
7367 DeclarationName MissingOperator =
7368 Context.DeclarationNames.getCXXOperatorName(
7369 NewDecls.empty() ? NewKind : DeleteKind);
7370 Diag(Record->getLocation(),
7371 diag::err_type_aware_allocator_missing_matching_operator)
7372 << FoundOperator << Context.getCanonicalTagType(Record)
7373 << MissingOperator;
7374 for (auto MD : NewDecls)
7375 Diag(MD->getLocation(),
7376 diag::note_unmatched_type_aware_allocator_declared)
7377 << MD;
7378 for (auto MD : DeleteDecls)
7379 Diag(MD->getLocation(),
7380 diag::note_unmatched_type_aware_allocator_declared)
7381 << MD;
7382 };
7383 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7384 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7385}
7386
7387/// Look up the special member function that would be called by a special
7388/// member function for a subobject of class type.
7389///
7390/// \param Class The class type of the subobject.
7391/// \param CSM The kind of special member function.
7392/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7393/// \param ConstRHS True if this is a copy operation with a const object
7394/// on its RHS, that is, if the argument to the outer special member
7395/// function is 'const' and this is not a field marked 'mutable'.
7398 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7399 bool ConstRHS) {
7400 unsigned LHSQuals = 0;
7403 LHSQuals = FieldQuals;
7404
7405 unsigned RHSQuals = FieldQuals;
7408 RHSQuals = 0;
7409 else if (ConstRHS)
7410 RHSQuals |= Qualifiers::Const;
7411
7412 return S.LookupSpecialMember(Class, CSM,
7413 RHSQuals & Qualifiers::Const,
7414 RHSQuals & Qualifiers::Volatile,
7415 false,
7416 LHSQuals & Qualifiers::Const,
7417 LHSQuals & Qualifiers::Volatile);
7418}
7419
7421 Sema &S;
7422 SourceLocation UseLoc;
7423
7424 /// A mapping from the base classes through which the constructor was
7425 /// inherited to the using shadow declaration in that base class (or a null
7426 /// pointer if the constructor was declared in that base class).
7427 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7428 InheritedFromBases;
7429
7430public:
7433 : S(S), UseLoc(UseLoc) {
7434 bool DiagnosedMultipleConstructedBases = false;
7435 CXXRecordDecl *ConstructedBase = nullptr;
7436 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7437
7438 // Find the set of such base class subobjects and check that there's a
7439 // unique constructed subobject.
7440 for (auto *D : Shadow->redecls()) {
7441 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7442 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7443 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7444
7445 InheritedFromBases.insert(
7446 std::make_pair(DNominatedBase->getCanonicalDecl(),
7447 DShadow->getNominatedBaseClassShadowDecl()));
7448 if (DShadow->constructsVirtualBase())
7449 InheritedFromBases.insert(
7450 std::make_pair(DConstructedBase->getCanonicalDecl(),
7451 DShadow->getConstructedBaseClassShadowDecl()));
7452 else
7453 assert(DNominatedBase == DConstructedBase);
7454
7455 // [class.inhctor.init]p2:
7456 // If the constructor was inherited from multiple base class subobjects
7457 // of type B, the program is ill-formed.
7458 if (!ConstructedBase) {
7459 ConstructedBase = DConstructedBase;
7460 ConstructedBaseIntroducer = D->getIntroducer();
7461 } else if (ConstructedBase != DConstructedBase &&
7462 !Shadow->isInvalidDecl()) {
7463 if (!DiagnosedMultipleConstructedBases) {
7464 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7465 << Shadow->getTargetDecl();
7466 S.Diag(ConstructedBaseIntroducer->getLocation(),
7467 diag::note_ambiguous_inherited_constructor_using)
7468 << ConstructedBase;
7469 DiagnosedMultipleConstructedBases = true;
7470 }
7471 S.Diag(D->getIntroducer()->getLocation(),
7472 diag::note_ambiguous_inherited_constructor_using)
7473 << DConstructedBase;
7474 }
7475 }
7476
7477 if (DiagnosedMultipleConstructedBases)
7478 Shadow->setInvalidDecl();
7479 }
7480
7481 /// Find the constructor to use for inherited construction of a base class,
7482 /// and whether that base class constructor inherits the constructor from a
7483 /// virtual base class (in which case it won't actually invoke it).
7484 std::pair<CXXConstructorDecl *, bool>
7486 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7487 if (It == InheritedFromBases.end())
7488 return std::make_pair(nullptr, false);
7489
7490 // This is an intermediary class.
7491 if (It->second)
7492 return std::make_pair(
7493 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7494 It->second->constructsVirtualBase());
7495
7496 // This is the base class from which the constructor was inherited.
7497 return std::make_pair(Ctor, false);
7498 }
7499};
7500
7501/// Is the special member function which would be selected to perform the
7502/// specified operation on the specified class type a constexpr constructor?
7504 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7505 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7506 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7507 // Suppress duplicate constraint checking here, in case a constraint check
7508 // caused us to decide to do this. Any truely recursive checks will get
7509 // caught during these checks anyway.
7511
7512 // If we're inheriting a constructor, see if we need to call it for this base
7513 // class.
7514 if (InheritedCtor) {
7516 auto BaseCtor =
7517 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7518 if (BaseCtor)
7519 return BaseCtor->isConstexpr();
7520 }
7521
7523 return ClassDecl->hasConstexprDefaultConstructor();
7525 return ClassDecl->hasConstexprDestructor();
7526
7528 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7529 if (!SMOR.getMethod())
7530 // A constructor we wouldn't select can't be "involved in initializing"
7531 // anything.
7532 return true;
7533 return SMOR.getMethod()->isConstexpr();
7534}
7535
7536/// Determine whether the specified special member function would be constexpr
7537/// if it were implicitly defined.
7539 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7540 CXXConstructorDecl *InheritedCtor = nullptr,
7541 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7542 if (!S.getLangOpts().CPlusPlus11)
7543 return false;
7544
7545 // C++11 [dcl.constexpr]p4:
7546 // In the definition of a constexpr constructor [...]
7547 bool Ctor = true;
7548 switch (CSM) {
7550 if (Inherited)
7551 break;
7552 // Since default constructor lookup is essentially trivial (and cannot
7553 // involve, for instance, template instantiation), we compute whether a
7554 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7555 //
7556 // This is important for performance; we need to know whether the default
7557 // constructor is constexpr to determine whether the type is a literal type.
7558 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7559
7562 // For copy or move constructors, we need to perform overload resolution.
7563 break;
7564
7567 if (!S.getLangOpts().CPlusPlus14)
7568 return false;
7569 // In C++1y, we need to perform overload resolution.
7570 Ctor = false;
7571 break;
7572
7574 return ClassDecl->defaultedDestructorIsConstexpr();
7575
7577 return false;
7578 }
7579
7580 // -- if the class is a non-empty union, or for each non-empty anonymous
7581 // union member of a non-union class, exactly one non-static data member
7582 // shall be initialized; [DR1359]
7583 //
7584 // If we squint, this is guaranteed, since exactly one non-static data member
7585 // will be initialized (if the constructor isn't deleted), we just don't know
7586 // which one.
7587 if (Ctor && ClassDecl->isUnion())
7589 ? ClassDecl->hasInClassInitializer() ||
7590 !ClassDecl->hasVariantMembers()
7591 : true;
7592
7593 // -- the class shall not have any virtual base classes;
7594 if (Ctor && ClassDecl->getNumVBases())
7595 return false;
7596
7597 // C++1y [class.copy]p26:
7598 // -- [the class] is a literal type, and
7599 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7600 return false;
7601
7602 // -- every constructor involved in initializing [...] base class
7603 // sub-objects shall be a constexpr constructor;
7604 // -- the assignment operator selected to copy/move each direct base
7605 // class is a constexpr function, and
7606 if (!S.getLangOpts().CPlusPlus23) {
7607 for (const auto &B : ClassDecl->bases()) {
7608 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7609 if (!BaseClassDecl)
7610 continue;
7611 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7612 InheritedCtor, Inherited))
7613 return false;
7614 }
7615 }
7616
7617 // -- every constructor involved in initializing non-static data members
7618 // [...] shall be a constexpr constructor;
7619 // -- every non-static data member and base class sub-object shall be
7620 // initialized
7621 // -- for each non-static data member of X that is of class type (or array
7622 // thereof), the assignment operator selected to copy/move that member is
7623 // a constexpr function
7624 if (!S.getLangOpts().CPlusPlus23) {
7625 for (const auto *F : ClassDecl->fields()) {
7626 if (F->isInvalidDecl())
7627 continue;
7629 F->hasInClassInitializer())
7630 continue;
7631 QualType BaseType = S.Context.getBaseElementType(F->getType());
7632 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7633 CXXRecordDecl *FieldRecDecl =
7634 cast<CXXRecordDecl>(RecordTy->getOriginalDecl())
7635 ->getDefinitionOrSelf();
7636 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7637 BaseType.getCVRQualifiers(),
7638 ConstArg && !F->isMutable()))
7639 return false;
7640 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7641 return false;
7642 }
7643 }
7644 }
7645
7646 // All OK, it's constexpr!
7647 return true;
7648}
7649
7650namespace {
7651/// RAII object to register a defaulted function as having its exception
7652/// specification computed.
7653struct ComputingExceptionSpec {
7654 Sema &S;
7655
7656 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7657 : S(S) {
7658 Sema::CodeSynthesisContext Ctx;
7660 Ctx.PointOfInstantiation = Loc;
7661 Ctx.Entity = FD;
7663 }
7664 ~ComputingExceptionSpec() {
7666 }
7667};
7668}
7669
7670static Sema::ImplicitExceptionSpecification
7671ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7672 CXXMethodDecl *MD,
7674 Sema::InheritedConstructorInfo *ICI);
7675
7676static Sema::ImplicitExceptionSpecification
7677ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7678 FunctionDecl *FD,
7680
7681static Sema::ImplicitExceptionSpecification
7683 auto DFK = S.getDefaultedFunctionKind(FD);
7684 if (DFK.isSpecialMember())
7686 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7687 if (DFK.isComparison())
7689 DFK.asComparison());
7690
7691 auto *CD = cast<CXXConstructorDecl>(FD);
7692 assert(CD->getInheritedConstructor() &&
7693 "only defaulted functions and inherited constructors have implicit "
7694 "exception specs");
7696 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7699}
7700
7702 CXXMethodDecl *MD) {
7704
7705 // Build an exception specification pointing back at this member.
7707 EPI.ExceptionSpec.SourceDecl = MD;
7708
7709 // Set the calling convention to the default for C++ instance methods.
7711 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7712 /*IsCXXMethod=*/true));
7713 return EPI;
7714}
7715
7717 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7719 return;
7720
7721 // Evaluate the exception specification.
7722 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7723 auto ESI = IES.getExceptionSpec();
7724
7725 // Update the type of the special member to use it.
7726 UpdateExceptionSpec(FD, ESI);
7727}
7728
7730 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7731
7733 if (!DefKind) {
7734 assert(FD->getDeclContext()->isDependentContext());
7735 return;
7736 }
7737
7738 if (DefKind.isComparison()) {
7739 auto PT = FD->getParamDecl(0)->getType();
7740 if (const CXXRecordDecl *RD =
7741 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7742 for (FieldDecl *Field : RD->fields()) {
7743 UnusedPrivateFields.remove(Field);
7744 }
7745 }
7746 }
7747
7748 if (DefKind.isSpecialMember()
7750 DefKind.asSpecialMember(),
7751 FD->getDefaultLoc())
7753 FD->setInvalidDecl();
7754}
7755
7758 SourceLocation DefaultLoc) {
7759 CXXRecordDecl *RD = MD->getParent();
7760
7762 "not an explicitly-defaulted special member");
7763
7764 // Defer all checking for special members of a dependent type.
7765 if (RD->isDependentType())
7766 return false;
7767
7768 // Whether this was the first-declared instance of the constructor.
7769 // This affects whether we implicitly add an exception spec and constexpr.
7770 bool First = MD == MD->getCanonicalDecl();
7771
7772 bool HadError = false;
7773
7774 // C++11 [dcl.fct.def.default]p1:
7775 // A function that is explicitly defaulted shall
7776 // -- be a special member function [...] (checked elsewhere),
7777 // -- have the same type (except for ref-qualifiers, and except that a
7778 // copy operation can take a non-const reference) as an implicit
7779 // declaration, and
7780 // -- not have default arguments.
7781 // C++2a changes the second bullet to instead delete the function if it's
7782 // defaulted on its first declaration, unless it's "an assignment operator,
7783 // and its return type differs or its parameter type is not a reference".
7784 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7785 bool ShouldDeleteForTypeMismatch = false;
7786 unsigned ExpectedParams = 1;
7789 ExpectedParams = 0;
7790 if (MD->getNumExplicitParams() != ExpectedParams) {
7791 // This checks for default arguments: a copy or move constructor with a
7792 // default argument is classified as a default constructor, and assignment
7793 // operations and destructors can't have default arguments.
7794 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7795 << CSM << MD->getSourceRange();
7796 HadError = true;
7797 } else if (MD->isVariadic()) {
7798 if (DeleteOnTypeMismatch)
7799 ShouldDeleteForTypeMismatch = true;
7800 else {
7801 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7802 << CSM << MD->getSourceRange();
7803 HadError = true;
7804 }
7805 }
7806
7808
7809 bool CanHaveConstParam = false;
7811 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7813 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7814
7815 QualType ReturnType = Context.VoidTy;
7818 // Check for return type matching.
7819 ReturnType = Type->getReturnType();
7821
7822 QualType DeclType =
7824 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7825 DeclType = Context.getAddrSpaceQualType(
7826 DeclType, ThisType.getQualifiers().getAddressSpace());
7827 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7828
7829 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7830 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7832 << ExpectedReturnType;
7833 HadError = true;
7834 }
7835
7836 // A defaulted special member cannot have cv-qualifiers.
7837 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7838 if (DeleteOnTypeMismatch)
7839 ShouldDeleteForTypeMismatch = true;
7840 else {
7841 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7843 << getLangOpts().CPlusPlus14;
7844 HadError = true;
7845 }
7846 }
7847 // [C++23][dcl.fct.def.default]/p2.2
7848 // if F2 has an implicit object parameter of type “reference to C”,
7849 // F1 may be an explicit object member function whose explicit object
7850 // parameter is of (possibly different) type “reference to C”,
7851 // in which case the type of F1 would differ from the type of F2
7852 // in that the type of F1 has an additional parameter;
7853 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7854 ? MD->getParamDecl(0)->getType()
7855 : QualType();
7856 if (!ExplicitObjectParameter.isNull() &&
7857 (!ExplicitObjectParameter->isReferenceType() ||
7858 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7859 Context.getCanonicalTagType(RD)))) {
7860 if (DeleteOnTypeMismatch)
7861 ShouldDeleteForTypeMismatch = true;
7862 else {
7863 Diag(MD->getLocation(),
7864 diag::err_defaulted_special_member_explicit_object_mismatch)
7865 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7866 << MD->getSourceRange();
7867 HadError = true;
7868 }
7869 }
7870 }
7871
7872 // Check for parameter type matching.
7874 ExpectedParams
7875 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7876 : QualType();
7877 bool HasConstParam = false;
7878 if (ExpectedParams && ArgType->isReferenceType()) {
7879 // Argument must be reference to possibly-const T.
7880 QualType ReferentType = ArgType->getPointeeType();
7881 HasConstParam = ReferentType.isConstQualified();
7882
7883 if (ReferentType.isVolatileQualified()) {
7884 if (DeleteOnTypeMismatch)
7885 ShouldDeleteForTypeMismatch = true;
7886 else {
7887 Diag(MD->getLocation(),
7888 diag::err_defaulted_special_member_volatile_param)
7889 << CSM;
7890 HadError = true;
7891 }
7892 }
7893
7894 if (HasConstParam && !CanHaveConstParam) {
7895 if (DeleteOnTypeMismatch)
7896 ShouldDeleteForTypeMismatch = true;
7897 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7899 Diag(MD->getLocation(),
7900 diag::err_defaulted_special_member_copy_const_param)
7902 // FIXME: Explain why this special member can't be const.
7903 HadError = true;
7904 } else {
7905 Diag(MD->getLocation(),
7906 diag::err_defaulted_special_member_move_const_param)
7908 HadError = true;
7909 }
7910 }
7911 } else if (ExpectedParams) {
7912 // A copy assignment operator can take its argument by value, but a
7913 // defaulted one cannot.
7915 "unexpected non-ref argument");
7916 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7917 HadError = true;
7918 }
7919
7920 // C++11 [dcl.fct.def.default]p2:
7921 // An explicitly-defaulted function may be declared constexpr only if it
7922 // would have been implicitly declared as constexpr,
7923 // Do not apply this rule to members of class templates, since core issue 1358
7924 // makes such functions always instantiate to constexpr functions. For
7925 // functions which cannot be constexpr (for non-constructors in C++11 and for
7926 // destructors in C++14 and C++17), this is checked elsewhere.
7927 //
7928 // FIXME: This should not apply if the member is deleted.
7929 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7930 HasConstParam);
7931
7932 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7933 // If the instantiated template specialization of a constexpr function
7934 // template or member function of a class template would fail to satisfy
7935 // the requirements for a constexpr function or constexpr constructor, that
7936 // specialization is still a constexpr function or constexpr constructor,
7937 // even though a call to such a function cannot appear in a constant
7938 // expression.
7939 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7940 Constexpr = true;
7941
7942 if ((getLangOpts().CPlusPlus20 ||
7944 : isa<CXXConstructorDecl>(MD))) &&
7945 MD->isConstexpr() && !Constexpr &&
7947 if (!MD->isConsteval() && RD->getNumVBases()) {
7948 Diag(MD->getBeginLoc(),
7949 diag::err_incorrect_defaulted_constexpr_with_vb)
7950 << CSM;
7951 for (const auto &I : RD->vbases())
7952 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7953 } else {
7954 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7955 << CSM << MD->isConsteval();
7956 }
7957 HadError = true;
7958 // FIXME: Explain why the special member can't be constexpr.
7959 }
7960
7961 if (First) {
7962 // C++2a [dcl.fct.def.default]p3:
7963 // If a function is explicitly defaulted on its first declaration, it is
7964 // implicitly considered to be constexpr if the implicit declaration
7965 // would be.
7970
7971 if (!Type->hasExceptionSpec()) {
7972 // C++2a [except.spec]p3:
7973 // If a declaration of a function does not have a noexcept-specifier
7974 // [and] is defaulted on its first declaration, [...] the exception
7975 // specification is as specified below
7976 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7978 EPI.ExceptionSpec.SourceDecl = MD;
7979 MD->setType(
7980 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7981 }
7982 }
7983
7984 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7985 if (First) {
7986 SetDeclDeleted(MD, MD->getLocation());
7987 if (!inTemplateInstantiation() && !HadError) {
7988 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7989 if (ShouldDeleteForTypeMismatch) {
7990 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7991 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7992 /*Diagnose*/ true) &&
7993 DefaultLoc.isValid()) {
7994 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7995 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7996 }
7997 }
7998 if (ShouldDeleteForTypeMismatch && !HadError) {
7999 Diag(MD->getLocation(),
8000 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8001 << CSM;
8002 }
8003 } else {
8004 // C++11 [dcl.fct.def.default]p4:
8005 // [For a] user-provided explicitly-defaulted function [...] if such a
8006 // function is implicitly defined as deleted, the program is ill-formed.
8007 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8008 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8009 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8010 HadError = true;
8011 }
8012 }
8013
8014 return HadError;
8015}
8016
8017namespace {
8018/// Helper class for building and checking a defaulted comparison.
8019///
8020/// Defaulted functions are built in two phases:
8021///
8022/// * First, the set of operations that the function will perform are
8023/// identified, and some of them are checked. If any of the checked
8024/// operations is invalid in certain ways, the comparison function is
8025/// defined as deleted and no body is built.
8026/// * Then, if the function is not defined as deleted, the body is built.
8027///
8028/// This is accomplished by performing two visitation steps over the eventual
8029/// body of the function.
8030template<typename Derived, typename ResultList, typename Result,
8031 typename Subobject>
8032class DefaultedComparisonVisitor {
8033public:
8034 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8035
8036 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8037 DefaultedComparisonKind DCK)
8038 : S(S), RD(RD), FD(FD), DCK(DCK) {
8039 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
8040 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8041 // UnresolvedSet to avoid this copy.
8042 Fns.assign(Info->getUnqualifiedLookups().begin(),
8043 Info->getUnqualifiedLookups().end());
8044 }
8045 }
8046
8047 ResultList visit() {
8048 // The type of an lvalue naming a parameter of this function.
8049 QualType ParamLvalType =
8051
8052 ResultList Results;
8053
8054 switch (DCK) {
8055 case DefaultedComparisonKind::None:
8056 llvm_unreachable("not a defaulted comparison");
8057
8058 case DefaultedComparisonKind::Equal:
8059 case DefaultedComparisonKind::ThreeWay:
8060 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8061 return Results;
8062
8063 case DefaultedComparisonKind::NotEqual:
8064 case DefaultedComparisonKind::Relational:
8065 Results.add(getDerived().visitExpandedSubobject(
8066 ParamLvalType, getDerived().getCompleteObject()));
8067 return Results;
8068 }
8069 llvm_unreachable("");
8070 }
8071
8072protected:
8073 Derived &getDerived() { return static_cast<Derived&>(*this); }
8074
8075 /// Visit the expanded list of subobjects of the given type, as specified in
8076 /// C++2a [class.compare.default].
8077 ///
8078 /// \return \c true if the ResultList object said we're done, \c false if not.
8079 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8080 Qualifiers Quals) {
8081 // C++2a [class.compare.default]p4:
8082 // The direct base class subobjects of C
8083 for (CXXBaseSpecifier &Base : Record->bases())
8084 if (Results.add(getDerived().visitSubobject(
8085 S.Context.getQualifiedType(Base.getType(), Quals),
8086 getDerived().getBase(&Base))))
8087 return true;
8088
8089 // followed by the non-static data members of C
8090 for (FieldDecl *Field : Record->fields()) {
8091 // C++23 [class.bit]p2:
8092 // Unnamed bit-fields are not members ...
8093 if (Field->isUnnamedBitField())
8094 continue;
8095 // Recursively expand anonymous structs.
8096 if (Field->isAnonymousStructOrUnion()) {
8097 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8098 Quals))
8099 return true;
8100 continue;
8101 }
8102
8103 // Figure out the type of an lvalue denoting this field.
8104 Qualifiers FieldQuals = Quals;
8105 if (Field->isMutable())
8106 FieldQuals.removeConst();
8107 QualType FieldType =
8108 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8109
8110 if (Results.add(getDerived().visitSubobject(
8111 FieldType, getDerived().getField(Field))))
8112 return true;
8113 }
8114
8115 // form a list of subobjects.
8116 return false;
8117 }
8118
8119 Result visitSubobject(QualType Type, Subobject Subobj) {
8120 // In that list, any subobject of array type is recursively expanded
8121 const ArrayType *AT = S.Context.getAsArrayType(Type);
8122 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8123 return getDerived().visitSubobjectArray(CAT->getElementType(),
8124 CAT->getSize(), Subobj);
8125 return getDerived().visitExpandedSubobject(Type, Subobj);
8126 }
8127
8128 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8129 Subobject Subobj) {
8130 return getDerived().visitSubobject(Type, Subobj);
8131 }
8132
8133protected:
8134 Sema &S;
8135 CXXRecordDecl *RD;
8136 FunctionDecl *FD;
8137 DefaultedComparisonKind DCK;
8138 UnresolvedSet<16> Fns;
8139};
8140
8141/// Information about a defaulted comparison, as determined by
8142/// DefaultedComparisonAnalyzer.
8143struct DefaultedComparisonInfo {
8144 bool Deleted = false;
8145 bool Constexpr = true;
8146 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8147
8148 static DefaultedComparisonInfo deleted() {
8149 DefaultedComparisonInfo Deleted;
8150 Deleted.Deleted = true;
8151 return Deleted;
8152 }
8153
8154 bool add(const DefaultedComparisonInfo &R) {
8155 Deleted |= R.Deleted;
8156 Constexpr &= R.Constexpr;
8157 Category = commonComparisonType(Category, R.Category);
8158 return Deleted;
8159 }
8160};
8161
8162/// An element in the expanded list of subobjects of a defaulted comparison, as
8163/// specified in C++2a [class.compare.default]p4.
8164struct DefaultedComparisonSubobject {
8165 enum { CompleteObject, Member, Base } Kind;
8166 NamedDecl *Decl;
8167 SourceLocation Loc;
8168};
8169
8170/// A visitor over the notional body of a defaulted comparison that determines
8171/// whether that body would be deleted or constexpr.
8172class DefaultedComparisonAnalyzer
8173 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8174 DefaultedComparisonInfo,
8175 DefaultedComparisonInfo,
8176 DefaultedComparisonSubobject> {
8177public:
8178 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8179
8180private:
8181 DiagnosticKind Diagnose;
8182
8183public:
8184 using Base = DefaultedComparisonVisitor;
8185 using Result = DefaultedComparisonInfo;
8186 using Subobject = DefaultedComparisonSubobject;
8187
8188 friend Base;
8189
8190 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8191 DefaultedComparisonKind DCK,
8192 DiagnosticKind Diagnose = NoDiagnostics)
8193 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8194
8195 Result visit() {
8196 if ((DCK == DefaultedComparisonKind::Equal ||
8197 DCK == DefaultedComparisonKind::ThreeWay) &&
8198 RD->hasVariantMembers()) {
8199 // C++2a [class.compare.default]p2 [P2002R0]:
8200 // A defaulted comparison operator function for class C is defined as
8201 // deleted if [...] C has variant members.
8202 if (Diagnose == ExplainDeleted) {
8203 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8204 << FD << RD->isUnion() << RD;
8205 }
8206 return Result::deleted();
8207 }
8208
8209 return Base::visit();
8210 }
8211
8212private:
8213 Subobject getCompleteObject() {
8214 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8215 }
8216
8217 Subobject getBase(CXXBaseSpecifier *Base) {
8218 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8219 Base->getBaseTypeLoc()};
8220 }
8221
8222 Subobject getField(FieldDecl *Field) {
8223 return Subobject{Subobject::Member, Field, Field->getLocation()};
8224 }
8225
8226 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8227 // C++2a [class.compare.default]p2 [P2002R0]:
8228 // A defaulted <=> or == operator function for class C is defined as
8229 // deleted if any non-static data member of C is of reference type
8230 if (Type->isReferenceType()) {
8231 if (Diagnose == ExplainDeleted) {
8232 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8233 << FD << RD;
8234 }
8235 return Result::deleted();
8236 }
8237
8238 // [...] Let xi be an lvalue denoting the ith element [...]
8239 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8240 Expr *Args[] = {&Xi, &Xi};
8241
8242 // All operators start by trying to apply that same operator recursively.
8244 assert(OO != OO_None && "not an overloaded operator!");
8245 return visitBinaryOperator(OO, Args, Subobj);
8246 }
8247
8248 Result
8249 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8250 Subobject Subobj,
8251 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8252 // Note that there is no need to consider rewritten candidates here if
8253 // we've already found there is no viable 'operator<=>' candidate (and are
8254 // considering synthesizing a '<=>' from '==' and '<').
8255 OverloadCandidateSet CandidateSet(
8257 OverloadCandidateSet::OperatorRewriteInfo(
8258 OO, FD->getLocation(),
8259 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8260
8261 /// C++2a [class.compare.default]p1 [P2002R0]:
8262 /// [...] the defaulted function itself is never a candidate for overload
8263 /// resolution [...]
8264 CandidateSet.exclude(FD);
8265
8266 if (Args[0]->getType()->isOverloadableType())
8267 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8268 else
8269 // FIXME: We determine whether this is a valid expression by checking to
8270 // see if there's a viable builtin operator candidate for it. That isn't
8271 // really what the rules ask us to do, but should give the right results.
8272 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8273
8274 Result R;
8275
8277 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8278 case OR_Success: {
8279 // C++2a [class.compare.secondary]p2 [P2002R0]:
8280 // The operator function [...] is defined as deleted if [...] the
8281 // candidate selected by overload resolution is not a rewritten
8282 // candidate.
8283 if ((DCK == DefaultedComparisonKind::NotEqual ||
8284 DCK == DefaultedComparisonKind::Relational) &&
8285 !Best->RewriteKind) {
8286 if (Diagnose == ExplainDeleted) {
8287 if (Best->Function) {
8288 S.Diag(Best->Function->getLocation(),
8289 diag::note_defaulted_comparison_not_rewritten_callee)
8290 << FD;
8291 } else {
8292 assert(Best->Conversions.size() == 2 &&
8293 Best->Conversions[0].isUserDefined() &&
8294 "non-user-defined conversion from class to built-in "
8295 "comparison");
8296 S.Diag(Best->Conversions[0]
8297 .UserDefined.FoundConversionFunction.getDecl()
8298 ->getLocation(),
8299 diag::note_defaulted_comparison_not_rewritten_conversion)
8300 << FD;
8301 }
8302 }
8303 return Result::deleted();
8304 }
8305
8306 // Throughout C++2a [class.compare]: if overload resolution does not
8307 // result in a usable function, the candidate function is defined as
8308 // deleted. This requires that we selected an accessible function.
8309 //
8310 // Note that this only considers the access of the function when named
8311 // within the type of the subobject, and not the access path for any
8312 // derived-to-base conversion.
8313 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8314 if (ArgClass && Best->FoundDecl.getDecl() &&
8315 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8316 QualType ObjectType = Subobj.Kind == Subobject::Member
8317 ? Args[0]->getType()
8320 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8321 Diagnose == ExplainDeleted
8322 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8323 << FD << Subobj.Kind << Subobj.Decl
8324 : S.PDiag()))
8325 return Result::deleted();
8326 }
8327
8328 bool NeedsDeducing =
8329 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8330
8331 if (FunctionDecl *BestFD = Best->Function) {
8332 // C++2a [class.compare.default]p3 [P2002R0]:
8333 // A defaulted comparison function is constexpr-compatible if
8334 // [...] no overlod resolution performed [...] results in a
8335 // non-constexpr function.
8336 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8337 // If it's not constexpr, explain why not.
8338 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8339 if (Subobj.Kind != Subobject::CompleteObject)
8340 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8341 << Subobj.Kind << Subobj.Decl;
8342 S.Diag(BestFD->getLocation(),
8343 diag::note_defaulted_comparison_not_constexpr_here);
8344 // Bail out after explaining; we don't want any more notes.
8345 return Result::deleted();
8346 }
8347 R.Constexpr &= BestFD->isConstexpr();
8348
8349 if (NeedsDeducing) {
8350 // If any callee has an undeduced return type, deduce it now.
8351 // FIXME: It's not clear how a failure here should be handled. For
8352 // now, we produce an eager diagnostic, because that is forward
8353 // compatible with most (all?) other reasonable options.
8354 if (BestFD->getReturnType()->isUndeducedType() &&
8355 S.DeduceReturnType(BestFD, FD->getLocation(),
8356 /*Diagnose=*/false)) {
8357 // Don't produce a duplicate error when asked to explain why the
8358 // comparison is deleted: we diagnosed that when initially checking
8359 // the defaulted operator.
8360 if (Diagnose == NoDiagnostics) {
8361 S.Diag(
8362 FD->getLocation(),
8363 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8364 << Subobj.Kind << Subobj.Decl;
8365 S.Diag(
8366 Subobj.Loc,
8367 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8368 << Subobj.Kind << Subobj.Decl;
8369 S.Diag(BestFD->getLocation(),
8370 diag::note_defaulted_comparison_cannot_deduce_callee)
8371 << Subobj.Kind << Subobj.Decl;
8372 }
8373 return Result::deleted();
8374 }
8376 BestFD->getCallResultType());
8377 if (!Info) {
8378 if (Diagnose == ExplainDeleted) {
8379 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8380 << Subobj.Kind << Subobj.Decl
8381 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8382 S.Diag(BestFD->getLocation(),
8383 diag::note_defaulted_comparison_cannot_deduce_callee)
8384 << Subobj.Kind << Subobj.Decl;
8385 }
8386 return Result::deleted();
8387 }
8388 R.Category = Info->Kind;
8389 }
8390 } else {
8391 QualType T = Best->BuiltinParamTypes[0];
8392 assert(T == Best->BuiltinParamTypes[1] &&
8393 "builtin comparison for different types?");
8394 assert(Best->BuiltinParamTypes[2].isNull() &&
8395 "invalid builtin comparison");
8396
8397 // FIXME: If the type we deduced is a vector type, we mark the
8398 // comparison as deleted because we don't yet support this.
8399 if (isa<VectorType>(T)) {
8400 if (Diagnose == ExplainDeleted) {
8401 S.Diag(FD->getLocation(),
8402 diag::note_defaulted_comparison_vector_types)
8403 << FD;
8404 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8405 }
8406 return Result::deleted();
8407 }
8408
8409 if (NeedsDeducing) {
8410 std::optional<ComparisonCategoryType> Cat =
8412 assert(Cat && "no category for builtin comparison?");
8413 R.Category = *Cat;
8414 }
8415 }
8416
8417 // Note that we might be rewriting to a different operator. That call is
8418 // not considered until we come to actually build the comparison function.
8419 break;
8420 }
8421
8422 case OR_Ambiguous:
8423 if (Diagnose == ExplainDeleted) {
8424 unsigned Kind = 0;
8425 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8426 Kind = OO == OO_EqualEqual ? 1 : 2;
8427 CandidateSet.NoteCandidates(
8429 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8430 << FD << Kind << Subobj.Kind << Subobj.Decl),
8431 S, OCD_AmbiguousCandidates, Args);
8432 }
8433 R = Result::deleted();
8434 break;
8435
8436 case OR_Deleted:
8437 if (Diagnose == ExplainDeleted) {
8438 if ((DCK == DefaultedComparisonKind::NotEqual ||
8439 DCK == DefaultedComparisonKind::Relational) &&
8440 !Best->RewriteKind) {
8441 S.Diag(Best->Function->getLocation(),
8442 diag::note_defaulted_comparison_not_rewritten_callee)
8443 << FD;
8444 } else {
8445 S.Diag(Subobj.Loc,
8446 diag::note_defaulted_comparison_calls_deleted)
8447 << FD << Subobj.Kind << Subobj.Decl;
8448 S.NoteDeletedFunction(Best->Function);
8449 }
8450 }
8451 R = Result::deleted();
8452 break;
8453
8455 // If there's no usable candidate, we're done unless we can rewrite a
8456 // '<=>' in terms of '==' and '<'.
8457 if (OO == OO_Spaceship &&
8459 // For any kind of comparison category return type, we need a usable
8460 // '==' and a usable '<'.
8461 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8462 &CandidateSet)))
8463 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8464 break;
8465 }
8466
8467 if (Diagnose == ExplainDeleted) {
8468 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8469 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8470 << Subobj.Kind << Subobj.Decl;
8471
8472 // For a three-way comparison, list both the candidates for the
8473 // original operator and the candidates for the synthesized operator.
8474 if (SpaceshipCandidates) {
8475 SpaceshipCandidates->NoteCandidates(
8476 S, Args,
8477 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8478 Args, FD->getLocation()));
8479 S.Diag(Subobj.Loc,
8480 diag::note_defaulted_comparison_no_viable_function_synthesized)
8481 << (OO == OO_EqualEqual ? 0 : 1);
8482 }
8483
8484 CandidateSet.NoteCandidates(
8485 S, Args,
8486 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8487 FD->getLocation()));
8488 }
8489 R = Result::deleted();
8490 break;
8491 }
8492
8493 return R;
8494 }
8495};
8496
8497/// A list of statements.
8498struct StmtListResult {
8499 bool IsInvalid = false;
8500 llvm::SmallVector<Stmt*, 16> Stmts;
8501
8502 bool add(const StmtResult &S) {
8503 IsInvalid |= S.isInvalid();
8504 if (IsInvalid)
8505 return true;
8506 Stmts.push_back(S.get());
8507 return false;
8508 }
8509};
8510
8511/// A visitor over the notional body of a defaulted comparison that synthesizes
8512/// the actual body.
8513class DefaultedComparisonSynthesizer
8514 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8515 StmtListResult, StmtResult,
8516 std::pair<ExprResult, ExprResult>> {
8517 SourceLocation Loc;
8518 unsigned ArrayDepth = 0;
8519
8520public:
8521 using Base = DefaultedComparisonVisitor;
8522 using ExprPair = std::pair<ExprResult, ExprResult>;
8523
8524 friend Base;
8525
8526 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8527 DefaultedComparisonKind DCK,
8528 SourceLocation BodyLoc)
8529 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8530
8531 /// Build a suitable function body for this defaulted comparison operator.
8532 StmtResult build() {
8533 Sema::CompoundScopeRAII CompoundScope(S);
8534
8535 StmtListResult Stmts = visit();
8536 if (Stmts.IsInvalid)
8537 return StmtError();
8538
8539 ExprResult RetVal;
8540 switch (DCK) {
8541 case DefaultedComparisonKind::None:
8542 llvm_unreachable("not a defaulted comparison");
8543
8544 case DefaultedComparisonKind::Equal: {
8545 // C++2a [class.eq]p3:
8546 // [...] compar[e] the corresponding elements [...] until the first
8547 // index i where xi == yi yields [...] false. If no such index exists,
8548 // V is true. Otherwise, V is false.
8549 //
8550 // Join the comparisons with '&&'s and return the result. Use a right
8551 // fold (traversing the conditions right-to-left), because that
8552 // short-circuits more naturally.
8553 auto OldStmts = std::move(Stmts.Stmts);
8554 Stmts.Stmts.clear();
8555 ExprResult CmpSoFar;
8556 // Finish a particular comparison chain.
8557 auto FinishCmp = [&] {
8558 if (Expr *Prior = CmpSoFar.get()) {
8559 // Convert the last expression to 'return ...;'
8560 if (RetVal.isUnset() && Stmts.Stmts.empty())
8561 RetVal = CmpSoFar;
8562 // Convert any prior comparison to 'if (!(...)) return false;'
8563 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8564 return true;
8565 CmpSoFar = ExprResult();
8566 }
8567 return false;
8568 };
8569 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8570 Expr *E = dyn_cast<Expr>(EAsStmt);
8571 if (!E) {
8572 // Found an array comparison.
8573 if (FinishCmp() || Stmts.add(EAsStmt))
8574 return StmtError();
8575 continue;
8576 }
8577
8578 if (CmpSoFar.isUnset()) {
8579 CmpSoFar = E;
8580 continue;
8581 }
8582 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8583 if (CmpSoFar.isInvalid())
8584 return StmtError();
8585 }
8586 if (FinishCmp())
8587 return StmtError();
8588 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8589 // If no such index exists, V is true.
8590 if (RetVal.isUnset())
8591 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8592 break;
8593 }
8594
8595 case DefaultedComparisonKind::ThreeWay: {
8596 // Per C++2a [class.spaceship]p3, as a fallback add:
8597 // return static_cast<R>(std::strong_ordering::equal);
8598 QualType StrongOrdering = S.CheckComparisonCategoryType(
8599 ComparisonCategoryType::StrongOrdering, Loc,
8600 Sema::ComparisonCategoryUsage::DefaultedOperator);
8601 if (StrongOrdering.isNull())
8602 return StmtError();
8603 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8604 .getValueInfo(ComparisonCategoryResult::Equal)
8605 ->VD;
8606 RetVal = getDecl(EqualVD);
8607 if (RetVal.isInvalid())
8608 return StmtError();
8609 RetVal = buildStaticCastToR(RetVal.get());
8610 break;
8611 }
8612
8613 case DefaultedComparisonKind::NotEqual:
8614 case DefaultedComparisonKind::Relational:
8615 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8616 break;
8617 }
8618
8619 // Build the final return statement.
8620 if (RetVal.isInvalid())
8621 return StmtError();
8622 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8623 if (ReturnStmt.isInvalid())
8624 return StmtError();
8625 Stmts.Stmts.push_back(ReturnStmt.get());
8626
8627 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8628 }
8629
8630private:
8631 ExprResult getDecl(ValueDecl *VD) {
8632 return S.BuildDeclarationNameExpr(
8633 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8634 }
8635
8636 ExprResult getParam(unsigned I) {
8637 ParmVarDecl *PD = FD->getParamDecl(I);
8638 return getDecl(PD);
8639 }
8640
8641 ExprPair getCompleteObject() {
8642 unsigned Param = 0;
8643 ExprResult LHS;
8644 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8645 MD && MD->isImplicitObjectMemberFunction()) {
8646 // LHS is '*this'.
8647 LHS = S.ActOnCXXThis(Loc);
8648 if (!LHS.isInvalid())
8649 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8650 } else {
8651 LHS = getParam(Param++);
8652 }
8653 ExprResult RHS = getParam(Param++);
8654 assert(Param == FD->getNumParams());
8655 return {LHS, RHS};
8656 }
8657
8658 ExprPair getBase(CXXBaseSpecifier *Base) {
8659 ExprPair Obj = getCompleteObject();
8660 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8661 return {ExprError(), ExprError()};
8662 CXXCastPath Path = {Base};
8663 const auto CastToBase = [&](Expr *E) {
8664 QualType ToType = S.Context.getQualifiedType(
8665 Base->getType(), E->getType().getQualifiers());
8666 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8667 };
8668 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8669 }
8670
8671 ExprPair getField(FieldDecl *Field) {
8672 ExprPair Obj = getCompleteObject();
8673 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8674 return {ExprError(), ExprError()};
8675
8676 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8677 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8678 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8679 CXXScopeSpec(), Field, Found, NameInfo),
8680 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8681 CXXScopeSpec(), Field, Found, NameInfo)};
8682 }
8683
8684 // FIXME: When expanding a subobject, register a note in the code synthesis
8685 // stack to say which subobject we're comparing.
8686
8687 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8688 if (Cond.isInvalid())
8689 return StmtError();
8690
8691 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8692 if (NotCond.isInvalid())
8693 return StmtError();
8694
8695 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8696 assert(!False.isInvalid() && "should never fail");
8697 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8698 if (ReturnFalse.isInvalid())
8699 return StmtError();
8700
8701 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8702 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8703 Sema::ConditionKind::Boolean),
8704 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8705 }
8706
8707 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8708 ExprPair Subobj) {
8709 QualType SizeType = S.Context.getSizeType();
8710 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8711
8712 // Build 'size_t i$n = 0'.
8713 IdentifierInfo *IterationVarName = nullptr;
8714 {
8715 SmallString<8> Str;
8716 llvm::raw_svector_ostream OS(Str);
8717 OS << "i" << ArrayDepth;
8718 IterationVarName = &S.Context.Idents.get(OS.str());
8719 }
8720 VarDecl *IterationVar = VarDecl::Create(
8721 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8722 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8723 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8724 IterationVar->setInit(
8725 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8726 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8727
8728 auto IterRef = [&] {
8729 ExprResult Ref = S.BuildDeclarationNameExpr(
8730 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8731 IterationVar);
8732 assert(!Ref.isInvalid() && "can't reference our own variable?");
8733 return Ref.get();
8734 };
8735
8736 // Build 'i$n != Size'.
8737 ExprResult Cond = S.CreateBuiltinBinOp(
8738 Loc, BO_NE, IterRef(),
8739 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8740 assert(!Cond.isInvalid() && "should never fail");
8741
8742 // Build '++i$n'.
8743 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8744 assert(!Inc.isInvalid() && "should never fail");
8745
8746 // Build 'a[i$n]' and 'b[i$n]'.
8747 auto Index = [&](ExprResult E) {
8748 if (E.isInvalid())
8749 return ExprError();
8750 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8751 };
8752 Subobj.first = Index(Subobj.first);
8753 Subobj.second = Index(Subobj.second);
8754
8755 // Compare the array elements.
8756 ++ArrayDepth;
8757 StmtResult Substmt = visitSubobject(Type, Subobj);
8758 --ArrayDepth;
8759
8760 if (Substmt.isInvalid())
8761 return StmtError();
8762
8763 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8764 // For outer levels or for an 'operator<=>' we already have a suitable
8765 // statement that returns as necessary.
8766 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8767 assert(DCK == DefaultedComparisonKind::Equal &&
8768 "should have non-expression statement");
8769 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8770 if (Substmt.isInvalid())
8771 return StmtError();
8772 }
8773
8774 // Build 'for (...) ...'
8775 return S.ActOnForStmt(Loc, Loc, Init,
8776 S.ActOnCondition(nullptr, Loc, Cond.get(),
8777 Sema::ConditionKind::Boolean),
8778 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8779 Substmt.get());
8780 }
8781
8782 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8783 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8784 return StmtError();
8785
8788 ExprResult Op;
8789 if (Type->isOverloadableType())
8790 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8791 Obj.second.get(), /*PerformADL=*/true,
8792 /*AllowRewrittenCandidates=*/true, FD);
8793 else
8794 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8795 if (Op.isInvalid())
8796 return StmtError();
8797
8798 switch (DCK) {
8799 case DefaultedComparisonKind::None:
8800 llvm_unreachable("not a defaulted comparison");
8801
8802 case DefaultedComparisonKind::Equal:
8803 // Per C++2a [class.eq]p2, each comparison is individually contextually
8804 // converted to bool.
8805 Op = S.PerformContextuallyConvertToBool(Op.get());
8806 if (Op.isInvalid())
8807 return StmtError();
8808 return Op.get();
8809
8810 case DefaultedComparisonKind::ThreeWay: {
8811 // Per C++2a [class.spaceship]p3, form:
8812 // if (R cmp = static_cast<R>(op); cmp != 0)
8813 // return cmp;
8814 QualType R = FD->getReturnType();
8815 Op = buildStaticCastToR(Op.get());
8816 if (Op.isInvalid())
8817 return StmtError();
8818
8819 // R cmp = ...;
8820 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8821 VarDecl *VD =
8822 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8823 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8824 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8825 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8826
8827 // cmp != 0
8828 ExprResult VDRef = getDecl(VD);
8829 if (VDRef.isInvalid())
8830 return StmtError();
8831 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8832 Expr *Zero =
8833 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8835 if (VDRef.get()->getType()->isOverloadableType())
8836 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8837 true, FD);
8838 else
8839 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8840 if (Comp.isInvalid())
8841 return StmtError();
8842 Sema::ConditionResult Cond = S.ActOnCondition(
8843 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8844 if (Cond.isInvalid())
8845 return StmtError();
8846
8847 // return cmp;
8848 VDRef = getDecl(VD);
8849 if (VDRef.isInvalid())
8850 return StmtError();
8851 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8852 if (ReturnStmt.isInvalid())
8853 return StmtError();
8854
8855 // if (...)
8856 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8857 Loc, ReturnStmt.get(),
8858 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8859 }
8860
8861 case DefaultedComparisonKind::NotEqual:
8862 case DefaultedComparisonKind::Relational:
8863 // C++2a [class.compare.secondary]p2:
8864 // Otherwise, the operator function yields x @ y.
8865 return Op.get();
8866 }
8867 llvm_unreachable("");
8868 }
8869
8870 /// Build "static_cast<R>(E)".
8871 ExprResult buildStaticCastToR(Expr *E) {
8872 QualType R = FD->getReturnType();
8873 assert(!R->isUndeducedType() && "type should have been deduced already");
8874
8875 // Don't bother forming a no-op cast in the common case.
8876 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8877 return E;
8878 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8879 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8880 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8881 }
8882};
8883}
8884
8885/// Perform the unqualified lookups that might be needed to form a defaulted
8886/// comparison function for the given operator.
8888 UnresolvedSetImpl &Operators,
8890 auto Lookup = [&](OverloadedOperatorKind OO) {
8891 Self.LookupOverloadedOperatorName(OO, S, Operators);
8892 };
8893
8894 // Every defaulted operator looks up itself.
8895 Lookup(Op);
8896 // ... and the rewritten form of itself, if any.
8898 Lookup(ExtraOp);
8899
8900 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8901 // synthesize a three-way comparison from '<' and '=='. In a dependent
8902 // context, we also need to look up '==' in case we implicitly declare a
8903 // defaulted 'operator=='.
8904 if (Op == OO_Spaceship) {
8905 Lookup(OO_ExclaimEqual);
8906 Lookup(OO_Less);
8907 Lookup(OO_EqualEqual);
8908 }
8909}
8910
8913 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8914
8915 // Perform any unqualified lookups we're going to need to default this
8916 // function.
8917 if (S) {
8918 UnresolvedSet<32> Operators;
8919 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8920 FD->getOverloadedOperator());
8923 Context, Operators.pairs()));
8924 }
8925
8926 // C++2a [class.compare.default]p1:
8927 // A defaulted comparison operator function for some class C shall be a
8928 // non-template function declared in the member-specification of C that is
8929 // -- a non-static const non-volatile member of C having one parameter of
8930 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8931 // -- a friend of C having two parameters of type const C& or two
8932 // parameters of type C.
8933
8934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8935 bool IsMethod = isa<CXXMethodDecl>(FD);
8936 if (IsMethod) {
8937 auto *MD = cast<CXXMethodDecl>(FD);
8938 assert(!MD->isStatic() && "comparison function cannot be a static member");
8939
8940 if (MD->getRefQualifier() == RQ_RValue) {
8941 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8942
8943 // Remove the ref qualifier to recover.
8944 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8945 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8946 EPI.RefQualifier = RQ_None;
8947 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8948 FPT->getParamTypes(), EPI));
8949 }
8950
8951 // If we're out-of-class, this is the class we're comparing.
8952 if (!RD)
8953 RD = MD->getParent();
8954 QualType T = MD->getFunctionObjectParameterReferenceType();
8955 if (!T.getNonReferenceType().isConstQualified() &&
8956 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
8957 SourceLocation Loc, InsertLoc;
8958 if (MD->isExplicitObjectMemberFunction()) {
8959 Loc = MD->getParamDecl(0)->getBeginLoc();
8960 InsertLoc = getLocForEndOfToken(
8961 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8962 } else {
8963 Loc = MD->getLocation();
8964 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8965 InsertLoc = Loc.getRParenLoc();
8966 }
8967 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8968 // corresponding defaulted 'operator<=>' already.
8969 if (!MD->isImplicit()) {
8970 Diag(Loc, diag::err_defaulted_comparison_non_const)
8971 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8972 }
8973
8974 // Add the 'const' to the type to recover.
8975 if (MD->isExplicitObjectMemberFunction()) {
8976 assert(T->isLValueReferenceType());
8977 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
8978 T.getNonReferenceType().withConst()));
8979 } else {
8980 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8981 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8982 EPI.TypeQuals.addConst();
8983 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8984 FPT->getParamTypes(), EPI));
8985 }
8986 }
8987
8988 if (MD->isVolatile()) {
8989 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8990
8991 // Remove the 'volatile' from the type to recover.
8992 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8993 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8995 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8996 FPT->getParamTypes(), EPI));
8997 }
8998 }
8999
9000 if ((FD->getNumParams() -
9001 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9002 (IsMethod ? 1 : 2)) {
9003 // Let's not worry about using a variadic template pack here -- who would do
9004 // such a thing?
9005 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9006 << int(IsMethod) << int(DCK);
9007 return true;
9008 }
9009
9010 const ParmVarDecl *KnownParm = nullptr;
9011 for (const ParmVarDecl *Param : FD->parameters()) {
9012 QualType ParmTy = Param->getType();
9013 if (!KnownParm) {
9014 auto CTy = ParmTy;
9015 // Is it `T const &`?
9016 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9017 QualType ExpectedTy;
9018 if (RD)
9019 ExpectedTy = Context.getCanonicalTagType(RD);
9020 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9021 CTy = Ref->getPointeeType();
9022 if (RD)
9023 ExpectedTy.addConst();
9024 Ok = true;
9025 }
9026
9027 // Is T a class?
9028 if (RD) {
9029 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9030 } else {
9031 RD = CTy->getAsCXXRecordDecl();
9032 Ok &= RD != nullptr;
9033 }
9034
9035 if (Ok) {
9036 KnownParm = Param;
9037 } else {
9038 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9039 // corresponding defaulted 'operator<=>' already.
9040 if (!FD->isImplicit()) {
9041 if (RD) {
9042 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9043 QualType RefTy =
9044 Context.getLValueReferenceType(PlainTy.withConst());
9045 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9046 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9047 << Param->getSourceRange();
9048 } else {
9049 assert(!IsMethod && "should know expected type for method");
9050 Diag(FD->getLocation(),
9051 diag::err_defaulted_comparison_param_unknown)
9052 << int(DCK) << ParmTy << Param->getSourceRange();
9053 }
9054 }
9055 return true;
9056 }
9057 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9058 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9059 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9060 << ParmTy << Param->getSourceRange();
9061 return true;
9062 }
9063 }
9064
9065 assert(RD && "must have determined class");
9066 if (IsMethod) {
9067 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9068 // In-class, must be a friend decl.
9069 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9070 } else {
9071 // Out of class, require the defaulted comparison to be a friend (of a
9072 // complete type, per CWG2547).
9073 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9074 diag::err_defaulted_comparison_not_friend, int(DCK),
9075 int(1)))
9076 return true;
9077
9078 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9079 return declaresSameEntity(F->getFriendDecl(), FD);
9080 })) {
9081 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9082 << int(DCK) << int(0) << RD;
9083 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9084 return true;
9085 }
9086 }
9087
9088 // C++2a [class.eq]p1, [class.rel]p1:
9089 // A [defaulted comparison other than <=>] shall have a declared return
9090 // type bool.
9093 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9094 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9095 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9096 << FD->getReturnTypeSourceRange();
9097 return true;
9098 }
9099 // C++2a [class.spaceship]p2 [P2002R0]:
9100 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9101 // R shall not contain a placeholder type.
9102 if (QualType RT = FD->getDeclaredReturnType();
9104 RT->getContainedDeducedType() &&
9105 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9106 RT->getContainedAutoType()->isConstrained())) {
9107 Diag(FD->getLocation(),
9108 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9109 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9110 << FD->getReturnTypeSourceRange();
9111 return true;
9112 }
9113
9114 // For a defaulted function in a dependent class, defer all remaining checks
9115 // until instantiation.
9116 if (RD->isDependentType())
9117 return false;
9118
9119 // Determine whether the function should be defined as deleted.
9120 DefaultedComparisonInfo Info =
9121 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9122
9123 bool First = FD == FD->getCanonicalDecl();
9124
9125 if (!First) {
9126 if (Info.Deleted) {
9127 // C++11 [dcl.fct.def.default]p4:
9128 // [For a] user-provided explicitly-defaulted function [...] if such a
9129 // function is implicitly defined as deleted, the program is ill-formed.
9130 //
9131 // This is really just a consequence of the general rule that you can
9132 // only delete a function on its first declaration.
9133 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9134 << FD->isImplicit() << (int)DCK;
9135 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9136 DefaultedComparisonAnalyzer::ExplainDeleted)
9137 .visit();
9138 return true;
9139 }
9141 // C++20 [class.compare.default]p1:
9142 // [...] A definition of a comparison operator as defaulted that appears
9143 // in a class shall be the first declaration of that function.
9144 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9145 << (int)DCK;
9147 diag::note_previous_declaration);
9148 return true;
9149 }
9150 }
9151
9152 // If we want to delete the function, then do so; there's nothing else to
9153 // check in that case.
9154 if (Info.Deleted) {
9155 SetDeclDeleted(FD, FD->getLocation());
9156 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9157 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9158 << (int)DCK;
9159 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9160 DefaultedComparisonAnalyzer::ExplainDeleted)
9161 .visit();
9162 if (FD->getDefaultLoc().isValid())
9163 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9164 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9165 }
9166 return false;
9167 }
9168
9169 // C++2a [class.spaceship]p2:
9170 // The return type is deduced as the common comparison type of R0, R1, ...
9174 if (RetLoc.isInvalid())
9175 RetLoc = FD->getBeginLoc();
9176 // FIXME: Should we really care whether we have the complete type and the
9177 // 'enumerator' constants here? A forward declaration seems sufficient.
9179 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9180 if (Cat.isNull())
9181 return true;
9182 Context.adjustDeducedFunctionResultType(
9183 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9184 }
9185
9186 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9187 // An explicitly-defaulted function that is not defined as deleted may be
9188 // declared constexpr or consteval only if it is constexpr-compatible.
9189 // C++2a [class.compare.default]p3 [P2002R0]:
9190 // A defaulted comparison function is constexpr-compatible if it satisfies
9191 // the requirements for a constexpr function [...]
9192 // The only relevant requirements are that the parameter and return types are
9193 // literal types. The remaining conditions are checked by the analyzer.
9194 //
9195 // We support P2448R2 in language modes earlier than C++23 as an extension.
9196 // The concept of constexpr-compatible was removed.
9197 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9198 // A function explicitly defaulted on its first declaration is implicitly
9199 // inline, and is implicitly constexpr if it is constexpr-suitable.
9200 // C++23 [dcl.constexpr]p3
9201 // A function is constexpr-suitable if
9202 // - it is not a coroutine, and
9203 // - if the function is a constructor or destructor, its class does not
9204 // have any virtual base classes.
9205 if (FD->isConstexpr()) {
9206 if (!getLangOpts().CPlusPlus23 &&
9209 !Info.Constexpr) {
9210 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9211 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9212 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9213 DefaultedComparisonAnalyzer::ExplainConstexpr)
9214 .visit();
9215 }
9216 }
9217
9218 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9219 // If a constexpr-compatible function is explicitly defaulted on its first
9220 // declaration, it is implicitly considered to be constexpr.
9221 // FIXME: Only applying this to the first declaration seems problematic, as
9222 // simple reorderings can affect the meaning of the program.
9223 if (First && !FD->isConstexpr() && Info.Constexpr)
9225
9226 // C++2a [except.spec]p3:
9227 // If a declaration of a function does not have a noexcept-specifier
9228 // [and] is defaulted on its first declaration, [...] the exception
9229 // specification is as specified below
9230 if (FD->getExceptionSpecType() == EST_None) {
9231 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9232 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9234 EPI.ExceptionSpec.SourceDecl = FD;
9235 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9236 FPT->getParamTypes(), EPI));
9237 }
9238
9239 return false;
9240}
9241
9243 FunctionDecl *Spaceship) {
9246 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9247 Ctx.Entity = Spaceship;
9249
9250 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9251 EqualEqual->setImplicit();
9252
9254}
9255
9258 assert(FD->isDefaulted() && !FD->isDeleted() &&
9260 if (FD->willHaveBody() || FD->isInvalidDecl())
9261 return;
9262
9264
9265 // Add a context note for diagnostics produced after this point.
9266 Scope.addContextNote(UseLoc);
9267
9268 {
9269 // Build and set up the function body.
9270 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9271 // the type of the class being compared.
9272 auto PT = FD->getParamDecl(0)->getType();
9273 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9274 SourceLocation BodyLoc =
9275 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9276 StmtResult Body =
9277 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9278 if (Body.isInvalid()) {
9279 FD->setInvalidDecl();
9280 return;
9281 }
9282 FD->setBody(Body.get());
9283 FD->markUsed(Context);
9284 }
9285
9286 // The exception specification is needed because we are defining the
9287 // function. Note that this will reuse the body we just built.
9289
9291 L->CompletedImplicitDefinition(FD);
9292}
9293
9296 FunctionDecl *FD,
9298 ComputingExceptionSpec CES(S, FD, Loc);
9300
9301 if (FD->isInvalidDecl())
9302 return ExceptSpec;
9303
9304 // The common case is that we just defined the comparison function. In that
9305 // case, just look at whether the body can throw.
9306 if (FD->hasBody()) {
9307 ExceptSpec.CalledStmt(FD->getBody());
9308 } else {
9309 // Otherwise, build a body so we can check it. This should ideally only
9310 // happen when we're not actually marking the function referenced. (This is
9311 // only really important for efficiency: we don't want to build and throw
9312 // away bodies for comparison functions more than we strictly need to.)
9313
9314 // Pretend to synthesize the function body in an unevaluated context.
9315 // Note that we can't actually just go ahead and define the function here:
9316 // we are not permitted to mark its callees as referenced.
9320
9321 CXXRecordDecl *RD =
9323 ? FD->getDeclContext()
9324 : FD->getLexicalDeclContext());
9325 SourceLocation BodyLoc =
9326 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9327 StmtResult Body =
9328 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9329 if (!Body.isInvalid())
9330 ExceptSpec.CalledStmt(Body.get());
9331
9332 // FIXME: Can we hold onto this body and just transform it to potentially
9333 // evaluated when we're asked to define the function rather than rebuilding
9334 // it? Either that, or we should only build the bits of the body that we
9335 // need (the expressions, not the statements).
9336 }
9337
9338 return ExceptSpec;
9339}
9340
9342 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9344
9345 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9347
9348 // Perform any deferred checking of exception specifications for virtual
9349 // destructors.
9350 for (auto &Check : Overriding)
9351 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9352
9353 // Perform any deferred checking of exception specifications for befriended
9354 // special members.
9355 for (auto &Check : Equivalent)
9356 CheckEquivalentExceptionSpec(Check.second, Check.first);
9357}
9358
9359namespace {
9360/// CRTP base class for visiting operations performed by a special member
9361/// function (or inherited constructor).
9362template<typename Derived>
9363struct SpecialMemberVisitor {
9364 Sema &S;
9365 CXXMethodDecl *MD;
9368
9369 // Properties of the special member, computed for convenience.
9370 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9371
9372 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9374 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9375 switch (CSM) {
9379 IsConstructor = true;
9380 break;
9383 IsAssignment = true;
9384 break;
9386 break;
9388 llvm_unreachable("invalid special member kind");
9389 }
9390
9391 if (MD->getNumExplicitParams()) {
9392 if (const ReferenceType *RT =
9393 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9394 ConstArg = RT->getPointeeType().isConstQualified();
9395 }
9396 }
9397
9398 Derived &getDerived() { return static_cast<Derived&>(*this); }
9399
9400 /// Is this a "move" special member?
9401 bool isMove() const {
9402 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9403 CSM == CXXSpecialMemberKind::MoveAssignment;
9404 }
9405
9406 /// Look up the corresponding special member in the given class.
9407 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9408 unsigned Quals, bool IsMutable) {
9409 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9410 ConstArg && !IsMutable);
9411 }
9412
9413 /// Look up the constructor for the specified base class to see if it's
9414 /// overridden due to this being an inherited constructor.
9415 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9416 if (!ICI)
9417 return {};
9418 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9419 auto *BaseCtor =
9420 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9421 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9422 return MD;
9423 return {};
9424 }
9425
9426 /// A base or member subobject.
9427 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9428
9429 /// Get the location to use for a subobject in diagnostics.
9430 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9431 // FIXME: For an indirect virtual base, the direct base leading to
9432 // the indirect virtual base would be a more useful choice.
9433 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9434 return B->getBaseTypeLoc();
9435 else
9436 return cast<FieldDecl *>(Subobj)->getLocation();
9437 }
9438
9439 enum BasesToVisit {
9440 /// Visit all non-virtual (direct) bases.
9441 VisitNonVirtualBases,
9442 /// Visit all direct bases, virtual or not.
9443 VisitDirectBases,
9444 /// Visit all non-virtual bases, and all virtual bases if the class
9445 /// is not abstract.
9446 VisitPotentiallyConstructedBases,
9447 /// Visit all direct or virtual bases.
9448 VisitAllBases
9449 };
9450
9451 // Visit the bases and members of the class.
9452 bool visit(BasesToVisit Bases) {
9453 CXXRecordDecl *RD = MD->getParent();
9454
9455 if (Bases == VisitPotentiallyConstructedBases)
9456 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9457
9458 for (auto &B : RD->bases())
9459 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9460 getDerived().visitBase(&B))
9461 return true;
9462
9463 if (Bases == VisitAllBases)
9464 for (auto &B : RD->vbases())
9465 if (getDerived().visitBase(&B))
9466 return true;
9467
9468 for (auto *F : RD->fields())
9469 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9470 getDerived().visitField(F))
9471 return true;
9472
9473 return false;
9474 }
9475};
9476}
9477
9478namespace {
9479struct SpecialMemberDeletionInfo
9480 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9481 bool Diagnose;
9482
9483 SourceLocation Loc;
9484
9485 bool AllFieldsAreConst;
9486
9487 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9489 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9490 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9491 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9492
9493 bool inUnion() const { return MD->getParent()->isUnion(); }
9494
9495 CXXSpecialMemberKind getEffectiveCSM() {
9496 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9497 }
9498
9499 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9500
9501 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9502
9503 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9504 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9505
9506 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9507 bool shouldDeleteForField(FieldDecl *FD);
9508 bool shouldDeleteForAllConstMembers();
9509
9510 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9511 unsigned Quals);
9512 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9513 Sema::SpecialMemberOverloadResult SMOR,
9514 bool IsDtorCallInCtor);
9515
9516 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9517};
9518}
9519
9520/// Is the given special member inaccessible when used on the given
9521/// sub-object.
9522bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9523 CXXMethodDecl *target) {
9524 /// If we're operating on a base class, the object type is the
9525 /// type of this special member.
9526 CanQualType objectTy;
9527 AccessSpecifier access = target->getAccess();
9528 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9529 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9530 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9531
9532 // If we're operating on a field, the object type is the type of the field.
9533 } else {
9534 objectTy = S.Context.getCanonicalTagType(target->getParent());
9535 }
9536
9538 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9539}
9540
9541/// Check whether we should delete a special member due to the implicit
9542/// definition containing a call to a special member of a subobject.
9543bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9544 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9545 bool IsDtorCallInCtor) {
9546 CXXMethodDecl *Decl = SMOR.getMethod();
9547 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9548
9549 int DiagKind = -1;
9550
9552 DiagKind = !Decl ? 0 : 1;
9554 DiagKind = 2;
9555 else if (!isAccessible(Subobj, Decl))
9556 DiagKind = 3;
9557 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9558 !Decl->isTrivial()) {
9559 // A member of a union must have a trivial corresponding special member.
9560 // As a weird special case, a destructor call from a union's constructor
9561 // must be accessible and non-deleted, but need not be trivial. Such a
9562 // destructor is never actually called, but is semantically checked as
9563 // if it were.
9564 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9565 // [class.default.ctor]p2:
9566 // A defaulted default constructor for class X is defined as deleted if
9567 // - X is a union that has a variant member with a non-trivial default
9568 // constructor and no variant member of X has a default member
9569 // initializer
9570 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9571 if (!RD->hasInClassInitializer())
9572 DiagKind = 4;
9573 } else {
9574 DiagKind = 4;
9575 }
9576 }
9577
9578 if (DiagKind == -1)
9579 return false;
9580
9581 if (Diagnose) {
9582 if (Field) {
9583 S.Diag(Field->getLocation(),
9584 diag::note_deleted_special_member_class_subobject)
9585 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9586 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9587 } else {
9588 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9589 S.Diag(Base->getBeginLoc(),
9590 diag::note_deleted_special_member_class_subobject)
9591 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9592 << Base->getType() << DiagKind << IsDtorCallInCtor
9593 << /*IsObjCPtr*/ false;
9594 }
9595
9596 if (DiagKind == 1)
9597 S.NoteDeletedFunction(Decl);
9598 // FIXME: Explain inaccessibility if DiagKind == 3.
9599 }
9600
9601 return true;
9602}
9603
9604/// Check whether we should delete a special member function due to having a
9605/// direct or virtual base class or non-static data member of class type M.
9606bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9607 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9608 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9609 bool IsMutable = Field && Field->isMutable();
9610
9611 // C++11 [class.ctor]p5:
9612 // -- any direct or virtual base class, or non-static data member with no
9613 // brace-or-equal-initializer, has class type M (or array thereof) and
9614 // either M has no default constructor or overload resolution as applied
9615 // to M's default constructor results in an ambiguity or in a function
9616 // that is deleted or inaccessible
9617 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9618 // -- a direct or virtual base class B that cannot be copied/moved because
9619 // overload resolution, as applied to B's corresponding special member,
9620 // results in an ambiguity or a function that is deleted or inaccessible
9621 // from the defaulted special member
9622 // C++11 [class.dtor]p5:
9623 // -- any direct or virtual base class [...] has a type with a destructor
9624 // that is deleted or inaccessible
9625 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9626 Field->hasInClassInitializer()) &&
9627 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9628 false))
9629 return true;
9630
9631 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9632 // -- any direct or virtual base class or non-static data member has a
9633 // type with a destructor that is deleted or inaccessible
9634 if (IsConstructor) {
9635 Sema::SpecialMemberOverloadResult SMOR =
9636 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9637 false, false, false, false);
9638 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9639 return true;
9640 }
9641
9642 return false;
9643}
9644
9645bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9646 FieldDecl *FD, QualType FieldType) {
9647 // The defaulted special functions are defined as deleted if this is a variant
9648 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9649 // type under ARC.
9650 if (!FieldType.hasNonTrivialObjCLifetime())
9651 return false;
9652
9653 // Don't make the defaulted default constructor defined as deleted if the
9654 // member has an in-class initializer.
9655 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9657 return false;
9658
9659 if (Diagnose) {
9660 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9661 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9662 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9663 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9664 }
9665
9666 return true;
9667}
9668
9669bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9670 const FieldDecl *FD) {
9671 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9672 // Copy/move constructors/assignment operators are deleted if the field has an
9673 // address-discriminated ptrauth qualifier.
9674 PointerAuthQualifier Q = FieldType.getPointerAuth();
9675
9676 if (!Q || !Q.isAddressDiscriminated())
9677 return false;
9678
9679 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9680 CSM == CXXSpecialMemberKind::Destructor)
9681 return false;
9682
9683 if (Diagnose) {
9684 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9685 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9686 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9687 << /*IsDtorCallInCtor*/ false << 2;
9688 }
9689
9690 return true;
9691}
9692
9693/// Check whether we should delete a special member function due to the class
9694/// having a particular direct or virtual base class.
9695bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9696 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9697 // If program is correct, BaseClass cannot be null, but if it is, the error
9698 // must be reported elsewhere.
9699 if (!BaseClass)
9700 return false;
9701 // If we have an inheriting constructor, check whether we're calling an
9702 // inherited constructor instead of a default constructor.
9703 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9704 if (auto *BaseCtor = SMOR.getMethod()) {
9705 // Note that we do not check access along this path; other than that,
9706 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9707 // FIXME: Check that the base has a usable destructor! Sink this into
9708 // shouldDeleteForClassSubobject.
9709 if (BaseCtor->isDeleted() && Diagnose) {
9710 S.Diag(Base->getBeginLoc(),
9711 diag::note_deleted_special_member_class_subobject)
9712 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9713 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9714 << /*IsObjCPtr*/ false;
9715 S.NoteDeletedFunction(BaseCtor);
9716 }
9717 return BaseCtor->isDeleted();
9718 }
9719 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9720}
9721
9722/// Check whether we should delete a special member function due to the class
9723/// having a particular non-static data member.
9724bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9725 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9726 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9727
9728 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9729 return true;
9730
9731 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9732 return true;
9733
9734 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9735 // For a default constructor, all references must be initialized in-class
9736 // and, if a union, it must have a non-const member.
9737 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9738 if (Diagnose)
9739 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9740 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9741 return true;
9742 }
9743 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9744 // data member of const-qualified type (or array thereof) with no
9745 // brace-or-equal-initializer is not const-default-constructible.
9746 if (!inUnion() && FieldType.isConstQualified() &&
9747 !FD->hasInClassInitializer() &&
9748 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9749 if (Diagnose)
9750 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9751 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9752 return true;
9753 }
9754
9755 if (inUnion() && !FieldType.isConstQualified())
9756 AllFieldsAreConst = false;
9757 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9758 // For a copy constructor, data members must not be of rvalue reference
9759 // type.
9760 if (FieldType->isRValueReferenceType()) {
9761 if (Diagnose)
9762 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9763 << MD->getParent() << FD << FieldType;
9764 return true;
9765 }
9766 } else if (IsAssignment) {
9767 // For an assignment operator, data members must not be of reference type.
9768 if (FieldType->isReferenceType()) {
9769 if (Diagnose)
9770 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9771 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9772 return true;
9773 }
9774 if (!FieldRecord && FieldType.isConstQualified()) {
9775 // C++11 [class.copy]p23:
9776 // -- a non-static data member of const non-class type (or array thereof)
9777 if (Diagnose)
9778 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9779 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9780 return true;
9781 }
9782 }
9783
9784 if (FieldRecord) {
9785 // Some additional restrictions exist on the variant members.
9786 if (!inUnion() && FieldRecord->isUnion() &&
9787 FieldRecord->isAnonymousStructOrUnion()) {
9788 bool AllVariantFieldsAreConst = true;
9789
9790 // FIXME: Handle anonymous unions declared within anonymous unions.
9791 for (auto *UI : FieldRecord->fields()) {
9792 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9793
9794 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9795 return true;
9796
9797 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9798 return true;
9799
9800 if (!UnionFieldType.isConstQualified())
9801 AllVariantFieldsAreConst = false;
9802
9803 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9804 if (UnionFieldRecord &&
9805 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9806 UnionFieldType.getCVRQualifiers()))
9807 return true;
9808 }
9809
9810 // At least one member in each anonymous union must be non-const
9811 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9812 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9813 if (Diagnose)
9814 S.Diag(FieldRecord->getLocation(),
9815 diag::note_deleted_default_ctor_all_const)
9816 << !!ICI << MD->getParent() << /*anonymous union*/1;
9817 return true;
9818 }
9819
9820 // Don't check the implicit member of the anonymous union type.
9821 // This is technically non-conformant but supported, and we have a
9822 // diagnostic for this elsewhere.
9823 return false;
9824 }
9825
9826 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9827 FieldType.getCVRQualifiers()))
9828 return true;
9829 }
9830
9831 return false;
9832}
9833
9834/// C++11 [class.ctor] p5:
9835/// A defaulted default constructor for a class X is defined as deleted if
9836/// X is a union and all of its variant members are of const-qualified type.
9837bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9838 // This is a silly definition, because it gives an empty union a deleted
9839 // default constructor. Don't do that.
9840 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9841 AllFieldsAreConst) {
9842 bool AnyFields = false;
9843 for (auto *F : MD->getParent()->fields())
9844 if ((AnyFields = !F->isUnnamedBitField()))
9845 break;
9846 if (!AnyFields)
9847 return false;
9848 if (Diagnose)
9849 S.Diag(MD->getParent()->getLocation(),
9850 diag::note_deleted_default_ctor_all_const)
9851 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9852 return true;
9853 }
9854 return false;
9855}
9856
9857/// Determine whether a defaulted special member function should be defined as
9858/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9859/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9863 bool Diagnose) {
9864 if (MD->isInvalidDecl())
9865 return false;
9866 CXXRecordDecl *RD = MD->getParent();
9867 assert(!RD->isDependentType() && "do deletion after instantiation");
9868 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9869 RD->isInvalidDecl())
9870 return false;
9871
9872 // C++11 [expr.lambda.prim]p19:
9873 // The closure type associated with a lambda-expression has a
9874 // deleted (8.4.3) default constructor and a deleted copy
9875 // assignment operator.
9876 // C++2a adds back these operators if the lambda has no lambda-capture.
9880 if (Diagnose)
9881 Diag(RD->getLocation(), diag::note_lambda_decl);
9882 return true;
9883 }
9884
9885 // For an anonymous struct or union, the copy and assignment special members
9886 // will never be used, so skip the check. For an anonymous union declared at
9887 // namespace scope, the constructor and destructor are used.
9890 return false;
9891
9892 // C++11 [class.copy]p7, p18:
9893 // If the class definition declares a move constructor or move assignment
9894 // operator, an implicitly declared copy constructor or copy assignment
9895 // operator is defined as deleted.
9898 CXXMethodDecl *UserDeclaredMove = nullptr;
9899
9900 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9901 // deletion of the corresponding copy operation, not both copy operations.
9902 // MSVC 2015 has adopted the standards conforming behavior.
9903 bool DeletesOnlyMatchingCopy =
9904 getLangOpts().MSVCCompat &&
9905 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9906
9908 (!DeletesOnlyMatchingCopy ||
9910 if (!Diagnose) return true;
9911
9912 // Find any user-declared move constructor.
9913 for (auto *I : RD->ctors()) {
9914 if (I->isMoveConstructor()) {
9915 UserDeclaredMove = I;
9916 break;
9917 }
9918 }
9919 assert(UserDeclaredMove);
9920 } else if (RD->hasUserDeclaredMoveAssignment() &&
9921 (!DeletesOnlyMatchingCopy ||
9923 if (!Diagnose) return true;
9924
9925 // Find any user-declared move assignment operator.
9926 for (auto *I : RD->methods()) {
9927 if (I->isMoveAssignmentOperator()) {
9928 UserDeclaredMove = I;
9929 break;
9930 }
9931 }
9932 assert(UserDeclaredMove);
9933 }
9934
9935 if (UserDeclaredMove) {
9936 Diag(UserDeclaredMove->getLocation(),
9937 diag::note_deleted_copy_user_declared_move)
9938 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9939 << UserDeclaredMove->isMoveAssignmentOperator();
9940 return true;
9941 }
9942 }
9943
9944 // Do access control from the special member function
9945 ContextRAII MethodContext(*this, MD);
9946
9947 // C++11 [class.dtor]p5:
9948 // -- for a virtual destructor, lookup of the non-array deallocation function
9949 // results in an ambiguity or in a function that is deleted or inaccessible
9950 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9951 FunctionDecl *OperatorDelete = nullptr;
9952 CanQualType DeallocType = Context.getCanonicalTagType(RD);
9953 DeclarationName Name =
9954 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9958 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9959 OperatorDelete, IDP,
9960 /*Diagnose=*/false)) {
9961 if (Diagnose)
9962 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9963 return true;
9964 }
9965 }
9966
9967 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9968
9969 // Per DR1611, do not consider virtual bases of constructors of abstract
9970 // classes, since we are not going to construct them.
9971 // Per DR1658, do not consider virtual bases of destructors of abstract
9972 // classes either.
9973 // Per DR2180, for assignment operators we only assign (and thus only
9974 // consider) direct bases.
9975 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9976 : SMI.VisitPotentiallyConstructedBases))
9977 return true;
9978
9979 if (SMI.shouldDeleteForAllConstMembers())
9980 return true;
9981
9982 if (getLangOpts().CUDA) {
9983 // We should delete the special member in CUDA mode if target inference
9984 // failed.
9985 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9986 // is treated as certain special member, which may not reflect what special
9987 // member MD really is. However inferTargetForImplicitSpecialMember
9988 // expects CSM to match MD, therefore recalculate CSM.
9989 assert(ICI || CSM == getSpecialMember(MD));
9990 auto RealCSM = CSM;
9991 if (ICI)
9992 RealCSM = getSpecialMember(MD);
9993
9994 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9995 SMI.ConstArg, Diagnose);
9996 }
9997
9998 return false;
9999}
10000
10003 assert(DFK && "not a defaultable function");
10004 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10005
10006 if (DFK.isSpecialMember()) {
10008 nullptr, /*Diagnose=*/true);
10009 } else {
10010 DefaultedComparisonAnalyzer(
10012 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10013 .visit();
10014 }
10015}
10016
10017/// Perform lookup for a special member of the specified kind, and determine
10018/// whether it is trivial. If the triviality can be determined without the
10019/// lookup, skip it. This is intended for use when determining whether a
10020/// special member of a containing object is trivial, and thus does not ever
10021/// perform overload resolution for default constructors.
10022///
10023/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10024/// member that was most likely to be intended to be trivial, if any.
10025///
10026/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10027/// determine whether the special member is trivial.
10029 CXXSpecialMemberKind CSM, unsigned Quals,
10030 bool ConstRHS, TrivialABIHandling TAH,
10031 CXXMethodDecl **Selected) {
10032 if (Selected)
10033 *Selected = nullptr;
10034
10035 switch (CSM) {
10037 llvm_unreachable("not a special member");
10038
10040 // C++11 [class.ctor]p5:
10041 // A default constructor is trivial if:
10042 // - all the [direct subobjects] have trivial default constructors
10043 //
10044 // Note, no overload resolution is performed in this case.
10046 return true;
10047
10048 if (Selected) {
10049 // If there's a default constructor which could have been trivial, dig it
10050 // out. Otherwise, if there's any user-provided default constructor, point
10051 // to that as an example of why there's not a trivial one.
10052 CXXConstructorDecl *DefCtor = nullptr;
10055 for (auto *CI : RD->ctors()) {
10056 if (!CI->isDefaultConstructor())
10057 continue;
10058 DefCtor = CI;
10059 if (!DefCtor->isUserProvided())
10060 break;
10061 }
10062
10063 *Selected = DefCtor;
10064 }
10065
10066 return false;
10067
10069 // C++11 [class.dtor]p5:
10070 // A destructor is trivial if:
10071 // - all the direct [subobjects] have trivial destructors
10072 if (RD->hasTrivialDestructor() ||
10075 return true;
10076
10077 if (Selected) {
10078 if (RD->needsImplicitDestructor())
10080 *Selected = RD->getDestructor();
10081 }
10082
10083 return false;
10084
10086 // C++11 [class.copy]p12:
10087 // A copy constructor is trivial if:
10088 // - the constructor selected to copy each direct [subobject] is trivial
10089 if (RD->hasTrivialCopyConstructor() ||
10092 if (Quals == Qualifiers::Const)
10093 // We must either select the trivial copy constructor or reach an
10094 // ambiguity; no need to actually perform overload resolution.
10095 return true;
10096 } else if (!Selected) {
10097 return false;
10098 }
10099 // In C++98, we are not supposed to perform overload resolution here, but we
10100 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10101 // cases like B as having a non-trivial copy constructor:
10102 // struct A { template<typename T> A(T&); };
10103 // struct B { mutable A a; };
10104 goto NeedOverloadResolution;
10105
10107 // C++11 [class.copy]p25:
10108 // A copy assignment operator is trivial if:
10109 // - the assignment operator selected to copy each direct [subobject] is
10110 // trivial
10111 if (RD->hasTrivialCopyAssignment()) {
10112 if (Quals == Qualifiers::Const)
10113 return true;
10114 } else if (!Selected) {
10115 return false;
10116 }
10117 // In C++98, we are not supposed to perform overload resolution here, but we
10118 // treat that as a language defect.
10119 goto NeedOverloadResolution;
10120
10123 NeedOverloadResolution:
10125 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10126
10127 // The standard doesn't describe how to behave if the lookup is ambiguous.
10128 // We treat it as not making the member non-trivial, just like the standard
10129 // mandates for the default constructor. This should rarely matter, because
10130 // the member will also be deleted.
10132 return true;
10133
10134 if (!SMOR.getMethod()) {
10135 assert(SMOR.getKind() ==
10137 return false;
10138 }
10139
10140 // We deliberately don't check if we found a deleted special member. We're
10141 // not supposed to!
10142 if (Selected)
10143 *Selected = SMOR.getMethod();
10144
10148 return SMOR.getMethod()->isTrivialForCall();
10149 return SMOR.getMethod()->isTrivial();
10150 }
10151
10152 llvm_unreachable("unknown special method kind");
10153}
10154
10156 for (auto *CI : RD->ctors())
10157 if (!CI->isImplicit())
10158 return CI;
10159
10160 // Look for constructor templates.
10162 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10163 if (CXXConstructorDecl *CD =
10164 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10165 return CD;
10166 }
10167
10168 return nullptr;
10169}
10170
10171/// The kind of subobject we are checking for triviality. The values of this
10172/// enumeration are used in diagnostics.
10174 /// The subobject is a base class.
10176 /// The subobject is a non-static data member.
10178 /// The object is actually the complete object.
10180};
10181
10182/// Check whether the special member selected for a given type would be trivial.
10184 QualType SubType, bool ConstRHS,
10187 TrivialABIHandling TAH, bool Diagnose) {
10188 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10189 if (!SubRD)
10190 return true;
10191
10192 CXXMethodDecl *Selected;
10193 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10194 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10195 return true;
10196
10197 if (Diagnose) {
10198 if (ConstRHS)
10199 SubType.addConst();
10200
10201 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10202 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10203 << Kind << SubType.getUnqualifiedType();
10205 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10206 } else if (!Selected)
10207 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10208 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10209 else if (Selected->isUserProvided()) {
10210 if (Kind == TSK_CompleteObject)
10211 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10212 << Kind << SubType.getUnqualifiedType() << CSM;
10213 else {
10214 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10215 << Kind << SubType.getUnqualifiedType() << CSM;
10216 S.Diag(Selected->getLocation(), diag::note_declared_at);
10217 }
10218 } else {
10219 if (Kind != TSK_CompleteObject)
10220 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10221 << Kind << SubType.getUnqualifiedType() << CSM;
10222
10223 // Explain why the defaulted or deleted special member isn't trivial.
10224 S.SpecialMemberIsTrivial(Selected, CSM,
10226 }
10227 }
10228
10229 return false;
10230}
10231
10232/// Check whether the members of a class type allow a special member to be
10233/// trivial.
10235 CXXSpecialMemberKind CSM, bool ConstArg,
10236 TrivialABIHandling TAH, bool Diagnose) {
10237 for (const auto *FI : RD->fields()) {
10238 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10239 continue;
10240
10241 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10242
10243 // Pretend anonymous struct or union members are members of this class.
10244 if (FI->isAnonymousStructOrUnion()) {
10245 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10246 CSM, ConstArg, TAH, Diagnose))
10247 return false;
10248 continue;
10249 }
10250
10251 // C++11 [class.ctor]p5:
10252 // A default constructor is trivial if [...]
10253 // -- no non-static data member of its class has a
10254 // brace-or-equal-initializer
10256 FI->hasInClassInitializer()) {
10257 if (Diagnose)
10258 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10259 << FI;
10260 return false;
10261 }
10262
10263 // Objective C ARC 4.3.5:
10264 // [...] nontrivally ownership-qualified types are [...] not trivially
10265 // default constructible, copy constructible, move constructible, copy
10266 // assignable, move assignable, or destructible [...]
10267 if (FieldType.hasNonTrivialObjCLifetime()) {
10268 if (Diagnose)
10269 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10270 << RD << FieldType.getObjCLifetime();
10271 return false;
10272 }
10273
10274 bool ConstRHS = ConstArg && !FI->isMutable();
10275 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10276 CSM, TSK_Field, TAH, Diagnose))
10277 return false;
10278 }
10279
10280 return true;
10281}
10282
10285 CanQualType Ty = Context.getCanonicalTagType(RD);
10286
10287 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10289 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10292 /*Diagnose*/ true);
10293}
10294
10296 TrivialABIHandling TAH, bool Diagnose) {
10297 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10298 "not special enough");
10299
10300 CXXRecordDecl *RD = MD->getParent();
10301
10302 bool ConstArg = false;
10303
10304 // C++11 [class.copy]p12, p25: [DR1593]
10305 // A [special member] is trivial if [...] its parameter-type-list is
10306 // equivalent to the parameter-type-list of an implicit declaration [...]
10307 switch (CSM) {
10310 // Trivial default constructors and destructors cannot have parameters.
10311 break;
10312
10315 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10316 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10317
10318 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10319 // if they are not user-provided and their parameter-type-list is equivalent
10320 // to the parameter-type-list of an implicit declaration. This maintains the
10321 // behavior before dr2171 was implemented.
10322 //
10323 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10324 // trivial, if they are not user-provided, regardless of the qualifiers on
10325 // the reference type.
10326 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10327 LangOptions::ClangABI::Ver14;
10328 if (!RT ||
10330 ClangABICompat14)) {
10331 if (Diagnose)
10332 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10333 << Param0->getSourceRange() << Param0->getType()
10334 << Context.getLValueReferenceType(
10335 Context.getCanonicalTagType(RD).withConst());
10336 return false;
10337 }
10338
10339 ConstArg = RT->getPointeeType().isConstQualified();
10340 break;
10341 }
10342
10345 // Trivial move operations always have non-cv-qualified parameters.
10346 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10347 const RValueReferenceType *RT =
10348 Param0->getType()->getAs<RValueReferenceType>();
10349 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10350 if (Diagnose)
10351 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10352 << Param0->getSourceRange() << Param0->getType()
10353 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10354 return false;
10355 }
10356 break;
10357 }
10358
10360 llvm_unreachable("not a special member");
10361 }
10362
10363 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10364 if (Diagnose)
10366 diag::note_nontrivial_default_arg)
10368 return false;
10369 }
10370 if (MD->isVariadic()) {
10371 if (Diagnose)
10372 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10373 return false;
10374 }
10375
10376 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10377 // A copy/move [constructor or assignment operator] is trivial if
10378 // -- the [member] selected to copy/move each direct base class subobject
10379 // is trivial
10380 //
10381 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10382 // A [default constructor or destructor] is trivial if
10383 // -- all the direct base classes have trivial [default constructors or
10384 // destructors]
10385 for (const auto &BI : RD->bases())
10386 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10387 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10388 return false;
10389
10390 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10391 // A copy/move [constructor or assignment operator] for a class X is
10392 // trivial if
10393 // -- for each non-static data member of X that is of class type (or array
10394 // thereof), the constructor selected to copy/move that member is
10395 // trivial
10396 //
10397 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10398 // A [default constructor or destructor] is trivial if
10399 // -- for all of the non-static data members of its class that are of class
10400 // type (or array thereof), each such class has a trivial [default
10401 // constructor or destructor]
10402 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10403 return false;
10404
10405 // C++11 [class.dtor]p5:
10406 // A destructor is trivial if [...]
10407 // -- the destructor is not virtual
10408 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10409 if (Diagnose)
10410 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10411 return false;
10412 }
10413
10414 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10415 // A [special member] for class X is trivial if [...]
10416 // -- class X has no virtual functions and no virtual base classes
10418 MD->getParent()->isDynamicClass()) {
10419 if (!Diagnose)
10420 return false;
10421
10422 if (RD->getNumVBases()) {
10423 // Check for virtual bases. We already know that the corresponding
10424 // member in all bases is trivial, so vbases must all be direct.
10425 CXXBaseSpecifier &BS = *RD->vbases_begin();
10426 assert(BS.isVirtual());
10427 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10428 return false;
10429 }
10430
10431 // Must have a virtual method.
10432 for (const auto *MI : RD->methods()) {
10433 if (MI->isVirtual()) {
10434 SourceLocation MLoc = MI->getBeginLoc();
10435 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10436 return false;
10437 }
10438 }
10439
10440 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10441 }
10442
10443 // Looks like it's trivial!
10444 return true;
10445}
10446
10447namespace {
10448struct FindHiddenVirtualMethod {
10449 Sema *S;
10451 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10452 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10453
10454private:
10455 /// Check whether any most overridden method from MD in Methods
10456 static bool CheckMostOverridenMethods(
10457 const CXXMethodDecl *MD,
10458 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10459 if (MD->size_overridden_methods() == 0)
10460 return Methods.count(MD->getCanonicalDecl());
10461 for (const CXXMethodDecl *O : MD->overridden_methods())
10462 if (CheckMostOverridenMethods(O, Methods))
10463 return true;
10464 return false;
10465 }
10466
10467public:
10468 /// Member lookup function that determines whether a given C++
10469 /// method overloads virtual methods in a base class without overriding any,
10470 /// to be used with CXXRecordDecl::lookupInBases().
10471 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10472 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10473 DeclarationName Name = Method->getDeclName();
10474 assert(Name.getNameKind() == DeclarationName::Identifier);
10475
10476 bool foundSameNameMethod = false;
10477 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10478 for (Path.Decls = BaseRecord->lookup(Name).begin();
10479 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10480 NamedDecl *D = *Path.Decls;
10481 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10482 MD = MD->getCanonicalDecl();
10483 foundSameNameMethod = true;
10484 // Interested only in hidden virtual methods.
10485 if (!MD->isVirtual())
10486 continue;
10487 // If the method we are checking overrides a method from its base
10488 // don't warn about the other overloaded methods. Clang deviates from
10489 // GCC by only diagnosing overloads of inherited virtual functions that
10490 // do not override any other virtual functions in the base. GCC's
10491 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10492 // function from a base class. These cases may be better served by a
10493 // warning (not specific to virtual functions) on call sites when the
10494 // call would select a different function from the base class, were it
10495 // visible.
10496 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10497 if (!S->IsOverload(Method, MD, false))
10498 return true;
10499 // Collect the overload only if its hidden.
10500 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10501 overloadedMethods.push_back(MD);
10502 }
10503 }
10504
10505 if (foundSameNameMethod)
10506 OverloadedMethods.append(overloadedMethods.begin(),
10507 overloadedMethods.end());
10508 return foundSameNameMethod;
10509 }
10510};
10511} // end anonymous namespace
10512
10513/// Add the most overridden methods from MD to Methods
10515 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10516 if (MD->size_overridden_methods() == 0)
10517 Methods.insert(MD->getCanonicalDecl());
10518 else
10519 for (const CXXMethodDecl *O : MD->overridden_methods())
10520 AddMostOverridenMethods(O, Methods);
10521}
10522
10524 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10525 if (!MD->getDeclName().isIdentifier())
10526 return;
10527
10528 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10529 /*bool RecordPaths=*/false,
10530 /*bool DetectVirtual=*/false);
10531 FindHiddenVirtualMethod FHVM;
10532 FHVM.Method = MD;
10533 FHVM.S = this;
10534
10535 // Keep the base methods that were overridden or introduced in the subclass
10536 // by 'using' in a set. A base method not in this set is hidden.
10537 CXXRecordDecl *DC = MD->getParent();
10539 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10540 NamedDecl *ND = *I;
10541 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10542 ND = shad->getTargetDecl();
10543 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10544 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10545 }
10546
10547 if (DC->lookupInBases(FHVM, Paths))
10548 OverloadedMethods = FHVM.OverloadedMethods;
10549}
10550
10552 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10553 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10554 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10556 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10557 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10558 Diag(overloadedMD->getLocation(), PD);
10559 }
10560}
10561
10563 if (MD->isInvalidDecl())
10564 return;
10565
10566 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10567 return;
10568
10569 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10570 FindHiddenVirtualMethods(MD, OverloadedMethods);
10571 if (!OverloadedMethods.empty()) {
10572 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10573 << MD << (OverloadedMethods.size() > 1);
10574
10575 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10576 }
10577}
10578
10580 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10581 // No diagnostics if this is a template instantiation.
10583 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10584 diag::ext_cannot_use_trivial_abi) << &RD;
10585 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10586 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10587 }
10588 RD.dropAttr<TrivialABIAttr>();
10589 };
10590
10591 // Ill-formed if the struct has virtual functions.
10592 if (RD.isPolymorphic()) {
10593 PrintDiagAndRemoveAttr(1);
10594 return;
10595 }
10596
10597 for (const auto &B : RD.bases()) {
10598 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10599 // virtual base.
10600 if (!B.getType()->isDependentType() &&
10601 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10602 PrintDiagAndRemoveAttr(2);
10603 return;
10604 }
10605
10606 if (B.isVirtual()) {
10607 PrintDiagAndRemoveAttr(3);
10608 return;
10609 }
10610 }
10611
10612 for (const auto *FD : RD.fields()) {
10613 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10614 // non-trivial for the purpose of calls.
10615 QualType FT = FD->getType();
10617 PrintDiagAndRemoveAttr(4);
10618 return;
10619 }
10620
10621 // Ill-formed if the field is an address-discriminated value.
10623 PrintDiagAndRemoveAttr(6);
10624 return;
10625 }
10626
10627 if (const auto *RT =
10628 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10629 if (!RT->isDependentType() &&
10630 !cast<CXXRecordDecl>(RT->getOriginalDecl()->getDefinitionOrSelf())
10631 ->canPassInRegisters()) {
10632 PrintDiagAndRemoveAttr(5);
10633 return;
10634 }
10635 }
10636
10638 return;
10639
10640 // Ill-formed if the copy and move constructors are deleted.
10641 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10642 // If the type is dependent, then assume it might have
10643 // implicit copy or move ctor because we won't know yet at this point.
10644 if (RD.isDependentType())
10645 return true;
10648 return true;
10651 return true;
10652 for (const CXXConstructorDecl *CD : RD.ctors())
10653 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10654 return true;
10655 return false;
10656 };
10657
10658 if (!HasNonDeletedCopyOrMoveConstructor()) {
10659 PrintDiagAndRemoveAttr(0);
10660 return;
10661 }
10662}
10663
10665 CXXRecordDecl &RD) {
10666 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10667 diag::err_incomplete_type_vtable_pointer_auth))
10668 return;
10669
10670 const CXXRecordDecl *PrimaryBase = &RD;
10671 if (PrimaryBase->hasAnyDependentBases())
10672 return;
10673
10674 while (1) {
10675 assert(PrimaryBase);
10676 const CXXRecordDecl *Base = nullptr;
10677 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10678 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10679 continue;
10680 Base = BasePtr.getType()->getAsCXXRecordDecl();
10681 break;
10682 }
10683 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10684 break;
10685 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10686 diag::err_non_top_level_vtable_pointer_auth)
10687 << &RD << Base;
10688 PrimaryBase = Base;
10689 }
10690
10691 if (!RD.isPolymorphic())
10692 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10693 diag::err_non_polymorphic_vtable_pointer_auth)
10694 << &RD;
10695}
10696
10699 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10700 if (!TagDecl)
10701 return;
10702
10704
10705 for (const ParsedAttr &AL : AttrList) {
10706 if (AL.getKind() != ParsedAttr::AT_Visibility)
10707 continue;
10708 AL.setInvalid();
10709 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10710 }
10711
10712 ActOnFields(S, RLoc, TagDecl,
10714 // strict aliasing violation!
10715 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10716 FieldCollector->getCurNumFields()),
10717 LBrac, RBrac, AttrList);
10718
10720}
10721
10722/// Find the equality comparison functions that should be implicitly declared
10723/// in a given class definition, per C++2a [class.compare.default]p3.
10725 ASTContext &Ctx, CXXRecordDecl *RD,
10727 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10728 if (!RD->lookup(EqEq).empty())
10729 // Member operator== explicitly declared: no implicit operator==s.
10730 return;
10731
10732 // Traverse friends looking for an '==' or a '<=>'.
10733 for (FriendDecl *Friend : RD->friends()) {
10734 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10735 if (!FD) continue;
10736
10737 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10738 // Friend operator== explicitly declared: no implicit operator==s.
10739 Spaceships.clear();
10740 return;
10741 }
10742
10743 if (FD->getOverloadedOperator() == OO_Spaceship &&
10745 Spaceships.push_back(FD);
10746 }
10747
10748 // Look for members named 'operator<=>'.
10749 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10750 for (NamedDecl *ND : RD->lookup(Cmp)) {
10751 // Note that we could find a non-function here (either a function template
10752 // or a using-declaration). Neither case results in an implicit
10753 // 'operator=='.
10754 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10755 if (FD->isExplicitlyDefaulted())
10756 Spaceships.push_back(FD);
10757 }
10758}
10759
10761 // Don't add implicit special members to templated classes.
10762 // FIXME: This means unqualified lookups for 'operator=' within a class
10763 // template don't work properly.
10764 if (!ClassDecl->isDependentType()) {
10765 if (ClassDecl->needsImplicitDefaultConstructor()) {
10766 ++getASTContext().NumImplicitDefaultConstructors;
10767
10768 if (ClassDecl->hasInheritedConstructor())
10770 }
10771
10772 if (ClassDecl->needsImplicitCopyConstructor()) {
10773 ++getASTContext().NumImplicitCopyConstructors;
10774
10775 // If the properties or semantics of the copy constructor couldn't be
10776 // determined while the class was being declared, force a declaration
10777 // of it now.
10779 ClassDecl->hasInheritedConstructor())
10781 // For the MS ABI we need to know whether the copy ctor is deleted. A
10782 // prerequisite for deleting the implicit copy ctor is that the class has
10783 // a move ctor or move assignment that is either user-declared or whose
10784 // semantics are inherited from a subobject. FIXME: We should provide a
10785 // more direct way for CodeGen to ask whether the constructor was deleted.
10786 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10787 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10789 ClassDecl->hasUserDeclaredMoveAssignment() ||
10792 }
10793
10794 if (getLangOpts().CPlusPlus11 &&
10795 ClassDecl->needsImplicitMoveConstructor()) {
10796 ++getASTContext().NumImplicitMoveConstructors;
10797
10799 ClassDecl->hasInheritedConstructor())
10801 }
10802
10803 if (ClassDecl->needsImplicitCopyAssignment()) {
10804 ++getASTContext().NumImplicitCopyAssignmentOperators;
10805
10806 // If we have a dynamic class, then the copy assignment operator may be
10807 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10808 // it shows up in the right place in the vtable and that we diagnose
10809 // problems with the implicit exception specification.
10810 if (ClassDecl->isDynamicClass() ||
10812 ClassDecl->hasInheritedAssignment())
10814 }
10815
10816 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10817 ++getASTContext().NumImplicitMoveAssignmentOperators;
10818
10819 // Likewise for the move assignment operator.
10820 if (ClassDecl->isDynamicClass() ||
10822 ClassDecl->hasInheritedAssignment())
10824 }
10825
10826 if (ClassDecl->needsImplicitDestructor()) {
10827 ++getASTContext().NumImplicitDestructors;
10828
10829 // If we have a dynamic class, then the destructor may be virtual, so we
10830 // have to declare the destructor immediately. This ensures that, e.g., it
10831 // shows up in the right place in the vtable and that we diagnose problems
10832 // with the implicit exception specification.
10833 if (ClassDecl->isDynamicClass() ||
10835 DeclareImplicitDestructor(ClassDecl);
10836 }
10837 }
10838
10839 // C++2a [class.compare.default]p3:
10840 // If the member-specification does not explicitly declare any member or
10841 // friend named operator==, an == operator function is declared implicitly
10842 // for each defaulted three-way comparison operator function defined in
10843 // the member-specification
10844 // FIXME: Consider doing this lazily.
10845 // We do this during the initial parse for a class template, not during
10846 // instantiation, so that we can handle unqualified lookups for 'operator=='
10847 // when parsing the template.
10849 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10851 DefaultedSpaceships);
10852 for (auto *FD : DefaultedSpaceships)
10853 DeclareImplicitEqualityComparison(ClassDecl, FD);
10854 }
10855}
10856
10857unsigned
10859 llvm::function_ref<Scope *()> EnterScope) {
10860 if (!D)
10861 return 0;
10863
10864 // In order to get name lookup right, reenter template scopes in order from
10865 // outermost to innermost.
10867 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10868
10869 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10870 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10871 ParameterLists.push_back(DD->getTemplateParameterList(i));
10872
10873 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10874 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10875 ParameterLists.push_back(FTD->getTemplateParameters());
10876 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10877 LookupDC = VD->getDeclContext();
10878
10880 ParameterLists.push_back(VTD->getTemplateParameters());
10881 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10882 ParameterLists.push_back(PSD->getTemplateParameters());
10883 }
10884 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10885 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10886 ParameterLists.push_back(TD->getTemplateParameterList(i));
10887
10888 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10890 ParameterLists.push_back(CTD->getTemplateParameters());
10891 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10892 ParameterLists.push_back(PSD->getTemplateParameters());
10893 }
10894 }
10895 // FIXME: Alias declarations and concepts.
10896
10897 unsigned Count = 0;
10898 Scope *InnermostTemplateScope = nullptr;
10899 for (TemplateParameterList *Params : ParameterLists) {
10900 // Ignore explicit specializations; they don't contribute to the template
10901 // depth.
10902 if (Params->size() == 0)
10903 continue;
10904
10905 InnermostTemplateScope = EnterScope();
10906 for (NamedDecl *Param : *Params) {
10907 if (Param->getDeclName()) {
10908 InnermostTemplateScope->AddDecl(Param);
10909 IdResolver.AddDecl(Param);
10910 }
10911 }
10912 ++Count;
10913 }
10914
10915 // Associate the new template scopes with the corresponding entities.
10916 if (InnermostTemplateScope) {
10917 assert(LookupDC && "no enclosing DeclContext for template lookup");
10918 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10919 }
10920
10921 return Count;
10922}
10923
10925 if (!RecordD) return;
10926 AdjustDeclIfTemplate(RecordD);
10929}
10930
10932 if (!RecordD) return;
10934}
10935
10937 if (!Param)
10938 return;
10939
10940 S->AddDecl(Param);
10941 if (Param->getDeclName())
10942 IdResolver.AddDecl(Param);
10943}
10944
10947
10948/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10949/// C++ method declaration. We're (re-)introducing the given
10950/// function parameter into scope for use in parsing later parts of
10951/// the method declaration. For example, we could see an
10952/// ActOnParamDefaultArgument event for this parameter.
10954 if (!ParamD)
10955 return;
10956
10957 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10958
10959 S->AddDecl(Param);
10960 if (Param->getDeclName())
10961 IdResolver.AddDecl(Param);
10962}
10963
10965 if (!MethodD)
10966 return;
10967
10968 AdjustDeclIfTemplate(MethodD);
10969
10971
10972 // Now that we have our default arguments, check the constructor
10973 // again. It could produce additional diagnostics or affect whether
10974 // the class has implicitly-declared destructors, among other
10975 // things.
10976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10978
10979 // Check the default arguments, which we may have added.
10980 if (!Method->isInvalidDecl())
10982}
10983
10984// Emit the given diagnostic for each non-address-space qualifier.
10985// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10986static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10988 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10989 bool DiagOccured = false;
10991 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10992 SourceLocation SL) {
10993 // This diagnostic should be emitted on any qualifier except an addr
10994 // space qualifier. However, forEachQualifier currently doesn't visit
10995 // addr space qualifiers, so there's no way to write this condition
10996 // right now; we just diagnose on everything.
10997 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10998 DiagOccured = true;
10999 });
11000 if (DiagOccured)
11001 D.setInvalidType();
11002 }
11003}
11004
11006 unsigned Kind) {
11007 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11008 return;
11009
11011 if (Chunk.Kind == DeclaratorChunk::Paren ||
11013 return;
11014
11015 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11016 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11017 << Kind << Chunk.getSourceRange();
11018 D.setInvalidType();
11019}
11020
11022 StorageClass &SC) {
11023 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11024
11025 // C++ [class.ctor]p3:
11026 // A constructor shall not be virtual (10.3) or static (9.4). A
11027 // constructor can be invoked for a const, volatile or const
11028 // volatile object. A constructor shall not be declared const,
11029 // volatile, or const volatile (9.3.2).
11030 if (isVirtual) {
11031 if (!D.isInvalidType())
11032 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11033 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11035 D.setInvalidType();
11036 }
11037 if (SC == SC_Static) {
11038 if (!D.isInvalidType())
11039 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11040 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11042 D.setInvalidType();
11043 SC = SC_None;
11044 }
11045
11046 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11048 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11052 D.setInvalidType();
11053 }
11054
11055 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11056 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11057
11058 // C++0x [class.ctor]p4:
11059 // A constructor shall not be declared with a ref-qualifier.
11061 if (FTI.hasRefQualifier()) {
11062 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11065 D.setInvalidType();
11066 }
11067
11068 // Rebuild the function type "R" without any type qualifiers (in
11069 // case any of the errors above fired) and with "void" as the
11070 // return type, since constructors don't have return types.
11071 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11072 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11073 return R;
11074
11076 EPI.TypeQuals = Qualifiers();
11077 EPI.RefQualifier = RQ_None;
11078
11079 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11080}
11081
11083 CXXRecordDecl *ClassDecl
11084 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11085 if (!ClassDecl)
11086 return Constructor->setInvalidDecl();
11087
11088 // C++ [class.copy]p3:
11089 // A declaration of a constructor for a class X is ill-formed if
11090 // its first parameter is of type (optionally cv-qualified) X and
11091 // either there are no other parameters or else all other
11092 // parameters have default arguments.
11093 if (!Constructor->isInvalidDecl() &&
11094 Constructor->hasOneParamOrDefaultArgs() &&
11095 !Constructor->isFunctionTemplateSpecialization()) {
11096 CanQualType ParamType =
11097 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11098 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11099 if (ParamType == ClassTy) {
11100 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11101 const char *ConstRef
11102 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11103 : " const &";
11104 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11105 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11106
11107 // FIXME: Rather that making the constructor invalid, we should endeavor
11108 // to fix the type.
11109 Constructor->setInvalidDecl();
11110 }
11111 }
11112}
11113
11115 CXXRecordDecl *RD = Destructor->getParent();
11116
11117 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11118 SourceLocation Loc;
11119
11120 if (!Destructor->isImplicit())
11121 Loc = Destructor->getLocation();
11122 else
11123 Loc = RD->getLocation();
11124
11125 // If we have a virtual destructor, look up the deallocation function
11127 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false)) {
11128 Expr *ThisArg = nullptr;
11129
11130 // If the notional 'delete this' expression requires a non-trivial
11131 // conversion from 'this' to the type of a destroying operator delete's
11132 // first parameter, perform that conversion now.
11133 if (OperatorDelete->isDestroyingOperatorDelete()) {
11134 unsigned AddressParamIndex = 0;
11135 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11136 ++AddressParamIndex;
11137 QualType ParamType =
11138 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11139 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11140 // C++ [class.dtor]p13:
11141 // ... as if for the expression 'delete this' appearing in a
11142 // non-virtual destructor of the destructor's class.
11143 ContextRAII SwitchContext(*this, Destructor);
11145 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11146 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11147 This = PerformImplicitConversion(This.get(), ParamType,
11149 if (This.isInvalid()) {
11150 // FIXME: Register this as a context note so that it comes out
11151 // in the right order.
11152 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11153 return true;
11154 }
11155 ThisArg = This.get();
11156 }
11157 }
11158
11159 DiagnoseUseOfDecl(OperatorDelete, Loc);
11160 MarkFunctionReferenced(Loc, OperatorDelete);
11161 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11162
11163 if (isa<CXXMethodDecl>(OperatorDelete) &&
11164 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11165 Context.getLangOpts())) {
11166 // In Microsoft ABI whenever a class has a defined operator delete,
11167 // scalar deleting destructors check the 3rd bit of the implicit
11168 // parameter and if it is set, then, global operator delete must be
11169 // called instead of the class-specific one. Find and save the global
11170 // operator delete for that case. Do not diagnose at this point because
11171 // the lack of a global operator delete is not an error if there are no
11172 // delete calls that require it.
11173 FunctionDecl *GlobalOperatorDelete =
11174 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11175 /*LookForGlobal*/ true);
11176 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11177 }
11178 }
11179 }
11180
11181 return false;
11182}
11183
11185 StorageClass& SC) {
11186 // C++ [class.dtor]p1:
11187 // [...] A typedef-name that names a class is a class-name
11188 // (7.1.3); however, a typedef-name that names a class shall not
11189 // be used as the identifier in the declarator for a destructor
11190 // declaration.
11191 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11192 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11193 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11194 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11195 else if (const TemplateSpecializationType *TST =
11196 DeclaratorType->getAs<TemplateSpecializationType>())
11197 if (TST->isTypeAlias())
11198 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11199 << DeclaratorType << 1;
11200
11201 // C++ [class.dtor]p2:
11202 // A destructor is used to destroy objects of its class type. A
11203 // destructor takes no parameters, and no return type can be
11204 // specified for it (not even void). The address of a destructor
11205 // shall not be taken. A destructor shall not be static. A
11206 // destructor can be invoked for a const, volatile or const
11207 // volatile object. A destructor shall not be declared const,
11208 // volatile or const volatile (9.3.2).
11209 if (SC == SC_Static) {
11210 if (!D.isInvalidType())
11211 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11212 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11215
11216 SC = SC_None;
11217 }
11218 if (!D.isInvalidType()) {
11219 // Destructors don't have return types, but the parser will
11220 // happily parse something like:
11221 //
11222 // class X {
11223 // float ~X();
11224 // };
11225 //
11226 // The return type will be eliminated later.
11227 if (D.getDeclSpec().hasTypeSpecifier())
11228 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11231 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11232 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11238 D.setInvalidType();
11239 }
11240 }
11241
11242 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11243 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11244
11245 // C++0x [class.dtor]p2:
11246 // A destructor shall not be declared with a ref-qualifier.
11248 if (FTI.hasRefQualifier()) {
11249 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11252 D.setInvalidType();
11253 }
11254
11255 // Make sure we don't have any parameters.
11256 if (FTIHasNonVoidParameters(FTI)) {
11257 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11258
11259 // Delete the parameters.
11260 FTI.freeParams();
11261 D.setInvalidType();
11262 }
11263
11264 // Make sure the destructor isn't variadic.
11265 if (FTI.isVariadic) {
11266 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11267 D.setInvalidType();
11268 }
11269
11270 // Rebuild the function type "R" without any type qualifiers or
11271 // parameters (in case any of the errors above fired) and with
11272 // "void" as the return type, since destructors don't have return
11273 // types.
11274 if (!D.isInvalidType())
11275 return R;
11276
11277 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11279 EPI.Variadic = false;
11280 EPI.TypeQuals = Qualifiers();
11281 EPI.RefQualifier = RQ_None;
11282 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11283}
11284
11285static void extendLeft(SourceRange &R, SourceRange Before) {
11286 if (Before.isInvalid())
11287 return;
11288 R.setBegin(Before.getBegin());
11289 if (R.getEnd().isInvalid())
11290 R.setEnd(Before.getEnd());
11291}
11292
11293static void extendRight(SourceRange &R, SourceRange After) {
11294 if (After.isInvalid())
11295 return;
11296 if (R.getBegin().isInvalid())
11297 R.setBegin(After.getBegin());
11298 R.setEnd(After.getEnd());
11299}
11300
11302 StorageClass& SC) {
11303 // C++ [class.conv.fct]p1:
11304 // Neither parameter types nor return type can be specified. The
11305 // type of a conversion function (8.3.5) is "function taking no
11306 // parameter returning conversion-type-id."
11307 if (SC == SC_Static) {
11308 if (!D.isInvalidType())
11309 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11311 << D.getName().getSourceRange();
11312 D.setInvalidType();
11313 SC = SC_None;
11314 }
11315
11316 TypeSourceInfo *ConvTSI = nullptr;
11317 QualType ConvType =
11319
11320 const DeclSpec &DS = D.getDeclSpec();
11321 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11322 // Conversion functions don't have return types, but the parser will
11323 // happily parse something like:
11324 //
11325 // class X {
11326 // float operator bool();
11327 // };
11328 //
11329 // The return type will be changed later anyway.
11330 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11333 D.setInvalidType();
11334 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11335 // It's also plausible that the user writes type qualifiers in the wrong
11336 // place, such as:
11337 // struct S { const operator int(); };
11338 // FIXME: we could provide a fixit to move the qualifiers onto the
11339 // conversion type.
11340 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11341 << SourceRange(D.getIdentifierLoc()) << 0;
11342 D.setInvalidType();
11343 }
11344 const auto *Proto = R->castAs<FunctionProtoType>();
11345 // Make sure we don't have any parameters.
11347 unsigned NumParam = Proto->getNumParams();
11348
11349 // [C++2b]
11350 // A conversion function shall have no non-object parameters.
11351 if (NumParam == 1) {
11353 if (const auto *First =
11354 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11355 First && First->isExplicitObjectParameter())
11356 NumParam--;
11357 }
11358
11359 if (NumParam != 0) {
11360 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11361 // Delete the parameters.
11362 FTI.freeParams();
11363 D.setInvalidType();
11364 } else if (Proto->isVariadic()) {
11365 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11366 D.setInvalidType();
11367 }
11368
11369 // Diagnose "&operator bool()" and other such nonsense. This
11370 // is actually a gcc extension which we don't support.
11371 if (Proto->getReturnType() != ConvType) {
11372 bool NeedsTypedef = false;
11373 SourceRange Before, After;
11374
11375 // Walk the chunks and extract information on them for our diagnostic.
11376 bool PastFunctionChunk = false;
11377 for (auto &Chunk : D.type_objects()) {
11378 switch (Chunk.Kind) {
11380 if (!PastFunctionChunk) {
11381 if (Chunk.Fun.HasTrailingReturnType) {
11382 TypeSourceInfo *TRT = nullptr;
11383 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11384 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11385 }
11386 PastFunctionChunk = true;
11387 break;
11388 }
11389 [[fallthrough]];
11391 NeedsTypedef = true;
11392 extendRight(After, Chunk.getSourceRange());
11393 break;
11394
11400 extendLeft(Before, Chunk.getSourceRange());
11401 break;
11402
11404 extendLeft(Before, Chunk.Loc);
11405 extendRight(After, Chunk.EndLoc);
11406 break;
11407 }
11408 }
11409
11410 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11411 After.isValid() ? After.getBegin() :
11412 D.getIdentifierLoc();
11413 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11414 DB << Before << After;
11415
11416 if (!NeedsTypedef) {
11417 DB << /*don't need a typedef*/0;
11418
11419 // If we can provide a correct fix-it hint, do so.
11420 if (After.isInvalid() && ConvTSI) {
11421 SourceLocation InsertLoc =
11423 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11425 InsertLoc, CharSourceRange::getTokenRange(Before))
11426 << FixItHint::CreateRemoval(Before);
11427 }
11428 } else if (!Proto->getReturnType()->isDependentType()) {
11429 DB << /*typedef*/1 << Proto->getReturnType();
11430 } else if (getLangOpts().CPlusPlus11) {
11431 DB << /*alias template*/2 << Proto->getReturnType();
11432 } else {
11433 DB << /*might not be fixable*/3;
11434 }
11435
11436 // Recover by incorporating the other type chunks into the result type.
11437 // Note, this does *not* change the name of the function. This is compatible
11438 // with the GCC extension:
11439 // struct S { &operator int(); } s;
11440 // int &r = s.operator int(); // ok in GCC
11441 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11442 ConvType = Proto->getReturnType();
11443 }
11444
11445 // C++ [class.conv.fct]p4:
11446 // The conversion-type-id shall not represent a function type nor
11447 // an array type.
11448 if (ConvType->isArrayType()) {
11449 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11450 ConvType = Context.getPointerType(ConvType);
11451 D.setInvalidType();
11452 } else if (ConvType->isFunctionType()) {
11453 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11454 ConvType = Context.getPointerType(ConvType);
11455 D.setInvalidType();
11456 }
11457
11458 // Rebuild the function type "R" without any parameters (in case any
11459 // of the errors above fired) and with the conversion type as the
11460 // return type.
11461 if (D.isInvalidType())
11462 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11463
11464 // C++0x explicit conversion operators.
11468 ? diag::warn_cxx98_compat_explicit_conversion_functions
11469 : diag::ext_explicit_conversion_functions)
11471}
11472
11474 assert(Conversion && "Expected to receive a conversion function declaration");
11475
11476 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11477
11478 // Make sure we aren't redeclaring the conversion function.
11479 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11480 // C++ [class.conv.fct]p1:
11481 // [...] A conversion function is never used to convert a
11482 // (possibly cv-qualified) object to the (possibly cv-qualified)
11483 // same object type (or a reference to it), to a (possibly
11484 // cv-qualified) base class of that type (or a reference to it),
11485 // or to (possibly cv-qualified) void.
11486 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11487 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11488 ConvType = ConvTypeRef->getPointeeType();
11489 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11491 /* Suppress diagnostics for instantiations. */;
11492 else if (Conversion->size_overridden_methods() != 0)
11493 /* Suppress diagnostics for overriding virtual function in a base class. */;
11494 else if (ConvType->isRecordType()) {
11495 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11496 if (ConvType == ClassType)
11497 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11498 << ClassType;
11499 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11500 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11501 << ClassType << ConvType;
11502 } else if (ConvType->isVoidType()) {
11503 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11504 << ClassType << ConvType;
11505 }
11506
11507 if (FunctionTemplateDecl *ConversionTemplate =
11508 Conversion->getDescribedFunctionTemplate()) {
11509 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11510 ConvType = ConvTypePtr->getPointeeType();
11511 }
11512 if (ConvType->isUndeducedAutoType()) {
11513 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11514 << getReturnTypeLoc(Conversion).getSourceRange()
11515 << ConvType->castAs<AutoType>()->getKeyword()
11516 << /* in declaration of conversion function template= */ 24;
11517 }
11518
11519 return ConversionTemplate;
11520 }
11521
11522 return Conversion;
11523}
11524
11529
11533
11535 DeclarationName Name, QualType R,
11536 bool IsLambda, DeclContext *DC) {
11537 if (!D.isFunctionDeclarator())
11538 return;
11539
11541 if (FTI.NumParams == 0)
11542 return;
11543 ParmVarDecl *ExplicitObjectParam = nullptr;
11544 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11545 const auto &ParamInfo = FTI.Params[Idx];
11546 if (!ParamInfo.Param)
11547 continue;
11548 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11549 if (!Param->isExplicitObjectParameter())
11550 continue;
11551 if (Idx == 0) {
11552 ExplicitObjectParam = Param;
11553 continue;
11554 } else {
11555 Diag(Param->getLocation(),
11556 diag::err_explicit_object_parameter_must_be_first)
11557 << IsLambda << Param->getSourceRange();
11558 }
11559 }
11560 if (!ExplicitObjectParam)
11561 return;
11562
11563 if (ExplicitObjectParam->hasDefaultArg()) {
11564 Diag(ExplicitObjectParam->getLocation(),
11565 diag::err_explicit_object_default_arg)
11566 << ExplicitObjectParam->getSourceRange();
11567 }
11568
11571 D.isStaticMember())) {
11572 Diag(ExplicitObjectParam->getBeginLoc(),
11573 diag::err_explicit_object_parameter_nonmember)
11574 << D.getSourceRange() << /*static=*/0 << IsLambda;
11575 D.setInvalidType();
11576 }
11577
11578 if (D.getDeclSpec().isVirtualSpecified()) {
11579 Diag(ExplicitObjectParam->getBeginLoc(),
11580 diag::err_explicit_object_parameter_nonmember)
11581 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11582 D.setInvalidType();
11583 }
11584
11585 // Friend declarations require some care. Consider:
11586 //
11587 // namespace N {
11588 // struct A{};
11589 // int f(A);
11590 // }
11591 //
11592 // struct S {
11593 // struct T {
11594 // int f(this T);
11595 // };
11596 //
11597 // friend int T::f(this T); // Allow this.
11598 // friend int f(this S); // But disallow this.
11599 // friend int N::f(this A); // And disallow this.
11600 // };
11601 //
11602 // Here, it seems to suffice to check whether the scope
11603 // specifier designates a class type.
11604 if (D.getDeclSpec().isFriendSpecified() &&
11605 !isa_and_present<CXXRecordDecl>(
11607 Diag(ExplicitObjectParam->getBeginLoc(),
11608 diag::err_explicit_object_parameter_nonmember)
11609 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11610 D.setInvalidType();
11611 }
11612
11613 if (IsLambda && FTI.hasMutableQualifier()) {
11614 Diag(ExplicitObjectParam->getBeginLoc(),
11615 diag::err_explicit_object_parameter_mutable)
11616 << D.getSourceRange();
11617 }
11618
11619 if (IsLambda)
11620 return;
11621
11622 if (!DC || !DC->isRecord()) {
11623 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11624 "should have been diagnosed already");
11625 return;
11626 }
11627
11628 // CWG2674: constructors and destructors cannot have explicit parameters.
11631 Diag(ExplicitObjectParam->getBeginLoc(),
11632 diag::err_explicit_object_parameter_constructor)
11634 << D.getSourceRange();
11635 D.setInvalidType();
11636 }
11637}
11638
11639namespace {
11640/// Utility class to accumulate and print a diagnostic listing the invalid
11641/// specifier(s) on a declaration.
11642struct BadSpecifierDiagnoser {
11643 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11644 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11645 ~BadSpecifierDiagnoser() {
11646 Diagnostic << Specifiers;
11647 }
11648
11649 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11650 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11651 }
11652 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11653 return check(SpecLoc,
11655 }
11656 void check(SourceLocation SpecLoc, const char *Spec) {
11657 if (SpecLoc.isInvalid()) return;
11658 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11659 if (!Specifiers.empty()) Specifiers += " ";
11660 Specifiers += Spec;
11661 }
11662
11663 Sema &S;
11664 Sema::SemaDiagnosticBuilder Diagnostic;
11665 std::string Specifiers;
11666};
11667}
11668
11670 StorageClass &SC) {
11671 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11672 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11673 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11674
11675 // C++ [temp.deduct.guide]p3:
11676 // A deduction-gide shall be declared in the same scope as the
11677 // corresponding class template.
11678 if (!CurContext->getRedeclContext()->Equals(
11679 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11680 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11681 << GuidedTemplateDecl;
11682 NoteTemplateLocation(*GuidedTemplateDecl);
11683 }
11684
11685 auto &DS = D.getMutableDeclSpec();
11686 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11687 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11688 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11689 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11690 BadSpecifierDiagnoser Diagnoser(
11691 *this, D.getIdentifierLoc(),
11692 diag::err_deduction_guide_invalid_specifier);
11693
11694 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11695 DS.ClearStorageClassSpecs();
11696 SC = SC_None;
11697
11698 // 'explicit' is permitted.
11699 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11700 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11701 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11702 DS.ClearConstexprSpec();
11703
11704 Diagnoser.check(DS.getConstSpecLoc(), "const");
11705 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11706 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11707 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11708 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11709 DS.ClearTypeQualifiers();
11710
11711 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11712 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11713 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11714 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11715 DS.ClearTypeSpecType();
11716 }
11717
11718 if (D.isInvalidType())
11719 return true;
11720
11721 // Check the declarator is simple enough.
11722 bool FoundFunction = false;
11723 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11724 if (Chunk.Kind == DeclaratorChunk::Paren)
11725 continue;
11726 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11728 diag::err_deduction_guide_with_complex_decl)
11729 << D.getSourceRange();
11730 break;
11731 }
11732 if (!Chunk.Fun.hasTrailingReturnType())
11733 return Diag(D.getName().getBeginLoc(),
11734 diag::err_deduction_guide_no_trailing_return_type);
11735
11736 // Check that the return type is written as a specialization of
11737 // the template specified as the deduction-guide's name.
11738 // The template name may not be qualified. [temp.deduct.guide]
11739 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11740 TypeSourceInfo *TSI = nullptr;
11741 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11742 assert(TSI && "deduction guide has valid type but invalid return type?");
11743 bool AcceptableReturnType = false;
11744 bool MightInstantiateToSpecialization = false;
11745 if (auto RetTST =
11747 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11748 bool TemplateMatches = Context.hasSameTemplateName(
11749 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11750
11752 SpecifiedName.getAsQualifiedTemplateName();
11753 assert(Qualifiers && "expected QualifiedTemplate");
11754 bool SimplyWritten =
11755 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11756 if (SimplyWritten && TemplateMatches)
11757 AcceptableReturnType = true;
11758 else {
11759 // This could still instantiate to the right type, unless we know it
11760 // names the wrong class template.
11761 auto *TD = SpecifiedName.getAsTemplateDecl();
11762 MightInstantiateToSpecialization =
11763 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11764 }
11765 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11766 MightInstantiateToSpecialization = true;
11767 }
11768
11769 if (!AcceptableReturnType)
11770 return Diag(TSI->getTypeLoc().getBeginLoc(),
11771 diag::err_deduction_guide_bad_trailing_return_type)
11772 << GuidedTemplate << TSI->getType()
11773 << MightInstantiateToSpecialization
11774 << TSI->getTypeLoc().getSourceRange();
11775
11776 // Keep going to check that we don't have any inner declarator pieces (we
11777 // could still have a function returning a pointer to a function).
11778 FoundFunction = true;
11779 }
11780
11781 if (D.isFunctionDefinition())
11782 // we can still create a valid deduction guide here.
11783 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11784 return false;
11785}
11786
11787//===----------------------------------------------------------------------===//
11788// Namespace Handling
11789//===----------------------------------------------------------------------===//
11790
11791/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11792/// reopened.
11794 SourceLocation Loc,
11795 IdentifierInfo *II, bool *IsInline,
11796 NamespaceDecl *PrevNS) {
11797 assert(*IsInline != PrevNS->isInline());
11798
11799 // 'inline' must appear on the original definition, but not necessarily
11800 // on all extension definitions, so the note should point to the first
11801 // definition to avoid confusion.
11802 PrevNS = PrevNS->getFirstDecl();
11803
11804 if (PrevNS->isInline())
11805 // The user probably just forgot the 'inline', so suggest that it
11806 // be added back.
11807 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11808 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11809 else
11810 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11811
11812 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11813 *IsInline = PrevNS->isInline();
11814}
11815
11816/// ActOnStartNamespaceDef - This is called at the start of a namespace
11817/// definition.
11819 SourceLocation InlineLoc,
11820 SourceLocation NamespaceLoc,
11821 SourceLocation IdentLoc, IdentifierInfo *II,
11822 SourceLocation LBrace,
11823 const ParsedAttributesView &AttrList,
11824 UsingDirectiveDecl *&UD, bool IsNested) {
11825 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11826 // For anonymous namespace, take the location of the left brace.
11827 SourceLocation Loc = II ? IdentLoc : LBrace;
11828 bool IsInline = InlineLoc.isValid();
11829 bool IsInvalid = false;
11830 bool IsStd = false;
11831 bool AddToKnown = false;
11832 Scope *DeclRegionScope = NamespcScope->getParent();
11833
11834 NamespaceDecl *PrevNS = nullptr;
11835 if (II) {
11836 // C++ [namespace.std]p7:
11837 // A translation unit shall not declare namespace std to be an inline
11838 // namespace (9.8.2).
11839 //
11840 // Precondition: the std namespace is in the file scope and is declared to
11841 // be inline
11842 auto DiagnoseInlineStdNS = [&]() {
11843 assert(IsInline && II->isStr("std") &&
11844 CurContext->getRedeclContext()->isTranslationUnit() &&
11845 "Precondition of DiagnoseInlineStdNS not met");
11846 Diag(InlineLoc, diag::err_inline_namespace_std)
11847 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11848 IsInline = false;
11849 };
11850 // C++ [namespace.def]p2:
11851 // The identifier in an original-namespace-definition shall not
11852 // have been previously defined in the declarative region in
11853 // which the original-namespace-definition appears. The
11854 // identifier in an original-namespace-definition is the name of
11855 // the namespace. Subsequently in that declarative region, it is
11856 // treated as an original-namespace-name.
11857 //
11858 // Since namespace names are unique in their scope, and we don't
11859 // look through using directives, just look for any ordinary names
11860 // as if by qualified name lookup.
11861 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11863 LookupQualifiedName(R, CurContext->getRedeclContext());
11864 NamedDecl *PrevDecl =
11865 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11866 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11867
11868 if (PrevNS) {
11869 // This is an extended namespace definition.
11870 if (IsInline && II->isStr("std") &&
11871 CurContext->getRedeclContext()->isTranslationUnit())
11872 DiagnoseInlineStdNS();
11873 else if (IsInline != PrevNS->isInline())
11874 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11875 &IsInline, PrevNS);
11876 } else if (PrevDecl) {
11877 // This is an invalid name redefinition.
11878 Diag(Loc, diag::err_redefinition_different_kind)
11879 << II;
11880 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11881 IsInvalid = true;
11882 // Continue on to push Namespc as current DeclContext and return it.
11883 } else if (II->isStr("std") &&
11884 CurContext->getRedeclContext()->isTranslationUnit()) {
11885 if (IsInline)
11886 DiagnoseInlineStdNS();
11887 // This is the first "real" definition of the namespace "std", so update
11888 // our cache of the "std" namespace to point at this definition.
11889 PrevNS = getStdNamespace();
11890 IsStd = true;
11891 AddToKnown = !IsInline;
11892 } else {
11893 // We've seen this namespace for the first time.
11894 AddToKnown = !IsInline;
11895 }
11896 } else {
11897 // Anonymous namespaces.
11898
11899 // Determine whether the parent already has an anonymous namespace.
11900 DeclContext *Parent = CurContext->getRedeclContext();
11901 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11902 PrevNS = TU->getAnonymousNamespace();
11903 } else {
11904 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11905 PrevNS = ND->getAnonymousNamespace();
11906 }
11907
11908 if (PrevNS && IsInline != PrevNS->isInline())
11909 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11910 &IsInline, PrevNS);
11911 }
11912
11914 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11915 if (IsInvalid)
11916 Namespc->setInvalidDecl();
11917
11918 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11919 AddPragmaAttributes(DeclRegionScope, Namespc);
11920 ProcessAPINotes(Namespc);
11921
11922 // FIXME: Should we be merging attributes?
11923 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11925
11926 if (IsStd)
11927 StdNamespace = Namespc;
11928 if (AddToKnown)
11929 KnownNamespaces[Namespc] = false;
11930
11931 if (II) {
11932 PushOnScopeChains(Namespc, DeclRegionScope);
11933 } else {
11934 // Link the anonymous namespace into its parent.
11935 DeclContext *Parent = CurContext->getRedeclContext();
11936 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11937 TU->setAnonymousNamespace(Namespc);
11938 } else {
11939 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11940 }
11941
11942 CurContext->addDecl(Namespc);
11943
11944 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11945 // behaves as if it were replaced by
11946 // namespace unique { /* empty body */ }
11947 // using namespace unique;
11948 // namespace unique { namespace-body }
11949 // where all occurrences of 'unique' in a translation unit are
11950 // replaced by the same identifier and this identifier differs
11951 // from all other identifiers in the entire program.
11952
11953 // We just create the namespace with an empty name and then add an
11954 // implicit using declaration, just like the standard suggests.
11955 //
11956 // CodeGen enforces the "universally unique" aspect by giving all
11957 // declarations semantically contained within an anonymous
11958 // namespace internal linkage.
11959
11960 if (!PrevNS) {
11962 /* 'using' */ LBrace,
11963 /* 'namespace' */ SourceLocation(),
11964 /* qualifier */ NestedNameSpecifierLoc(),
11965 /* identifier */ SourceLocation(),
11966 Namespc,
11967 /* Ancestor */ Parent);
11968 UD->setImplicit();
11969 Parent->addDecl(UD);
11970 }
11971 }
11972
11973 ActOnDocumentableDecl(Namespc);
11974
11975 // Although we could have an invalid decl (i.e. the namespace name is a
11976 // redefinition), push it as current DeclContext and try to continue parsing.
11977 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11978 // for the namespace has the declarations that showed up in that particular
11979 // namespace definition.
11980 PushDeclContext(NamespcScope, Namespc);
11981 return Namespc;
11982}
11983
11984/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11985/// is a namespace alias, returns the namespace it points to.
11987 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11988 return AD->getNamespace();
11989 return dyn_cast_or_null<NamespaceDecl>(D);
11990}
11991
11993 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11994 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11995 Namespc->setRBraceLoc(RBrace);
11997 if (Namespc->hasAttr<VisibilityAttr>())
11998 PopPragmaVisibility(true, RBrace);
11999 // If this namespace contains an export-declaration, export it now.
12000 if (DeferredExportedNamespaces.erase(Namespc))
12002}
12003
12005 return cast_or_null<CXXRecordDecl>(
12006 StdBadAlloc.get(Context.getExternalSource()));
12007}
12008
12010 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12011}
12012
12014 return cast_or_null<NamespaceDecl>(
12015 StdNamespace.get(Context.getExternalSource()));
12016}
12017
12018namespace {
12019
12020enum UnsupportedSTLSelect {
12021 USS_InvalidMember,
12022 USS_MissingMember,
12023 USS_NonTrivial,
12024 USS_Other
12025};
12026
12027struct InvalidSTLDiagnoser {
12028 Sema &S;
12029 SourceLocation Loc;
12030 QualType TyForDiags;
12031
12032 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12033 const VarDecl *VD = nullptr) {
12034 {
12035 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12036 << TyForDiags << ((int)Sel);
12037 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12038 assert(!Name.empty());
12039 D << Name;
12040 }
12041 }
12042 if (Sel == USS_InvalidMember) {
12043 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12044 << VD << VD->getSourceRange();
12045 }
12046 return QualType();
12047 }
12048};
12049} // namespace
12050
12052 SourceLocation Loc,
12054 assert(getLangOpts().CPlusPlus &&
12055 "Looking for comparison category type outside of C++.");
12056
12057 // Use an elaborated type for diagnostics which has a name containing the
12058 // prepended 'std' namespace but not any inline namespace names.
12059 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12061 /*Prefix=*/std::nullopt);
12062 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12063 Info->Record,
12064 /*OwnsTag=*/false);
12065 };
12066
12067 // Check if we've already successfully checked the comparison category type
12068 // before. If so, skip checking it again.
12069 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12070 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12071 // The only thing we need to check is that the type has a reachable
12072 // definition in the current context.
12073 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12074 return QualType();
12075
12076 return Info->getType();
12077 }
12078
12079 // If lookup failed
12080 if (!Info) {
12081 std::string NameForDiags = "std::";
12082 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12083 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12084 << NameForDiags << (int)Usage;
12085 return QualType();
12086 }
12087
12088 assert(Info->Kind == Kind);
12089 assert(Info->Record);
12090
12091 // Update the Record decl in case we encountered a forward declaration on our
12092 // first pass. FIXME: This is a bit of a hack.
12093 if (Info->Record->hasDefinition())
12094 Info->Record = Info->Record->getDefinition();
12095
12096 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12097 return QualType();
12098
12099 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12100
12101 if (!Info->Record->isTriviallyCopyable())
12102 return UnsupportedSTLError(USS_NonTrivial);
12103
12104 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12105 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12106 // Tolerate empty base classes.
12107 if (Base->isEmpty())
12108 continue;
12109 // Reject STL implementations which have at least one non-empty base.
12110 return UnsupportedSTLError();
12111 }
12112
12113 // Check that the STL has implemented the types using a single integer field.
12114 // This expectation allows better codegen for builtin operators. We require:
12115 // (1) The class has exactly one field.
12116 // (2) The field is an integral or enumeration type.
12117 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12118 if (std::distance(FIt, FEnd) != 1 ||
12119 !FIt->getType()->isIntegralOrEnumerationType()) {
12120 return UnsupportedSTLError();
12121 }
12122
12123 // Build each of the require values and store them in Info.
12124 for (ComparisonCategoryResult CCR :
12126 StringRef MemName = ComparisonCategories::getResultString(CCR);
12127 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12128
12129 if (!ValInfo)
12130 return UnsupportedSTLError(USS_MissingMember, MemName);
12131
12132 VarDecl *VD = ValInfo->VD;
12133 assert(VD && "should not be null!");
12134
12135 // Attempt to diagnose reasons why the STL definition of this type
12136 // might be foobar, including it failing to be a constant expression.
12137 // TODO Handle more ways the lookup or result can be invalid.
12138 if (!VD->isStaticDataMember() ||
12140 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12141
12142 // Attempt to evaluate the var decl as a constant expression and extract
12143 // the value of its first field as a ICE. If this fails, the STL
12144 // implementation is not supported.
12145 if (!ValInfo->hasValidIntValue())
12146 return UnsupportedSTLError();
12147
12148 MarkVariableReferenced(Loc, VD);
12149 }
12150
12151 // We've successfully built the required types and expressions. Update
12152 // the cache and return the newly cached value.
12153 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12154 return Info->getType();
12155}
12156
12158 if (!StdNamespace) {
12159 // The "std" namespace has not yet been defined, so build one implicitly.
12161 Context, Context.getTranslationUnitDecl(),
12162 /*Inline=*/false, SourceLocation(), SourceLocation(),
12163 &PP.getIdentifierTable().get("std"),
12164 /*PrevDecl=*/nullptr, /*Nested=*/false);
12165 getStdNamespace()->setImplicit(true);
12166 // We want the created NamespaceDecl to be available for redeclaration
12167 // lookups, but not for regular name lookups.
12168 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12169 getStdNamespace()->clearIdentifierNamespace();
12170 }
12171
12172 return getStdNamespace();
12173}
12174
12175static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12176 const char *ClassName,
12177 ClassTemplateDecl **CachedDecl,
12178 const Decl **MalformedDecl) {
12179 // We're looking for implicit instantiations of
12180 // template <typename U> class std::{ClassName}.
12181
12182 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12183 // it.
12184 return false;
12185
12186 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12187 if (!MalformedDecl)
12188 return;
12189 if (!D)
12190 D = SugaredType->getAsTagDecl();
12191 if (!D || !D->isInStdNamespace())
12192 return;
12193 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12194 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12195 *MalformedDecl = D;
12196 };
12197
12198 ClassTemplateDecl *Template = nullptr;
12200 if (const TemplateSpecializationType *TST =
12202 Template = dyn_cast_or_null<ClassTemplateDecl>(
12203 TST->getTemplateName().getAsTemplateDecl());
12204 Arguments = TST->template_arguments();
12205 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12206 Template = TT->getTemplateDecl();
12207 Arguments = TT->getTemplateArgs(S.Context);
12208 }
12209
12210 if (!Template) {
12211 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12212 return false;
12213 }
12214
12215 if (!*CachedDecl) {
12216 // Haven't recognized std::{ClassName} yet, maybe this is it.
12217 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12218 // semantics of this are slightly different, most notably the existing
12219 // "lookup" semantics explicitly diagnose an invalid definition as an
12220 // error.
12221 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12222 if (TemplateClass->getIdentifier() !=
12223 &S.PP.getIdentifierTable().get(ClassName) ||
12225 TemplateClass->getNonTransparentDeclContext()))
12226 return false;
12227 // This is a template called std::{ClassName}, but is it the right
12228 // template?
12229 TemplateParameterList *Params = Template->getTemplateParameters();
12230 if (Params->getMinRequiredArguments() != 1 ||
12231 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12232 Params->getParam(0)->isTemplateParameterPack()) {
12233 if (MalformedDecl)
12234 *MalformedDecl = TemplateClass;
12235 return false;
12236 }
12237
12238 // It's the right template.
12239 *CachedDecl = Template;
12240 }
12241
12242 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12243 return false;
12244
12245 // This is an instance of std::{ClassName}. Find the argument type.
12246 if (TypeArg) {
12247 QualType ArgType = Arguments[0].getAsType();
12248 // FIXME: Since TST only has as-written arguments, we have to perform the
12249 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12250 // - If an explicitly-specified template argument type is a lifetime type
12251 // with no lifetime qualifier, the __strong lifetime qualifier is
12252 // inferred.
12253 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12254 !ArgType.getObjCLifetime()) {
12255 Qualifiers Qs;
12257 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12258 }
12259 *TypeArg = ArgType;
12260 }
12261
12262 return true;
12263}
12264
12266 assert(getLangOpts().CPlusPlus &&
12267 "Looking for std::initializer_list outside of C++.");
12268
12269 // We're looking for implicit instantiations of
12270 // template <typename E> class std::initializer_list.
12271
12272 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12273 &StdInitializerList, /*MalformedDecl=*/nullptr);
12274}
12275
12277 const Decl **MalformedDecl) {
12278 assert(getLangOpts().CPlusPlus &&
12279 "Looking for std::type_identity outside of C++.");
12280
12281 // We're looking for implicit instantiations of
12282 // template <typename T> struct std::type_identity.
12283
12284 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12285 &StdTypeIdentity, MalformedDecl);
12286}
12287
12289 const char *ClassName,
12290 bool *WasMalformed) {
12291 if (!S.StdNamespace)
12292 return nullptr;
12293
12294 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12296 if (!S.LookupQualifiedName(Result, S.getStdNamespace()))
12297 return nullptr;
12298
12299 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12300 if (!Template) {
12301 Result.suppressDiagnostics();
12302 // We found something weird. Complain about the first thing we found.
12303 NamedDecl *Found = *Result.begin();
12304 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12305 << ClassName;
12306 if (WasMalformed)
12307 *WasMalformed = true;
12308 return nullptr;
12309 }
12310
12311 // We found some template with the correct name. Now verify that it's
12312 // correct.
12313 TemplateParameterList *Params = Template->getTemplateParameters();
12314 if (Params->getMinRequiredArguments() != 1 ||
12315 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12316 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12317 << ClassName;
12318 if (WasMalformed)
12319 *WasMalformed = true;
12320 return nullptr;
12321 }
12322
12323 return Template;
12324}
12325
12327 QualType TypeParam, SourceLocation Loc) {
12328 assert(S.getStdNamespace());
12329 TemplateArgumentListInfo Args(Loc, Loc);
12330 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12331 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12332
12334 Loc, Args, /*Scope=*/nullptr,
12335 /*ForNestedNameSpecifier=*/false);
12336}
12337
12339 if (!StdInitializerList) {
12340 bool WasMalformed = false;
12342 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12343 if (!StdInitializerList) {
12344 if (!WasMalformed)
12345 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12346 return QualType();
12347 }
12348 }
12349 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12350}
12351
12353 if (!StdTypeIdentity) {
12354 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12355 /*WasMalformed=*/nullptr);
12356 if (!StdTypeIdentity)
12357 return QualType();
12358 }
12359 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12360}
12361
12363 // C++ [dcl.init.list]p2:
12364 // A constructor is an initializer-list constructor if its first parameter
12365 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12366 // std::initializer_list<E> for some type E, and either there are no other
12367 // parameters or else all other parameters have default arguments.
12368 if (!Ctor->hasOneParamOrDefaultArgs())
12369 return false;
12370
12371 QualType ArgType = Ctor->getParamDecl(0)->getType();
12372 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12373 ArgType = RT->getPointeeType().getUnqualifiedType();
12374
12375 return isStdInitializerList(ArgType, nullptr);
12376}
12377
12378/// Determine whether a using statement is in a context where it will be
12379/// apply in all contexts.
12381 switch (CurContext->getDeclKind()) {
12382 case Decl::TranslationUnit:
12383 return true;
12384 case Decl::LinkageSpec:
12385 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12386 default:
12387 return false;
12388 }
12389}
12390
12391namespace {
12392
12393// Callback to only accept typo corrections that are namespaces.
12394class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12395public:
12396 bool ValidateCandidate(const TypoCorrection &candidate) override {
12397 if (NamedDecl *ND = candidate.getCorrectionDecl())
12399 return false;
12400 }
12401
12402 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12403 return std::make_unique<NamespaceValidatorCCC>(*this);
12404 }
12405};
12406
12407}
12408
12409static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12410 Sema &S) {
12411 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12412 Module *M = ND->getOwningModule();
12413 assert(M && "hidden namespace definition not in a module?");
12414
12415 if (M->isExplicitGlobalModule())
12416 S.Diag(Corrected.getCorrectionRange().getBegin(),
12417 diag::err_module_unimported_use_header)
12419 << /*Header Name*/ false;
12420 else
12421 S.Diag(Corrected.getCorrectionRange().getBegin(),
12422 diag::err_module_unimported_use)
12424 << M->getTopLevelModuleName();
12425}
12426
12428 CXXScopeSpec &SS,
12429 SourceLocation IdentLoc,
12430 IdentifierInfo *Ident) {
12431 R.clear();
12432 NamespaceValidatorCCC CCC{};
12433 if (TypoCorrection Corrected =
12434 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12436 // Generally we find it is confusing more than helpful to diagnose the
12437 // invisible namespace.
12438 // See https://github.com/llvm/llvm-project/issues/73893.
12439 //
12440 // However, we should diagnose when the users are trying to using an
12441 // invisible namespace. So we handle the case specially here.
12442 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12443 Corrected.requiresImport()) {
12444 DiagnoseInvisibleNamespace(Corrected, S);
12445 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12446 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12447 bool DroppedSpecifier =
12448 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12449 S.diagnoseTypo(Corrected,
12450 S.PDiag(diag::err_using_directive_member_suggest)
12451 << Ident << DC << DroppedSpecifier << SS.getRange(),
12452 S.PDiag(diag::note_namespace_defined_here));
12453 } else {
12454 S.diagnoseTypo(Corrected,
12455 S.PDiag(diag::err_using_directive_suggest) << Ident,
12456 S.PDiag(diag::note_namespace_defined_here));
12457 }
12458 R.addDecl(Corrected.getFoundDecl());
12459 return true;
12460 }
12461 return false;
12462}
12463
12465 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12466 SourceLocation IdentLoc,
12467 IdentifierInfo *NamespcName,
12468 const ParsedAttributesView &AttrList) {
12469 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12470 assert(NamespcName && "Invalid NamespcName.");
12471 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12472
12473 // Get the innermost enclosing declaration scope.
12474 S = S->getDeclParent();
12475
12476 UsingDirectiveDecl *UDir = nullptr;
12477 NestedNameSpecifier Qualifier = SS.getScopeRep();
12478
12479 // Lookup namespace name.
12480 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12481 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12482 if (R.isAmbiguous())
12483 return nullptr;
12484
12485 if (R.empty()) {
12486 R.clear();
12487 // Allow "using namespace std;" or "using namespace ::std;" even if
12488 // "std" hasn't been defined yet, for GCC compatibility.
12489 if ((!Qualifier ||
12490 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12491 NamespcName->isStr("std")) {
12492 Diag(IdentLoc, diag::ext_using_undefined_std);
12494 R.resolveKind();
12495 }
12496 // Otherwise, attempt typo correction.
12497 else
12498 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12499 }
12500
12501 if (!R.empty()) {
12502 NamedDecl *Named = R.getRepresentativeDecl();
12504 assert(NS && "expected namespace decl");
12505
12506 // The use of a nested name specifier may trigger deprecation warnings.
12507 DiagnoseUseOfDecl(Named, IdentLoc);
12508
12509 // C++ [namespace.udir]p1:
12510 // A using-directive specifies that the names in the nominated
12511 // namespace can be used in the scope in which the
12512 // using-directive appears after the using-directive. During
12513 // unqualified name lookup (3.4.1), the names appear as if they
12514 // were declared in the nearest enclosing namespace which
12515 // contains both the using-directive and the nominated
12516 // namespace. [Note: in this context, "contains" means "contains
12517 // directly or indirectly". ]
12518
12519 // Find enclosing context containing both using-directive and
12520 // nominated namespace.
12521 DeclContext *CommonAncestor = NS;
12522 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12523 CommonAncestor = CommonAncestor->getParent();
12524
12525 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12527 IdentLoc, Named, CommonAncestor);
12528
12530 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12531 Diag(IdentLoc, diag::warn_using_directive_in_header);
12532 }
12533
12534 PushUsingDirective(S, UDir);
12535 } else {
12536 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12537 }
12538
12539 if (UDir) {
12540 ProcessDeclAttributeList(S, UDir, AttrList);
12541 ProcessAPINotes(UDir);
12542 }
12543
12544 return UDir;
12545}
12546
12548 // If the scope has an associated entity and the using directive is at
12549 // namespace or translation unit scope, add the UsingDirectiveDecl into
12550 // its lookup structure so qualified name lookup can find it.
12551 DeclContext *Ctx = S->getEntity();
12552 if (Ctx && !Ctx->isFunctionOrMethod())
12553 Ctx->addDecl(UDir);
12554 else
12555 // Otherwise, it is at block scope. The using-directives will affect lookup
12556 // only to the end of the scope.
12557 S->PushUsingDirective(UDir);
12558}
12559
12561 SourceLocation UsingLoc,
12562 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12563 UnqualifiedId &Name,
12564 SourceLocation EllipsisLoc,
12565 const ParsedAttributesView &AttrList) {
12566 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12567
12568 if (SS.isEmpty()) {
12569 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12570 return nullptr;
12571 }
12572
12573 switch (Name.getKind()) {
12579 break;
12580
12583 // C++11 inheriting constructors.
12584 Diag(Name.getBeginLoc(),
12586 ? diag::warn_cxx98_compat_using_decl_constructor
12587 : diag::err_using_decl_constructor)
12588 << SS.getRange();
12589
12590 if (getLangOpts().CPlusPlus11) break;
12591
12592 return nullptr;
12593
12595 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12596 return nullptr;
12597
12599 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12601 return nullptr;
12602
12604 llvm_unreachable("cannot parse qualified deduction guide name");
12605 }
12606
12607 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12608 DeclarationName TargetName = TargetNameInfo.getName();
12609 if (!TargetName)
12610 return nullptr;
12611
12612 // Warn about access declarations.
12613 if (UsingLoc.isInvalid()) {
12615 ? diag::err_access_decl
12616 : diag::warn_access_decl_deprecated)
12617 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12618 }
12619
12620 if (EllipsisLoc.isInvalid()) {
12623 return nullptr;
12624 } else {
12626 !TargetNameInfo.containsUnexpandedParameterPack()) {
12627 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12628 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12629 EllipsisLoc = SourceLocation();
12630 }
12631 }
12632
12633 NamedDecl *UD =
12634 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12635 SS, TargetNameInfo, EllipsisLoc, AttrList,
12636 /*IsInstantiation*/ false,
12637 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12638 if (UD)
12639 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12640
12641 return UD;
12642}
12643
12645 SourceLocation UsingLoc,
12646 SourceLocation EnumLoc, SourceRange TyLoc,
12647 const IdentifierInfo &II, ParsedType Ty,
12648 const CXXScopeSpec &SS) {
12649 TypeSourceInfo *TSI = nullptr;
12650 SourceLocation IdentLoc = TyLoc.getBegin();
12651 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12652 if (EnumTy.isNull()) {
12653 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12654 ? diag::err_using_enum_is_dependent
12655 : diag::err_unknown_typename)
12656 << II.getName()
12657 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12658 TyLoc.getEnd());
12659 return nullptr;
12660 }
12661
12662 if (EnumTy->isDependentType()) {
12663 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12664 return nullptr;
12665 }
12666
12667 auto *Enum = EnumTy->getAsEnumDecl();
12668 if (!Enum) {
12669 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12670 return nullptr;
12671 }
12672
12673 if (TSI == nullptr)
12674 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12675
12676 auto *UD =
12677 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12678
12679 if (UD)
12680 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12681
12682 return UD;
12683}
12684
12685/// Determine whether a using declaration considers the given
12686/// declarations as "equivalent", e.g., if they are redeclarations of
12687/// the same entity or are both typedefs of the same type.
12688static bool
12690 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12691 return true;
12692
12693 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12694 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12695 return Context.hasSameType(TD1->getUnderlyingType(),
12696 TD2->getUnderlyingType());
12697
12698 // Two using_if_exists using-declarations are equivalent if both are
12699 // unresolved.
12702 return true;
12703
12704 return false;
12705}
12706
12708 const LookupResult &Previous,
12709 UsingShadowDecl *&PrevShadow) {
12710 // Diagnose finding a decl which is not from a base class of the
12711 // current class. We do this now because there are cases where this
12712 // function will silently decide not to build a shadow decl, which
12713 // will pre-empt further diagnostics.
12714 //
12715 // We don't need to do this in C++11 because we do the check once on
12716 // the qualifier.
12717 //
12718 // FIXME: diagnose the following if we care enough:
12719 // struct A { int foo; };
12720 // struct B : A { using A::foo; };
12721 // template <class T> struct C : A {};
12722 // template <class T> struct D : C<T> { using B::foo; } // <---
12723 // This is invalid (during instantiation) in C++03 because B::foo
12724 // resolves to the using decl in B, which is not a base class of D<T>.
12725 // We can't diagnose it immediately because C<T> is an unknown
12726 // specialization. The UsingShadowDecl in D<T> then points directly
12727 // to A::foo, which will look well-formed when we instantiate.
12728 // The right solution is to not collapse the shadow-decl chain.
12729 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12730 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12731 DeclContext *OrigDC = Orig->getDeclContext();
12732
12733 // Handle enums and anonymous structs.
12734 if (isa<EnumDecl>(OrigDC))
12735 OrigDC = OrigDC->getParent();
12736 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12737 while (OrigRec->isAnonymousStructOrUnion())
12738 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12739
12741 if (OrigDC == CurContext) {
12742 Diag(Using->getLocation(),
12743 diag::err_using_decl_nested_name_specifier_is_current_class)
12744 << Using->getQualifierLoc().getSourceRange();
12745 Diag(Orig->getLocation(), diag::note_using_decl_target);
12746 Using->setInvalidDecl();
12747 return true;
12748 }
12749
12750 Diag(Using->getQualifierLoc().getBeginLoc(),
12751 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12752 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12753 << Using->getQualifierLoc().getSourceRange();
12754 Diag(Orig->getLocation(), diag::note_using_decl_target);
12755 Using->setInvalidDecl();
12756 return true;
12757 }
12758 }
12759
12760 if (Previous.empty()) return false;
12761
12762 NamedDecl *Target = Orig;
12764 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12765
12766 // If the target happens to be one of the previous declarations, we
12767 // don't have a conflict.
12768 //
12769 // FIXME: but we might be increasing its access, in which case we
12770 // should redeclare it.
12771 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12772 bool FoundEquivalentDecl = false;
12773 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12774 I != E; ++I) {
12775 NamedDecl *D = (*I)->getUnderlyingDecl();
12776 // We can have UsingDecls in our Previous results because we use the same
12777 // LookupResult for checking whether the UsingDecl itself is a valid
12778 // redeclaration.
12780 continue;
12781
12782 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12783 // C++ [class.mem]p19:
12784 // If T is the name of a class, then [every named member other than
12785 // a non-static data member] shall have a name different from T
12786 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12790 CurContext,
12792 return true;
12793 }
12794
12796 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12797 PrevShadow = Shadow;
12798 FoundEquivalentDecl = true;
12800 // We don't conflict with an existing using shadow decl of an equivalent
12801 // declaration, but we're not a redeclaration of it.
12802 FoundEquivalentDecl = true;
12803 }
12804
12805 if (isVisible(D))
12806 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12807 }
12808
12809 if (FoundEquivalentDecl)
12810 return false;
12811
12812 // Always emit a diagnostic for a mismatch between an unresolved
12813 // using_if_exists and a resolved using declaration in either direction.
12815 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12816 if (!NonTag && !Tag)
12817 return false;
12818 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12819 Diag(Target->getLocation(), diag::note_using_decl_target);
12820 Diag((NonTag ? NonTag : Tag)->getLocation(),
12821 diag::note_using_decl_conflict);
12822 BUD->setInvalidDecl();
12823 return true;
12824 }
12825
12826 if (FunctionDecl *FD = Target->getAsFunction()) {
12827 NamedDecl *OldDecl = nullptr;
12828 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12829 /*IsForUsingDecl*/ true)) {
12831 return false;
12832
12834 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12835 break;
12836
12837 // We found a decl with the exact signature.
12839 // If we're in a record, we want to hide the target, so we
12840 // return true (without a diagnostic) to tell the caller not to
12841 // build a shadow decl.
12842 if (CurContext->isRecord())
12843 return true;
12844
12845 // If we're not in a record, this is an error.
12846 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12847 break;
12848 }
12849
12850 Diag(Target->getLocation(), diag::note_using_decl_target);
12851 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12852 BUD->setInvalidDecl();
12853 return true;
12854 }
12855
12856 // Target is not a function.
12857
12858 if (isa<TagDecl>(Target)) {
12859 // No conflict between a tag and a non-tag.
12860 if (!Tag) return false;
12861
12862 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12863 Diag(Target->getLocation(), diag::note_using_decl_target);
12864 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12865 BUD->setInvalidDecl();
12866 return true;
12867 }
12868
12869 // No conflict between a tag and a non-tag.
12870 if (!NonTag) return false;
12871
12872 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12873 Diag(Target->getLocation(), diag::note_using_decl_target);
12874 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12875 BUD->setInvalidDecl();
12876 return true;
12877}
12878
12879/// Determine whether a direct base class is a virtual base class.
12881 if (!Derived->getNumVBases())
12882 return false;
12883 for (auto &B : Derived->bases())
12884 if (B.getType()->getAsCXXRecordDecl() == Base)
12885 return B.isVirtual();
12886 llvm_unreachable("not a direct base class");
12887}
12888
12890 NamedDecl *Orig,
12891 UsingShadowDecl *PrevDecl) {
12892 // If we resolved to another shadow declaration, just coalesce them.
12893 NamedDecl *Target = Orig;
12895 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12896 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12897 }
12898
12899 NamedDecl *NonTemplateTarget = Target;
12900 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12901 NonTemplateTarget = TargetTD->getTemplatedDecl();
12902
12903 UsingShadowDecl *Shadow;
12904 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12905 UsingDecl *Using = cast<UsingDecl>(BUD);
12906 bool IsVirtualBase =
12908 Using->getQualifier().getAsRecordDecl());
12910 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12911 } else {
12913 Target->getDeclName(), BUD, Target);
12914 }
12915 BUD->addShadowDecl(Shadow);
12916
12917 Shadow->setAccess(BUD->getAccess());
12918 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12919 Shadow->setInvalidDecl();
12920
12921 Shadow->setPreviousDecl(PrevDecl);
12922
12923 if (S)
12924 PushOnScopeChains(Shadow, S);
12925 else
12926 CurContext->addDecl(Shadow);
12927
12928
12929 return Shadow;
12930}
12931
12933 if (Shadow->getDeclName().getNameKind() ==
12935 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12936
12937 // Remove it from the DeclContext...
12938 Shadow->getDeclContext()->removeDecl(Shadow);
12939
12940 // ...and the scope, if applicable...
12941 if (S) {
12942 S->RemoveDecl(Shadow);
12943 IdResolver.RemoveDecl(Shadow);
12944 }
12945
12946 // ...and the using decl.
12947 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12948
12949 // TODO: complain somehow if Shadow was used. It shouldn't
12950 // be possible for this to happen, because...?
12951}
12952
12953/// Find the base specifier for a base class with the given type.
12955 QualType DesiredBase,
12956 bool &AnyDependentBases) {
12957 // Check whether the named type is a direct base class.
12958 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12960 for (auto &Base : Derived->bases()) {
12961 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12962 if (CanonicalDesiredBase == BaseType)
12963 return &Base;
12964 if (BaseType->isDependentType())
12965 AnyDependentBases = true;
12966 }
12967 return nullptr;
12968}
12969
12970namespace {
12971class UsingValidatorCCC final : public CorrectionCandidateCallback {
12972public:
12973 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12974 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
12975 : HasTypenameKeyword(HasTypenameKeyword),
12976 IsInstantiation(IsInstantiation), OldNNS(NNS),
12977 RequireMemberOf(RequireMemberOf) {}
12978
12979 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12980 NamedDecl *ND = Candidate.getCorrectionDecl();
12981
12982 // Keywords are not valid here.
12983 if (!ND || isa<NamespaceDecl>(ND))
12984 return false;
12985
12986 // Completely unqualified names are invalid for a 'using' declaration.
12987 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12988 return false;
12989
12990 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12991 // reject.
12992
12993 if (RequireMemberOf) {
12994 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12995 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12996 // No-one ever wants a using-declaration to name an injected-class-name
12997 // of a base class, unless they're declaring an inheriting constructor.
12998 ASTContext &Ctx = ND->getASTContext();
12999 if (!Ctx.getLangOpts().CPlusPlus11)
13000 return false;
13001 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13002
13003 // Check that the injected-class-name is named as a member of its own
13004 // type; we don't want to suggest 'using Derived::Base;', since that
13005 // means something else.
13006 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13007 ? Candidate.getCorrectionSpecifier()
13008 : OldNNS;
13009 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13010 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13011 return false;
13012
13013 // Check that this inheriting constructor declaration actually names a
13014 // direct base class of the current class.
13015 bool AnyDependentBases = false;
13016 if (!findDirectBaseWithType(RequireMemberOf,
13017 Ctx.getCanonicalTagType(FoundRecord),
13018 AnyDependentBases) &&
13019 !AnyDependentBases)
13020 return false;
13021 } else {
13022 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13023 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13024 return false;
13025
13026 // FIXME: Check that the base class member is accessible?
13027 }
13028 } else {
13029 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13030 if (FoundRecord && FoundRecord->isInjectedClassName())
13031 return false;
13032 }
13033
13034 if (isa<TypeDecl>(ND))
13035 return HasTypenameKeyword || !IsInstantiation;
13036
13037 return !HasTypenameKeyword;
13038 }
13039
13040 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13041 return std::make_unique<UsingValidatorCCC>(*this);
13042 }
13043
13044private:
13045 bool HasTypenameKeyword;
13046 bool IsInstantiation;
13047 NestedNameSpecifier OldNNS;
13048 CXXRecordDecl *RequireMemberOf;
13049};
13050} // end anonymous namespace
13051
13053 // It is really dumb that we have to do this.
13054 LookupResult::Filter F = Previous.makeFilter();
13055 while (F.hasNext()) {
13056 NamedDecl *D = F.next();
13057 if (!isDeclInScope(D, CurContext, S))
13058 F.erase();
13059 // If we found a local extern declaration that's not ordinarily visible,
13060 // and this declaration is being added to a non-block scope, ignore it.
13061 // We're only checking for scope conflicts here, not also for violations
13062 // of the linkage rules.
13063 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13065 F.erase();
13066 }
13067 F.done();
13068}
13069
13071 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13072 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13073 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13074 const ParsedAttributesView &AttrList, bool IsInstantiation,
13075 bool IsUsingIfExists) {
13076 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13077 SourceLocation IdentLoc = NameInfo.getLoc();
13078 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13079
13080 // FIXME: We ignore attributes for now.
13081
13082 // For an inheriting constructor declaration, the name of the using
13083 // declaration is the name of a constructor in this class, not in the
13084 // base class.
13085 DeclarationNameInfo UsingName = NameInfo;
13087 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13088 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13089 Context.getCanonicalTagType(RD)));
13090
13091 // Do the redeclaration lookup in the current scope.
13092 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13094 Previous.setHideTags(false);
13095 if (S) {
13096 LookupName(Previous, S);
13097
13099 } else {
13100 assert(IsInstantiation && "no scope in non-instantiation");
13101 if (CurContext->isRecord())
13103 else {
13104 // No redeclaration check is needed here; in non-member contexts we
13105 // diagnosed all possible conflicts with other using-declarations when
13106 // building the template:
13107 //
13108 // For a dependent non-type using declaration, the only valid case is
13109 // if we instantiate to a single enumerator. We check for conflicts
13110 // between shadow declarations we introduce, and we check in the template
13111 // definition for conflicts between a non-type using declaration and any
13112 // other declaration, which together covers all cases.
13113 //
13114 // A dependent typename using declaration will never successfully
13115 // instantiate, since it will always name a class member, so we reject
13116 // that in the template definition.
13117 }
13118 }
13119
13120 // Check for invalid redeclarations.
13121 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13122 SS, IdentLoc, Previous))
13123 return nullptr;
13124
13125 // 'using_if_exists' doesn't make sense on an inherited constructor.
13126 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13128 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13129 return nullptr;
13130 }
13131
13132 DeclContext *LookupContext = computeDeclContext(SS);
13134 if (!LookupContext || EllipsisLoc.isValid()) {
13135 NamedDecl *D;
13136 // Dependent scope, or an unexpanded pack
13137 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13138 SS, NameInfo, IdentLoc))
13139 return nullptr;
13140
13141 if (Previous.isSingleResult() &&
13142 Previous.getFoundDecl()->isTemplateParameter())
13143 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13144
13145 if (HasTypenameKeyword) {
13146 // FIXME: not all declaration name kinds are legal here
13148 UsingLoc, TypenameLoc,
13149 QualifierLoc,
13150 IdentLoc, NameInfo.getName(),
13151 EllipsisLoc);
13152 } else {
13154 QualifierLoc, NameInfo, EllipsisLoc);
13155 }
13156 D->setAccess(AS);
13157 CurContext->addDecl(D);
13158 ProcessDeclAttributeList(S, D, AttrList);
13159 return D;
13160 }
13161
13162 auto Build = [&](bool Invalid) {
13163 UsingDecl *UD =
13164 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13165 UsingName, HasTypenameKeyword);
13166 UD->setAccess(AS);
13167 CurContext->addDecl(UD);
13168 ProcessDeclAttributeList(S, UD, AttrList);
13170 return UD;
13171 };
13172 auto BuildInvalid = [&]{ return Build(true); };
13173 auto BuildValid = [&]{ return Build(false); };
13174
13175 if (RequireCompleteDeclContext(SS, LookupContext))
13176 return BuildInvalid();
13177
13178 // Look up the target name.
13179 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13180
13181 // Unlike most lookups, we don't always want to hide tag
13182 // declarations: tag names are visible through the using declaration
13183 // even if hidden by ordinary names, *except* in a dependent context
13184 // where they may be used by two-phase lookup.
13185 if (!IsInstantiation)
13186 R.setHideTags(false);
13187
13188 // For the purposes of this lookup, we have a base object type
13189 // equal to that of the current context.
13190 if (CurContext->isRecord()) {
13192 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13193 }
13194
13195 LookupQualifiedName(R, LookupContext);
13196
13197 // Validate the context, now we have a lookup
13198 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13199 IdentLoc, &R))
13200 return nullptr;
13201
13202 if (R.empty() && IsUsingIfExists)
13204 UsingName.getName()),
13205 AS_public);
13206
13207 // Try to correct typos if possible. If constructor name lookup finds no
13208 // results, that means the named class has no explicit constructors, and we
13209 // suppressed declaring implicit ones (probably because it's dependent or
13210 // invalid).
13211 if (R.empty() &&
13213 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13214 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13215 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13216 auto *II = NameInfo.getName().getAsIdentifierInfo();
13217 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13218 CurContext->isStdNamespace() &&
13219 isa<TranslationUnitDecl>(LookupContext) &&
13220 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13221 getSourceManager().isInSystemHeader(UsingLoc))
13222 return nullptr;
13223 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13224 dyn_cast<CXXRecordDecl>(CurContext));
13225 if (TypoCorrection Corrected =
13226 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13228 // We reject candidates where DroppedSpecifier == true, hence the
13229 // literal '0' below.
13230 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13231 << NameInfo.getName() << LookupContext << 0
13232 << SS.getRange());
13233
13234 // If we picked a correction with no attached Decl we can't do anything
13235 // useful with it, bail out.
13236 NamedDecl *ND = Corrected.getCorrectionDecl();
13237 if (!ND)
13238 return BuildInvalid();
13239
13240 // If we corrected to an inheriting constructor, handle it as one.
13241 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13242 if (RD && RD->isInjectedClassName()) {
13243 // The parent of the injected class name is the class itself.
13244 RD = cast<CXXRecordDecl>(RD->getParent());
13245
13246 // Fix up the information we'll use to build the using declaration.
13247 if (Corrected.WillReplaceSpecifier()) {
13249 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13250 QualifierLoc.getSourceRange());
13251 QualifierLoc = Builder.getWithLocInContext(Context);
13252 }
13253
13254 // In this case, the name we introduce is the name of a derived class
13255 // constructor.
13256 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13257 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13258 Context.getCanonicalTagType(CurClass)));
13259 UsingName.setNamedTypeInfo(nullptr);
13260 for (auto *Ctor : LookupConstructors(RD))
13261 R.addDecl(Ctor);
13262 R.resolveKind();
13263 } else {
13264 // FIXME: Pick up all the declarations if we found an overloaded
13265 // function.
13266 UsingName.setName(ND->getDeclName());
13267 R.addDecl(ND);
13268 }
13269 } else {
13270 Diag(IdentLoc, diag::err_no_member)
13271 << NameInfo.getName() << LookupContext << SS.getRange();
13272 return BuildInvalid();
13273 }
13274 }
13275
13276 if (R.isAmbiguous())
13277 return BuildInvalid();
13278
13279 if (HasTypenameKeyword) {
13280 // If we asked for a typename and got a non-type decl, error out.
13281 if (!R.getAsSingle<TypeDecl>() &&
13283 Diag(IdentLoc, diag::err_using_typename_non_type);
13284 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13285 Diag((*I)->getUnderlyingDecl()->getLocation(),
13286 diag::note_using_decl_target);
13287 return BuildInvalid();
13288 }
13289 } else {
13290 // If we asked for a non-typename and we got a type, error out,
13291 // but only if this is an instantiation of an unresolved using
13292 // decl. Otherwise just silently find the type name.
13293 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13294 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13295 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13296 return BuildInvalid();
13297 }
13298 }
13299
13300 // C++14 [namespace.udecl]p6:
13301 // A using-declaration shall not name a namespace.
13302 if (R.getAsSingle<NamespaceDecl>()) {
13303 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13304 << SS.getRange();
13305 // Suggest using 'using namespace ...' instead.
13306 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13307 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13308 return BuildInvalid();
13309 }
13310
13311 UsingDecl *UD = BuildValid();
13312
13313 // Some additional rules apply to inheriting constructors.
13314 if (UsingName.getName().getNameKind() ==
13316 // Suppress access diagnostics; the access check is instead performed at the
13317 // point of use for an inheriting constructor.
13320 return UD;
13321 }
13322
13323 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13324 UsingShadowDecl *PrevDecl = nullptr;
13325 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13326 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13327 }
13328
13329 return UD;
13330}
13331
13333 SourceLocation UsingLoc,
13334 SourceLocation EnumLoc,
13335 SourceLocation NameLoc,
13336 TypeSourceInfo *EnumType,
13337 EnumDecl *ED) {
13338 bool Invalid = false;
13339
13340 if (CurContext->getRedeclContext()->isRecord()) {
13341 /// In class scope, check if this is a duplicate, for better a diagnostic.
13342 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13343 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13345
13347
13348 for (NamedDecl *D : Previous)
13349 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13350 if (UED->getEnumDecl() == ED) {
13351 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13352 << SourceRange(EnumLoc, NameLoc);
13353 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13354 Invalid = true;
13355 break;
13356 }
13357 }
13358
13359 if (RequireCompleteEnumDecl(ED, NameLoc))
13360 Invalid = true;
13361
13363 EnumLoc, NameLoc, EnumType);
13364 UD->setAccess(AS);
13365 CurContext->addDecl(UD);
13366
13367 if (Invalid) {
13368 UD->setInvalidDecl();
13369 return UD;
13370 }
13371
13372 // Create the shadow decls for each enumerator
13373 for (EnumConstantDecl *EC : ED->enumerators()) {
13374 UsingShadowDecl *PrevDecl = nullptr;
13375 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13378 LookupName(Previous, S);
13380
13381 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13382 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13383 }
13384
13385 return UD;
13386}
13387
13389 ArrayRef<NamedDecl *> Expansions) {
13390 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13391 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13392 isa<UsingPackDecl>(InstantiatedFrom));
13393
13394 auto *UPD =
13395 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13396 UPD->setAccess(InstantiatedFrom->getAccess());
13397 CurContext->addDecl(UPD);
13398 return UPD;
13399}
13400
13402 assert(!UD->hasTypename() && "expecting a constructor name");
13403
13404 QualType SourceType(UD->getQualifier().getAsType(), 0);
13406
13407 // Check whether the named type is a direct base class.
13408 bool AnyDependentBases = false;
13409 auto *Base =
13410 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13411 if (!Base && !AnyDependentBases) {
13412 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13413 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13414 UD->setInvalidDecl();
13415 return true;
13416 }
13417
13418 if (Base)
13419 Base->setInheritConstructors();
13420
13421 return false;
13422}
13423
13425 bool HasTypenameKeyword,
13426 const CXXScopeSpec &SS,
13427 SourceLocation NameLoc,
13428 const LookupResult &Prev) {
13429 NestedNameSpecifier Qual = SS.getScopeRep();
13430
13431 // C++03 [namespace.udecl]p8:
13432 // C++0x [namespace.udecl]p10:
13433 // A using-declaration is a declaration and can therefore be used
13434 // repeatedly where (and only where) multiple declarations are
13435 // allowed.
13436 //
13437 // That's in non-member contexts.
13438 if (!CurContext->getRedeclContext()->isRecord()) {
13439 // A dependent qualifier outside a class can only ever resolve to an
13440 // enumeration type. Therefore it conflicts with any other non-type
13441 // declaration in the same scope.
13442 // FIXME: How should we check for dependent type-type conflicts at block
13443 // scope?
13444 if (Qual.isDependent() && !HasTypenameKeyword) {
13445 for (auto *D : Prev) {
13446 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13447 bool OldCouldBeEnumerator =
13449 Diag(NameLoc,
13450 OldCouldBeEnumerator ? diag::err_redefinition
13451 : diag::err_redefinition_different_kind)
13452 << Prev.getLookupName();
13453 Diag(D->getLocation(), diag::note_previous_definition);
13454 return true;
13455 }
13456 }
13457 }
13458 return false;
13459 }
13460
13461 NestedNameSpecifier CNNS = Qual.getCanonical();
13462 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13463 NamedDecl *D = *I;
13464
13465 bool DTypename;
13466 NestedNameSpecifier DQual = std::nullopt;
13467 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13468 DTypename = UD->hasTypename();
13469 DQual = UD->getQualifier();
13470 } else if (UnresolvedUsingValueDecl *UD
13471 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13472 DTypename = false;
13473 DQual = UD->getQualifier();
13474 } else if (UnresolvedUsingTypenameDecl *UD
13475 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13476 DTypename = true;
13477 DQual = UD->getQualifier();
13478 } else continue;
13479
13480 // using decls differ if one says 'typename' and the other doesn't.
13481 // FIXME: non-dependent using decls?
13482 if (HasTypenameKeyword != DTypename) continue;
13483
13484 // using decls differ if they name different scopes (but note that
13485 // template instantiation can cause this check to trigger when it
13486 // didn't before instantiation).
13487 if (CNNS != DQual.getCanonical())
13488 continue;
13489
13490 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13491 Diag(D->getLocation(), diag::note_using_decl) << 1;
13492 return true;
13493 }
13494
13495 return false;
13496}
13497
13498bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13499 const CXXScopeSpec &SS,
13500 const DeclarationNameInfo &NameInfo,
13501 SourceLocation NameLoc,
13502 const LookupResult *R, const UsingDecl *UD) {
13503 DeclContext *NamedContext = computeDeclContext(SS);
13504 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13505 "resolvable context must have exactly one set of decls");
13506
13507 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13508 // relationship.
13509 bool Cxx20Enumerator = false;
13510 if (NamedContext) {
13511 EnumConstantDecl *EC = nullptr;
13512 if (R)
13513 EC = R->getAsSingle<EnumConstantDecl>();
13514 else if (UD && UD->shadow_size() == 1)
13515 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13516 if (EC)
13517 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13518
13519 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13520 // C++14 [namespace.udecl]p7:
13521 // A using-declaration shall not name a scoped enumerator.
13522 // C++20 p1099 permits enumerators.
13523 if (EC && R && ED->isScoped())
13524 Diag(SS.getBeginLoc(),
13526 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13527 : diag::ext_using_decl_scoped_enumerator)
13528 << SS.getRange();
13529
13530 // We want to consider the scope of the enumerator
13531 NamedContext = ED->getDeclContext();
13532 }
13533 }
13534
13535 if (!CurContext->isRecord()) {
13536 // C++03 [namespace.udecl]p3:
13537 // C++0x [namespace.udecl]p8:
13538 // A using-declaration for a class member shall be a member-declaration.
13539 // C++20 [namespace.udecl]p7
13540 // ... other than an enumerator ...
13541
13542 // If we weren't able to compute a valid scope, it might validly be a
13543 // dependent class or enumeration scope. If we have a 'typename' keyword,
13544 // the scope must resolve to a class type.
13545 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13546 : !HasTypename)
13547 return false; // OK
13548
13549 Diag(NameLoc,
13550 Cxx20Enumerator
13551 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13552 : diag::err_using_decl_can_not_refer_to_class_member)
13553 << SS.getRange();
13554
13555 if (Cxx20Enumerator)
13556 return false; // OK
13557
13558 auto *RD = NamedContext
13559 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13560 : nullptr;
13561 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13562 // See if there's a helpful fixit
13563
13564 if (!R) {
13565 // We will have already diagnosed the problem on the template
13566 // definition, Maybe we should do so again?
13567 } else if (R->getAsSingle<TypeDecl>()) {
13568 if (getLangOpts().CPlusPlus11) {
13569 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13570 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13571 << diag::MemClassWorkaround::AliasDecl
13573 NameInfo.getName().getAsString() +
13574 " = ");
13575 } else {
13576 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13577 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13578 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13579 << diag::MemClassWorkaround::TypedefDecl
13580 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13582 InsertLoc, " " + NameInfo.getName().getAsString());
13583 }
13584 } else if (R->getAsSingle<VarDecl>()) {
13585 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13586 // repeating the type of the static data member here.
13587 FixItHint FixIt;
13588 if (getLangOpts().CPlusPlus11) {
13589 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13591 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13592 }
13593
13594 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13595 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13596 } else if (R->getAsSingle<EnumConstantDecl>()) {
13597 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13598 // repeating the type of the enumeration here, and we can't do so if
13599 // the type is anonymous.
13600 FixItHint FixIt;
13601 if (getLangOpts().CPlusPlus11) {
13602 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13604 UsingLoc,
13605 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13606 }
13607
13608 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13609 << (getLangOpts().CPlusPlus11
13610 ? diag::MemClassWorkaround::ConstexprVar
13611 : diag::MemClassWorkaround::ConstVar)
13612 << FixIt;
13613 }
13614 }
13615
13616 return true; // Fail
13617 }
13618
13619 // If the named context is dependent, we can't decide much.
13620 if (!NamedContext) {
13621 // FIXME: in C++0x, we can diagnose if we can prove that the
13622 // nested-name-specifier does not refer to a base class, which is
13623 // still possible in some cases.
13624
13625 // Otherwise we have to conservatively report that things might be
13626 // okay.
13627 return false;
13628 }
13629
13630 // The current scope is a record.
13631 if (!NamedContext->isRecord()) {
13632 // Ideally this would point at the last name in the specifier,
13633 // but we don't have that level of source info.
13634 Diag(SS.getBeginLoc(),
13635 Cxx20Enumerator
13636 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13637 : diag::err_using_decl_nested_name_specifier_is_not_class)
13638 << SS.getScopeRep() << SS.getRange();
13639
13640 if (Cxx20Enumerator)
13641 return false; // OK
13642
13643 return true;
13644 }
13645
13646 if (!NamedContext->isDependentContext() &&
13647 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13648 return true;
13649
13650 // C++26 [namespace.udecl]p3:
13651 // In a using-declaration used as a member-declaration, each
13652 // using-declarator shall either name an enumerator or have a
13653 // nested-name-specifier naming a base class of the current class
13654 // ([expr.prim.this]). ...
13655 // "have a nested-name-specifier naming a base class of the current class"
13656 // was introduced by CWG400.
13657
13660
13661 if (Cxx20Enumerator) {
13662 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13663 << SS.getRange();
13664 return false;
13665 }
13666
13667 if (CurContext == NamedContext) {
13668 Diag(SS.getBeginLoc(),
13669 diag::err_using_decl_nested_name_specifier_is_current_class)
13670 << SS.getRange();
13671 return true;
13672 }
13673
13674 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13675 Diag(SS.getBeginLoc(),
13676 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13678 << SS.getRange();
13679 }
13680 return true;
13681 }
13682
13683 return false;
13684}
13685
13687 MultiTemplateParamsArg TemplateParamLists,
13688 SourceLocation UsingLoc, UnqualifiedId &Name,
13689 const ParsedAttributesView &AttrList,
13690 TypeResult Type, Decl *DeclFromDeclSpec) {
13691
13692 if (Type.isInvalid())
13693 return nullptr;
13694
13695 bool Invalid = false;
13697 TypeSourceInfo *TInfo = nullptr;
13698 GetTypeFromParser(Type.get(), &TInfo);
13699
13700 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13701 return nullptr;
13702
13705 Invalid = true;
13706 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13707 TInfo->getTypeLoc().getBeginLoc());
13708 }
13709
13710 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13711 TemplateParamLists.size()
13714 LookupName(Previous, S);
13715
13716 // Warn about shadowing the name of a template parameter.
13717 if (Previous.isSingleResult() &&
13718 Previous.getFoundDecl()->isTemplateParameter()) {
13720 Previous.clear();
13721 }
13722
13723 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13724 "name in alias declaration must be an identifier");
13726 Name.StartLocation,
13727 Name.Identifier, TInfo);
13728
13729 NewTD->setAccess(AS);
13730
13731 if (Invalid)
13732 NewTD->setInvalidDecl();
13733
13734 ProcessDeclAttributeList(S, NewTD, AttrList);
13735 AddPragmaAttributes(S, NewTD);
13736 ProcessAPINotes(NewTD);
13737
13739 Invalid |= NewTD->isInvalidDecl();
13740
13741 // Get the innermost enclosing declaration scope.
13742 S = S->getDeclParent();
13743
13744 bool Redeclaration = false;
13745
13746 NamedDecl *NewND;
13747 if (TemplateParamLists.size()) {
13748 TypeAliasTemplateDecl *OldDecl = nullptr;
13749 TemplateParameterList *OldTemplateParams = nullptr;
13750
13751 if (TemplateParamLists.size() != 1) {
13752 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13753 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13754 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13755 Invalid = true;
13756 }
13757 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13758
13759 // Check that we can declare a template here.
13760 if (CheckTemplateDeclScope(S, TemplateParams))
13761 return nullptr;
13762
13763 // Only consider previous declarations in the same scope.
13764 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13765 /*ExplicitInstantiationOrSpecialization*/false);
13766 if (!Previous.empty()) {
13767 Redeclaration = true;
13768
13769 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13770 if (!OldDecl && !Invalid) {
13771 Diag(UsingLoc, diag::err_redefinition_different_kind)
13772 << Name.Identifier;
13773
13774 NamedDecl *OldD = Previous.getRepresentativeDecl();
13775 if (OldD->getLocation().isValid())
13776 Diag(OldD->getLocation(), diag::note_previous_definition);
13777
13778 Invalid = true;
13779 }
13780
13781 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13782 if (TemplateParameterListsAreEqual(TemplateParams,
13783 OldDecl->getTemplateParameters(),
13784 /*Complain=*/true,
13786 OldTemplateParams =
13788 else
13789 Invalid = true;
13790
13791 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13792 if (!Invalid &&
13793 !Context.hasSameType(OldTD->getUnderlyingType(),
13794 NewTD->getUnderlyingType())) {
13795 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13796 // but we can't reasonably accept it.
13797 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13798 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13799 if (OldTD->getLocation().isValid())
13800 Diag(OldTD->getLocation(), diag::note_previous_definition);
13801 Invalid = true;
13802 }
13803 }
13804 }
13805
13806 // Merge any previous default template arguments into our parameters,
13807 // and check the parameter list.
13808 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13809 TPC_Other))
13810 return nullptr;
13811
13812 TypeAliasTemplateDecl *NewDecl =
13814 Name.Identifier, TemplateParams,
13815 NewTD);
13816 NewTD->setDescribedAliasTemplate(NewDecl);
13817
13818 NewDecl->setAccess(AS);
13819
13820 if (Invalid)
13821 NewDecl->setInvalidDecl();
13822 else if (OldDecl) {
13823 NewDecl->setPreviousDecl(OldDecl);
13824 CheckRedeclarationInModule(NewDecl, OldDecl);
13825 }
13826
13827 NewND = NewDecl;
13828 } else {
13829 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13831 handleTagNumbering(TD, S);
13832 }
13834 NewND = NewTD;
13835 }
13836
13837 PushOnScopeChains(NewND, S);
13838 ActOnDocumentableDecl(NewND);
13839 return NewND;
13840}
13841
13843 SourceLocation AliasLoc,
13844 IdentifierInfo *Alias, CXXScopeSpec &SS,
13845 SourceLocation IdentLoc,
13846 IdentifierInfo *Ident) {
13847
13848 // Lookup the namespace name.
13849 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13850 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13851
13852 if (R.isAmbiguous())
13853 return nullptr;
13854
13855 if (R.empty()) {
13856 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13857 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13858 return nullptr;
13859 }
13860 }
13861 assert(!R.isAmbiguous() && !R.empty());
13863
13864 // Check if we have a previous declaration with the same name.
13865 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13867 LookupName(PrevR, S);
13868
13869 // Check we're not shadowing a template parameter.
13870 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13872 PrevR.clear();
13873 }
13874
13875 // Filter out any other lookup result from an enclosing scope.
13876 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13877 /*AllowInlineNamespace*/false);
13878
13879 // Find the previous declaration and check that we can redeclare it.
13880 NamespaceAliasDecl *Prev = nullptr;
13881 if (PrevR.isSingleResult()) {
13882 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13883 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13884 // We already have an alias with the same name that points to the same
13885 // namespace; check that it matches.
13886 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13887 Prev = AD;
13888 } else if (isVisible(PrevDecl)) {
13889 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13890 << Alias;
13891 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13892 << AD->getNamespace();
13893 return nullptr;
13894 }
13895 } else if (isVisible(PrevDecl)) {
13896 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13897 ? diag::err_redefinition
13898 : diag::err_redefinition_different_kind;
13899 Diag(AliasLoc, DiagID) << Alias;
13900 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13901 return nullptr;
13902 }
13903 }
13904
13905 // The use of a nested name specifier may trigger deprecation warnings.
13906 DiagnoseUseOfDecl(ND, IdentLoc);
13907
13909 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13910 Alias, SS.getWithLocInContext(Context),
13911 IdentLoc, ND);
13912 if (Prev)
13913 AliasDecl->setPreviousDecl(Prev);
13914
13916 return AliasDecl;
13917}
13918
13919namespace {
13920struct SpecialMemberExceptionSpecInfo
13921 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13922 SourceLocation Loc;
13924
13925 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13928 SourceLocation Loc)
13929 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13930
13931 bool visitBase(CXXBaseSpecifier *Base);
13932 bool visitField(FieldDecl *FD);
13933
13934 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13935 unsigned Quals);
13936
13937 void visitSubobjectCall(Subobject Subobj,
13939};
13940}
13941
13942bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13943 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
13944 if (!BaseClass)
13945 return false;
13946
13947 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13948 if (auto *BaseCtor = SMOR.getMethod()) {
13949 visitSubobjectCall(Base, BaseCtor);
13950 return false;
13951 }
13952
13953 visitClassSubobject(BaseClass, Base, 0);
13954 return false;
13955}
13956
13957bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13958 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13959 FD->hasInClassInitializer()) {
13960 Expr *E = FD->getInClassInitializer();
13961 if (!E)
13962 // FIXME: It's a little wasteful to build and throw away a
13963 // CXXDefaultInitExpr here.
13964 // FIXME: We should have a single context note pointing at Loc, and
13965 // this location should be MD->getLocation() instead, since that's
13966 // the location where we actually use the default init expression.
13967 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13968 if (E)
13969 ExceptSpec.CalledExpr(E);
13970 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
13971 ->getAsCXXRecordDecl()) {
13972 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
13973 }
13974 return false;
13975}
13976
13977void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13978 Subobject Subobj,
13979 unsigned Quals) {
13980 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13981 bool IsMutable = Field && Field->isMutable();
13982 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13983}
13984
13985void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13986 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13987 // Note, if lookup fails, it doesn't matter what exception specification we
13988 // choose because the special member will be deleted.
13989 if (CXXMethodDecl *MD = SMOR.getMethod())
13990 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13991}
13992
13994 llvm::APSInt Result;
13996 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
13997 ExplicitSpec.setExpr(Converted.get());
13998 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13999 ExplicitSpec.setKind(Result.getBoolValue()
14002 return true;
14003 }
14005 return false;
14006}
14007
14010 if (!ExplicitExpr->isTypeDependent())
14012 return ES;
14013}
14014
14019 ComputingExceptionSpec CES(S, MD, Loc);
14020
14021 CXXRecordDecl *ClassDecl = MD->getParent();
14022
14023 // C++ [except.spec]p14:
14024 // An implicitly declared special member function (Clause 12) shall have an
14025 // exception-specification. [...]
14026 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14027 if (ClassDecl->isInvalidDecl())
14028 return Info.ExceptSpec;
14029
14030 // FIXME: If this diagnostic fires, we're probably missing a check for
14031 // attempting to resolve an exception specification before it's known
14032 // at a higher level.
14033 if (S.RequireCompleteType(MD->getLocation(),
14034 S.Context.getCanonicalTagType(ClassDecl),
14035 diag::err_exception_spec_incomplete_type))
14036 return Info.ExceptSpec;
14037
14038 // C++1z [except.spec]p7:
14039 // [Look for exceptions thrown by] a constructor selected [...] to
14040 // initialize a potentially constructed subobject,
14041 // C++1z [except.spec]p8:
14042 // The exception specification for an implicitly-declared destructor, or a
14043 // destructor without a noexcept-specifier, is potentially-throwing if and
14044 // only if any of the destructors for any of its potentially constructed
14045 // subojects is potentially throwing.
14046 // FIXME: We respect the first rule but ignore the "potentially constructed"
14047 // in the second rule to resolve a core issue (no number yet) that would have
14048 // us reject:
14049 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14050 // struct B : A {};
14051 // struct C : B { void f(); };
14052 // ... due to giving B::~B() a non-throwing exception specification.
14053 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14054 : Info.VisitAllBases);
14055
14056 return Info.ExceptSpec;
14057}
14058
14059namespace {
14060/// RAII object to register a special member as being currently declared.
14061struct DeclaringSpecialMember {
14062 Sema &S;
14064 Sema::ContextRAII SavedContext;
14065 bool WasAlreadyBeingDeclared;
14066
14067 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14068 : S(S), D(RD, CSM), SavedContext(S, RD) {
14069 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14070 if (WasAlreadyBeingDeclared)
14071 // This almost never happens, but if it does, ensure that our cache
14072 // doesn't contain a stale result.
14073 S.SpecialMemberCache.clear();
14074 else {
14075 // Register a note to be produced if we encounter an error while
14076 // declaring the special member.
14077 Sema::CodeSynthesisContext Ctx;
14078 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14079 // FIXME: We don't have a location to use here. Using the class's
14080 // location maintains the fiction that we declare all special members
14081 // with the class, but (1) it's not clear that lying about that helps our
14082 // users understand what's going on, and (2) there may be outer contexts
14083 // on the stack (some of which are relevant) and printing them exposes
14084 // our lies.
14085 Ctx.PointOfInstantiation = RD->getLocation();
14086 Ctx.Entity = RD;
14087 Ctx.SpecialMember = CSM;
14088 S.pushCodeSynthesisContext(Ctx);
14089 }
14090 }
14091 ~DeclaringSpecialMember() {
14092 if (!WasAlreadyBeingDeclared) {
14093 S.SpecialMembersBeingDeclared.erase(D);
14095 }
14096 }
14097
14098 /// Are we already trying to declare this special member?
14099 bool isAlreadyBeingDeclared() const {
14100 return WasAlreadyBeingDeclared;
14101 }
14102};
14103}
14104
14106 // Look up any existing declarations, but don't trigger declaration of all
14107 // implicit special members with this name.
14108 DeclarationName Name = FD->getDeclName();
14111 for (auto *D : FD->getParent()->lookup(Name))
14112 if (auto *Acceptable = R.getAcceptableDecl(D))
14113 R.addDecl(Acceptable);
14114 R.resolveKind();
14116
14117 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14119}
14120
14121void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14122 QualType ResultTy,
14123 ArrayRef<QualType> Args) {
14124 // Build an exception specification pointing back at this constructor.
14126
14127 LangAS AS = getDefaultCXXMethodAddrSpace();
14128 if (AS != LangAS::Default) {
14129 EPI.TypeQuals.addAddressSpace(AS);
14130 }
14131
14132 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14133 SpecialMem->setType(QT);
14134
14135 // During template instantiation of implicit special member functions we need
14136 // a reliable TypeSourceInfo for the function prototype in order to allow
14137 // functions to be substituted.
14138 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14139 TypeSourceInfo *TSI =
14140 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14141 SpecialMem->setTypeSourceInfo(TSI);
14142 }
14143}
14144
14146 CXXRecordDecl *ClassDecl) {
14147 // C++ [class.ctor]p5:
14148 // A default constructor for a class X is a constructor of class X
14149 // that can be called without an argument. If there is no
14150 // user-declared constructor for class X, a default constructor is
14151 // implicitly declared. An implicitly-declared default constructor
14152 // is an inline public member of its class.
14153 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14154 "Should not build implicit default constructor!");
14155
14156 DeclaringSpecialMember DSM(*this, ClassDecl,
14158 if (DSM.isAlreadyBeingDeclared())
14159 return nullptr;
14160
14162 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14163
14164 // Create the actual constructor declaration.
14165 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14166 SourceLocation ClassLoc = ClassDecl->getLocation();
14167 DeclarationName Name
14168 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14169 DeclarationNameInfo NameInfo(Name, ClassLoc);
14171 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14172 /*TInfo=*/nullptr, ExplicitSpecifier(),
14173 getCurFPFeatures().isFPConstrained(),
14174 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14177 DefaultCon->setAccess(AS_public);
14178 DefaultCon->setDefaulted();
14179
14180 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14181
14182 if (getLangOpts().CUDA)
14183 CUDA().inferTargetForImplicitSpecialMember(
14184 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14185 /* ConstRHS */ false,
14186 /* Diagnose */ false);
14187
14188 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14189 // constructors is easy to compute.
14190 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14191
14192 // Note that we have declared this constructor.
14193 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14194
14195 Scope *S = getScopeForContext(ClassDecl);
14197
14198 if (ShouldDeleteSpecialMember(DefaultCon,
14200 SetDeclDeleted(DefaultCon, ClassLoc);
14201
14202 if (S)
14203 PushOnScopeChains(DefaultCon, S, false);
14204 ClassDecl->addDecl(DefaultCon);
14205
14206 return DefaultCon;
14207}
14208
14211 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14212 !Constructor->doesThisDeclarationHaveABody() &&
14213 !Constructor->isDeleted()) &&
14214 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14215 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14216 return;
14217
14218 CXXRecordDecl *ClassDecl = Constructor->getParent();
14219 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14220 if (ClassDecl->isInvalidDecl()) {
14221 return;
14222 }
14223
14225
14226 // The exception specification is needed because we are defining the
14227 // function.
14228 ResolveExceptionSpec(CurrentLocation,
14229 Constructor->getType()->castAs<FunctionProtoType>());
14230 MarkVTableUsed(CurrentLocation, ClassDecl);
14231
14232 // Add a context note for diagnostics produced after this point.
14233 Scope.addContextNote(CurrentLocation);
14234
14235 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14236 Constructor->setInvalidDecl();
14237 return;
14238 }
14239
14240 SourceLocation Loc = Constructor->getEndLoc().isValid()
14241 ? Constructor->getEndLoc()
14242 : Constructor->getLocation();
14243 Constructor->setBody(new (Context) CompoundStmt(Loc));
14244 Constructor->markUsed(Context);
14245
14247 L->CompletedImplicitDefinition(Constructor);
14248 }
14249
14250 DiagnoseUninitializedFields(*this, Constructor);
14251}
14252
14254 // Perform any delayed checks on exception specifications.
14256}
14257
14258/// Find or create the fake constructor we synthesize to model constructing an
14259/// object of a derived class via a constructor of a base class.
14262 CXXConstructorDecl *BaseCtor,
14264 CXXRecordDecl *Derived = Shadow->getParent();
14265 SourceLocation UsingLoc = Shadow->getLocation();
14266
14267 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14268 // For now we use the name of the base class constructor as a member of the
14269 // derived class to indicate a (fake) inherited constructor name.
14270 DeclarationName Name = BaseCtor->getDeclName();
14271
14272 // Check to see if we already have a fake constructor for this inherited
14273 // constructor call.
14274 for (NamedDecl *Ctor : Derived->lookup(Name))
14276 ->getInheritedConstructor()
14277 .getConstructor(),
14278 BaseCtor))
14279 return cast<CXXConstructorDecl>(Ctor);
14280
14281 DeclarationNameInfo NameInfo(Name, UsingLoc);
14282 TypeSourceInfo *TInfo =
14283 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14284 FunctionProtoTypeLoc ProtoLoc =
14286
14287 // Check the inherited constructor is valid and find the list of base classes
14288 // from which it was inherited.
14289 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14290
14291 bool Constexpr = BaseCtor->isConstexpr() &&
14294 false, BaseCtor, &ICI);
14295
14297 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14298 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14299 /*isInline=*/true,
14300 /*isImplicitlyDeclared=*/true,
14302 InheritedConstructor(Shadow, BaseCtor),
14303 BaseCtor->getTrailingRequiresClause());
14304 if (Shadow->isInvalidDecl())
14305 DerivedCtor->setInvalidDecl();
14306
14307 // Build an unevaluated exception specification for this fake constructor.
14308 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14311 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14312 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14313 FPT->getParamTypes(), EPI));
14314
14315 // Build the parameter declarations.
14317 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14318 TypeSourceInfo *TInfo =
14319 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14321 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14322 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14323 PD->setScopeInfo(0, I);
14324 PD->setImplicit();
14325 // Ensure attributes are propagated onto parameters (this matters for
14326 // format, pass_object_size, ...).
14327 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14328 ParamDecls.push_back(PD);
14329 ProtoLoc.setParam(I, PD);
14330 }
14331
14332 // Set up the new constructor.
14333 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14334 DerivedCtor->setAccess(BaseCtor->getAccess());
14335 DerivedCtor->setParams(ParamDecls);
14336 Derived->addDecl(DerivedCtor);
14337
14338 if (ShouldDeleteSpecialMember(DerivedCtor,
14340 SetDeclDeleted(DerivedCtor, UsingLoc);
14341
14342 return DerivedCtor;
14343}
14344
14352
14355 CXXRecordDecl *ClassDecl = Constructor->getParent();
14356 assert(Constructor->getInheritedConstructor() &&
14357 !Constructor->doesThisDeclarationHaveABody() &&
14358 !Constructor->isDeleted());
14359 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14360 return;
14361
14362 // Initializations are performed "as if by a defaulted default constructor",
14363 // so enter the appropriate scope.
14365
14366 // The exception specification is needed because we are defining the
14367 // function.
14368 ResolveExceptionSpec(CurrentLocation,
14369 Constructor->getType()->castAs<FunctionProtoType>());
14370 MarkVTableUsed(CurrentLocation, ClassDecl);
14371
14372 // Add a context note for diagnostics produced after this point.
14373 Scope.addContextNote(CurrentLocation);
14374
14376 Constructor->getInheritedConstructor().getShadowDecl();
14377 CXXConstructorDecl *InheritedCtor =
14378 Constructor->getInheritedConstructor().getConstructor();
14379
14380 // [class.inhctor.init]p1:
14381 // initialization proceeds as if a defaulted default constructor is used to
14382 // initialize the D object and each base class subobject from which the
14383 // constructor was inherited
14384
14385 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14386 CXXRecordDecl *RD = Shadow->getParent();
14387 SourceLocation InitLoc = Shadow->getLocation();
14388
14389 // Build explicit initializers for all base classes from which the
14390 // constructor was inherited.
14392 for (bool VBase : {false, true}) {
14393 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14394 if (B.isVirtual() != VBase)
14395 continue;
14396
14397 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14398 if (!BaseRD)
14399 continue;
14400
14401 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14402 if (!BaseCtor.first)
14403 continue;
14404
14405 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14407 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14408
14409 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14410 Inits.push_back(new (Context) CXXCtorInitializer(
14411 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14412 SourceLocation()));
14413 }
14414 }
14415
14416 // We now proceed as if for a defaulted default constructor, with the relevant
14417 // initializers replaced.
14418
14419 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14420 Constructor->setInvalidDecl();
14421 return;
14422 }
14423
14424 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14425 Constructor->markUsed(Context);
14426
14428 L->CompletedImplicitDefinition(Constructor);
14429 }
14430
14431 DiagnoseUninitializedFields(*this, Constructor);
14432}
14433
14435 // C++ [class.dtor]p2:
14436 // If a class has no user-declared destructor, a destructor is
14437 // declared implicitly. An implicitly-declared destructor is an
14438 // inline public member of its class.
14439 assert(ClassDecl->needsImplicitDestructor());
14440
14441 DeclaringSpecialMember DSM(*this, ClassDecl,
14443 if (DSM.isAlreadyBeingDeclared())
14444 return nullptr;
14445
14447 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14448
14449 // Create the actual destructor declaration.
14450 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14451 SourceLocation ClassLoc = ClassDecl->getLocation();
14452 DeclarationName Name
14453 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14454 DeclarationNameInfo NameInfo(Name, ClassLoc);
14456 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14457 getCurFPFeatures().isFPConstrained(),
14458 /*isInline=*/true,
14459 /*isImplicitlyDeclared=*/true,
14462 Destructor->setAccess(AS_public);
14463 Destructor->setDefaulted();
14464
14465 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14466
14467 if (getLangOpts().CUDA)
14468 CUDA().inferTargetForImplicitSpecialMember(
14470 /* ConstRHS */ false,
14471 /* Diagnose */ false);
14472
14473 // We don't need to use SpecialMemberIsTrivial here; triviality for
14474 // destructors is easy to compute.
14475 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14476 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14477 ClassDecl->hasTrivialDestructorForCall());
14478
14479 // Note that we have declared this destructor.
14480 ++getASTContext().NumImplicitDestructorsDeclared;
14481
14482 Scope *S = getScopeForContext(ClassDecl);
14484
14485 // We can't check whether an implicit destructor is deleted before we complete
14486 // the definition of the class, because its validity depends on the alignment
14487 // of the class. We'll check this from ActOnFields once the class is complete.
14488 if (ClassDecl->isCompleteDefinition() &&
14490 SetDeclDeleted(Destructor, ClassLoc);
14491
14492 // Introduce this destructor into its scope.
14493 if (S)
14494 PushOnScopeChains(Destructor, S, false);
14495 ClassDecl->addDecl(Destructor);
14496
14497 return Destructor;
14498}
14499
14502 assert((Destructor->isDefaulted() &&
14503 !Destructor->doesThisDeclarationHaveABody() &&
14504 !Destructor->isDeleted()) &&
14505 "DefineImplicitDestructor - call it for implicit default dtor");
14506 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14507 return;
14508
14509 CXXRecordDecl *ClassDecl = Destructor->getParent();
14510 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14511
14513
14514 // The exception specification is needed because we are defining the
14515 // function.
14516 ResolveExceptionSpec(CurrentLocation,
14517 Destructor->getType()->castAs<FunctionProtoType>());
14518 MarkVTableUsed(CurrentLocation, ClassDecl);
14519
14520 // Add a context note for diagnostics produced after this point.
14521 Scope.addContextNote(CurrentLocation);
14522
14524 Destructor->getParent());
14525
14527 Destructor->setInvalidDecl();
14528 return;
14529 }
14530
14531 SourceLocation Loc = Destructor->getEndLoc().isValid()
14532 ? Destructor->getEndLoc()
14533 : Destructor->getLocation();
14534 Destructor->setBody(new (Context) CompoundStmt(Loc));
14535 Destructor->markUsed(Context);
14536
14538 L->CompletedImplicitDefinition(Destructor);
14539 }
14540}
14541
14544 if (Destructor->isInvalidDecl())
14545 return;
14546
14547 CXXRecordDecl *ClassDecl = Destructor->getParent();
14548 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14549 "implicit complete dtors unneeded outside MS ABI");
14550 assert(ClassDecl->getNumVBases() > 0 &&
14551 "complete dtor only exists for classes with vbases");
14552
14554
14555 // Add a context note for diagnostics produced after this point.
14556 Scope.addContextNote(CurrentLocation);
14557
14558 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14559}
14560
14562 // If the context is an invalid C++ class, just suppress these checks.
14563 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14564 if (Record->isInvalidDecl()) {
14567 return;
14568 }
14570 }
14571}
14572
14575
14576 if (!DelayedDllExportMemberFunctions.empty()) {
14578 std::swap(DelayedDllExportMemberFunctions, WorkList);
14579 for (CXXMethodDecl *M : WorkList) {
14580 DefineDefaultedFunction(*this, M, M->getLocation());
14581
14582 // Pass the method to the consumer to get emitted. This is not necessary
14583 // for explicit instantiation definitions, as they will get emitted
14584 // anyway.
14585 if (M->getParent()->getTemplateSpecializationKind() !=
14588 }
14589 }
14590}
14591
14593 if (!DelayedDllExportClasses.empty()) {
14594 // Calling ReferenceDllExportedMembers might cause the current function to
14595 // be called again, so use a local copy of DelayedDllExportClasses.
14597 std::swap(DelayedDllExportClasses, WorkList);
14598 for (CXXRecordDecl *Class : WorkList)
14600 }
14601}
14602
14604 assert(getLangOpts().CPlusPlus11 &&
14605 "adjusting dtor exception specs was introduced in c++11");
14606
14607 if (Destructor->isDependentContext())
14608 return;
14609
14610 // C++11 [class.dtor]p3:
14611 // A declaration of a destructor that does not have an exception-
14612 // specification is implicitly considered to have the same exception-
14613 // specification as an implicit declaration.
14614 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14615 if (DtorType->hasExceptionSpec())
14616 return;
14617
14618 // Replace the destructor's type, building off the existing one. Fortunately,
14619 // the only thing of interest in the destructor type is its extended info.
14620 // The return and arguments are fixed.
14621 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14624 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14625
14626 // FIXME: If the destructor has a body that could throw, and the newly created
14627 // spec doesn't allow exceptions, we should emit a warning, because this
14628 // change in behavior can break conforming C++03 programs at runtime.
14629 // However, we don't have a body or an exception specification yet, so it
14630 // needs to be done somewhere else.
14631}
14632
14633namespace {
14634/// An abstract base class for all helper classes used in building the
14635// copy/move operators. These classes serve as factory functions and help us
14636// avoid using the same Expr* in the AST twice.
14637class ExprBuilder {
14638 ExprBuilder(const ExprBuilder&) = delete;
14639 ExprBuilder &operator=(const ExprBuilder&) = delete;
14640
14641protected:
14642 static Expr *assertNotNull(Expr *E) {
14643 assert(E && "Expression construction must not fail.");
14644 return E;
14645 }
14646
14647public:
14648 ExprBuilder() {}
14649 virtual ~ExprBuilder() {}
14650
14651 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14652};
14653
14654class RefBuilder: public ExprBuilder {
14655 VarDecl *Var;
14656 QualType VarType;
14657
14658public:
14659 Expr *build(Sema &S, SourceLocation Loc) const override {
14660 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14661 }
14662
14663 RefBuilder(VarDecl *Var, QualType VarType)
14664 : Var(Var), VarType(VarType) {}
14665};
14666
14667class ThisBuilder: public ExprBuilder {
14668public:
14669 Expr *build(Sema &S, SourceLocation Loc) const override {
14670 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14671 }
14672};
14673
14674class CastBuilder: public ExprBuilder {
14675 const ExprBuilder &Builder;
14676 QualType Type;
14678 const CXXCastPath &Path;
14679
14680public:
14681 Expr *build(Sema &S, SourceLocation Loc) const override {
14682 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14683 CK_UncheckedDerivedToBase, Kind,
14684 &Path).get());
14685 }
14686
14687 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14688 const CXXCastPath &Path)
14689 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14690};
14691
14692class DerefBuilder: public ExprBuilder {
14693 const ExprBuilder &Builder;
14694
14695public:
14696 Expr *build(Sema &S, SourceLocation Loc) const override {
14697 return assertNotNull(
14698 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14699 }
14700
14701 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14702};
14703
14704class MemberBuilder: public ExprBuilder {
14705 const ExprBuilder &Builder;
14706 QualType Type;
14707 CXXScopeSpec SS;
14708 bool IsArrow;
14709 LookupResult &MemberLookup;
14710
14711public:
14712 Expr *build(Sema &S, SourceLocation Loc) const override {
14713 return assertNotNull(S.BuildMemberReferenceExpr(
14714 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14715 nullptr, MemberLookup, nullptr, nullptr).get());
14716 }
14717
14718 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14719 LookupResult &MemberLookup)
14720 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14721 MemberLookup(MemberLookup) {}
14722};
14723
14724class MoveCastBuilder: public ExprBuilder {
14725 const ExprBuilder &Builder;
14726
14727public:
14728 Expr *build(Sema &S, SourceLocation Loc) const override {
14729 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14730 }
14731
14732 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14733};
14734
14735class LvalueConvBuilder: public ExprBuilder {
14736 const ExprBuilder &Builder;
14737
14738public:
14739 Expr *build(Sema &S, SourceLocation Loc) const override {
14740 return assertNotNull(
14741 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14742 }
14743
14744 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14745};
14746
14747class SubscriptBuilder: public ExprBuilder {
14748 const ExprBuilder &Base;
14749 const ExprBuilder &Index;
14750
14751public:
14752 Expr *build(Sema &S, SourceLocation Loc) const override {
14753 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14754 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14755 }
14756
14757 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14758 : Base(Base), Index(Index) {}
14759};
14760
14761} // end anonymous namespace
14762
14763/// When generating a defaulted copy or move assignment operator, if a field
14764/// should be copied with __builtin_memcpy rather than via explicit assignments,
14765/// do so. This optimization only applies for arrays of scalars, and for arrays
14766/// of class type where the selected copy/move-assignment operator is trivial.
14767static StmtResult
14769 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14770 // Compute the size of the memory buffer to be copied.
14771 QualType SizeType = S.Context.getSizeType();
14772 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14774
14775 // Take the address of the field references for "from" and "to". We
14776 // directly construct UnaryOperators here because semantic analysis
14777 // does not permit us to take the address of an xvalue.
14778 Expr *From = FromB.build(S, Loc);
14779 From = UnaryOperator::Create(
14780 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14781 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14782 Expr *To = ToB.build(S, Loc);
14784 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14785 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14786
14787 bool NeedsCollectableMemCpy = false;
14788 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14789 NeedsCollectableMemCpy = RD->hasObjectMember();
14790
14791 // Create a reference to the __builtin_objc_memmove_collectable function
14792 StringRef MemCpyName = NeedsCollectableMemCpy ?
14793 "__builtin_objc_memmove_collectable" :
14794 "__builtin_memcpy";
14795 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14797 S.LookupName(R, S.TUScope, true);
14798
14799 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14800 if (!MemCpy)
14801 // Something went horribly wrong earlier, and we will have complained
14802 // about it.
14803 return StmtError();
14804
14805 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14806 VK_PRValue, Loc, nullptr);
14807 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14808
14809 Expr *CallArgs[] = {
14810 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14811 };
14812 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14813 Loc, CallArgs, Loc);
14814
14815 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14816 return Call.getAs<Stmt>();
14817}
14818
14819/// Builds a statement that copies/moves the given entity from \p From to
14820/// \c To.
14821///
14822/// This routine is used to copy/move the members of a class with an
14823/// implicitly-declared copy/move assignment operator. When the entities being
14824/// copied are arrays, this routine builds for loops to copy them.
14825///
14826/// \param S The Sema object used for type-checking.
14827///
14828/// \param Loc The location where the implicit copy/move is being generated.
14829///
14830/// \param T The type of the expressions being copied/moved. Both expressions
14831/// must have this type.
14832///
14833/// \param To The expression we are copying/moving to.
14834///
14835/// \param From The expression we are copying/moving from.
14836///
14837/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14838/// Otherwise, it's a non-static member subobject.
14839///
14840/// \param Copying Whether we're copying or moving.
14841///
14842/// \param Depth Internal parameter recording the depth of the recursion.
14843///
14844/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14845/// if a memcpy should be used instead.
14846static StmtResult
14848 const ExprBuilder &To, const ExprBuilder &From,
14849 bool CopyingBaseSubobject, bool Copying,
14850 unsigned Depth = 0) {
14851 // C++11 [class.copy]p28:
14852 // Each subobject is assigned in the manner appropriate to its type:
14853 //
14854 // - if the subobject is of class type, as if by a call to operator= with
14855 // the subobject as the object expression and the corresponding
14856 // subobject of x as a single function argument (as if by explicit
14857 // qualification; that is, ignoring any possible virtual overriding
14858 // functions in more derived classes);
14859 //
14860 // C++03 [class.copy]p13:
14861 // - if the subobject is of class type, the copy assignment operator for
14862 // the class is used (as if by explicit qualification; that is,
14863 // ignoring any possible virtual overriding functions in more derived
14864 // classes);
14865 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
14866 // Look for operator=.
14867 DeclarationName Name
14869 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14870 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14871
14872 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14873 // operator.
14874 if (!S.getLangOpts().CPlusPlus11) {
14875 LookupResult::Filter F = OpLookup.makeFilter();
14876 while (F.hasNext()) {
14877 NamedDecl *D = F.next();
14878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14879 if (Method->isCopyAssignmentOperator() ||
14880 (!Copying && Method->isMoveAssignmentOperator()))
14881 continue;
14882
14883 F.erase();
14884 }
14885 F.done();
14886 }
14887
14888 // Suppress the protected check (C++ [class.protected]) for each of the
14889 // assignment operators we found. This strange dance is required when
14890 // we're assigning via a base classes's copy-assignment operator. To
14891 // ensure that we're getting the right base class subobject (without
14892 // ambiguities), we need to cast "this" to that subobject type; to
14893 // ensure that we don't go through the virtual call mechanism, we need
14894 // to qualify the operator= name with the base class (see below). However,
14895 // this means that if the base class has a protected copy assignment
14896 // operator, the protected member access check will fail. So, we
14897 // rewrite "protected" access to "public" access in this case, since we
14898 // know by construction that we're calling from a derived class.
14899 if (CopyingBaseSubobject) {
14900 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14901 L != LEnd; ++L) {
14902 if (L.getAccess() == AS_protected)
14903 L.setAccess(AS_public);
14904 }
14905 }
14906
14907 // Create the nested-name-specifier that will be used to qualify the
14908 // reference to operator=; this is required to suppress the virtual
14909 // call mechanism.
14910 CXXScopeSpec SS;
14911 // FIXME: Don't canonicalize this.
14912 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14913 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
14914
14915 // Create the reference to operator=.
14916 ExprResult OpEqualRef
14917 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14918 SS, /*TemplateKWLoc=*/SourceLocation(),
14919 /*FirstQualifierInScope=*/nullptr,
14920 OpLookup,
14921 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14922 /*SuppressQualifierCheck=*/true);
14923 if (OpEqualRef.isInvalid())
14924 return StmtError();
14925
14926 // Build the call to the assignment operator.
14927
14928 Expr *FromInst = From.build(S, Loc);
14929 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14930 OpEqualRef.getAs<Expr>(),
14931 Loc, FromInst, Loc);
14932 if (Call.isInvalid())
14933 return StmtError();
14934
14935 // If we built a call to a trivial 'operator=' while copying an array,
14936 // bail out. We'll replace the whole shebang with a memcpy.
14937 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14938 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14939 return StmtResult((Stmt*)nullptr);
14940
14941 // Convert to an expression-statement, and clean up any produced
14942 // temporaries.
14943 return S.ActOnExprStmt(Call);
14944 }
14945
14946 // - if the subobject is of scalar type, the built-in assignment
14947 // operator is used.
14949 if (!ArrayTy) {
14951 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14952 if (Assignment.isInvalid())
14953 return StmtError();
14954 return S.ActOnExprStmt(Assignment);
14955 }
14956
14957 // - if the subobject is an array, each element is assigned, in the
14958 // manner appropriate to the element type;
14959
14960 // Construct a loop over the array bounds, e.g.,
14961 //
14962 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14963 //
14964 // that will copy each of the array elements.
14965 QualType SizeType = S.Context.getSizeType();
14966
14967 // Create the iteration variable.
14968 IdentifierInfo *IterationVarName = nullptr;
14969 {
14970 SmallString<8> Str;
14971 llvm::raw_svector_ostream OS(Str);
14972 OS << "__i" << Depth;
14973 IterationVarName = &S.Context.Idents.get(OS.str());
14974 }
14975 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14976 IterationVarName, SizeType,
14977 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14978 SC_None);
14979
14980 // Initialize the iteration variable to zero.
14981 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14982 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14983
14984 // Creates a reference to the iteration variable.
14985 RefBuilder IterationVarRef(IterationVar, SizeType);
14986 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14987
14988 // Create the DeclStmt that holds the iteration variable.
14989 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14990
14991 // Subscript the "from" and "to" expressions with the iteration variable.
14992 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14993 MoveCastBuilder FromIndexMove(FromIndexCopy);
14994 const ExprBuilder *FromIndex;
14995 if (Copying)
14996 FromIndex = &FromIndexCopy;
14997 else
14998 FromIndex = &FromIndexMove;
14999
15000 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15001
15002 // Build the copy/move for an individual element of the array.
15003 StmtResult Copy =
15005 ToIndex, *FromIndex, CopyingBaseSubobject,
15006 Copying, Depth + 1);
15007 // Bail out if copying fails or if we determined that we should use memcpy.
15008 if (Copy.isInvalid() || !Copy.get())
15009 return Copy;
15010
15011 // Create the comparison against the array bound.
15012 llvm::APInt Upper
15013 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15015 S.Context, IterationVarRefRVal.build(S, Loc),
15016 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15019
15020 // Create the pre-increment of the iteration variable. We can determine
15021 // whether the increment will overflow based on the value of the array
15022 // bound.
15023 Expr *Increment = UnaryOperator::Create(
15024 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15025 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15026
15027 // Construct the loop that copies all elements of this array.
15028 return S.ActOnForStmt(
15029 Loc, Loc, InitStmt,
15031 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15032}
15033
15034static StmtResult
15036 const ExprBuilder &To, const ExprBuilder &From,
15037 bool CopyingBaseSubobject, bool Copying) {
15038 // Maybe we should use a memcpy?
15039 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15040 T.isTriviallyCopyableType(S.Context))
15041 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15042
15043 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15044 CopyingBaseSubobject,
15045 Copying, 0));
15046
15047 // If we ended up picking a trivial assignment operator for an array of a
15048 // non-trivially-copyable class type, just emit a memcpy.
15049 if (!Result.isInvalid() && !Result.get())
15050 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15051
15052 return Result;
15053}
15054
15056 // Note: The following rules are largely analoguous to the copy
15057 // constructor rules. Note that virtual bases are not taken into account
15058 // for determining the argument type of the operator. Note also that
15059 // operators taking an object instead of a reference are allowed.
15060 assert(ClassDecl->needsImplicitCopyAssignment());
15061
15062 DeclaringSpecialMember DSM(*this, ClassDecl,
15064 if (DSM.isAlreadyBeingDeclared())
15065 return nullptr;
15066
15068 /*Qualifier=*/std::nullopt, ClassDecl,
15069 /*OwnsTag=*/false);
15071 if (AS != LangAS::Default)
15072 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15073 QualType RetType = Context.getLValueReferenceType(ArgType);
15074 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15075 if (Const)
15076 ArgType = ArgType.withConst();
15077
15078 ArgType = Context.getLValueReferenceType(ArgType);
15079
15081 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15082
15083 // An implicitly-declared copy assignment operator is an inline public
15084 // member of its class.
15085 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15086 SourceLocation ClassLoc = ClassDecl->getLocation();
15087 DeclarationNameInfo NameInfo(Name, ClassLoc);
15089 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15090 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15091 getCurFPFeatures().isFPConstrained(),
15092 /*isInline=*/true,
15094 SourceLocation());
15095 CopyAssignment->setAccess(AS_public);
15096 CopyAssignment->setDefaulted();
15097 CopyAssignment->setImplicit();
15098
15099 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15100
15101 if (getLangOpts().CUDA)
15102 CUDA().inferTargetForImplicitSpecialMember(
15104 /* ConstRHS */ Const,
15105 /* Diagnose */ false);
15106
15107 // Add the parameter to the operator.
15109 ClassLoc, ClassLoc,
15110 /*Id=*/nullptr, ArgType,
15111 /*TInfo=*/nullptr, SC_None,
15112 nullptr);
15113 CopyAssignment->setParams(FromParam);
15114
15115 CopyAssignment->setTrivial(
15119 : ClassDecl->hasTrivialCopyAssignment());
15120
15121 // Note that we have added this copy-assignment operator.
15122 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15123
15124 Scope *S = getScopeForContext(ClassDecl);
15126
15130 SetDeclDeleted(CopyAssignment, ClassLoc);
15131 }
15132
15133 if (S)
15135 ClassDecl->addDecl(CopyAssignment);
15136
15137 return CopyAssignment;
15138}
15139
15140/// Diagnose an implicit copy operation for a class which is odr-used, but
15141/// which is deprecated because the class has a user-declared copy constructor,
15142/// copy assignment operator, or destructor.
15144 assert(CopyOp->isImplicit());
15145
15146 CXXRecordDecl *RD = CopyOp->getParent();
15147 CXXMethodDecl *UserDeclaredOperation = nullptr;
15148
15149 if (RD->hasUserDeclaredDestructor()) {
15150 UserDeclaredOperation = RD->getDestructor();
15151 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15153 // Find any user-declared copy constructor.
15154 for (auto *I : RD->ctors()) {
15155 if (I->isCopyConstructor()) {
15156 UserDeclaredOperation = I;
15157 break;
15158 }
15159 }
15160 assert(UserDeclaredOperation);
15161 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15163 // Find any user-declared move assignment operator.
15164 for (auto *I : RD->methods()) {
15165 if (I->isCopyAssignmentOperator()) {
15166 UserDeclaredOperation = I;
15167 break;
15168 }
15169 }
15170 assert(UserDeclaredOperation);
15171 }
15172
15173 if (UserDeclaredOperation) {
15174 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15175 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15176 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15177 unsigned DiagID =
15178 (UDOIsUserProvided && UDOIsDestructor)
15179 ? diag::warn_deprecated_copy_with_user_provided_dtor
15180 : (UDOIsUserProvided && !UDOIsDestructor)
15181 ? diag::warn_deprecated_copy_with_user_provided_copy
15182 : (!UDOIsUserProvided && UDOIsDestructor)
15183 ? diag::warn_deprecated_copy_with_dtor
15184 : diag::warn_deprecated_copy;
15185 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15186 << RD << IsCopyAssignment;
15187 }
15188}
15189
15191 CXXMethodDecl *CopyAssignOperator) {
15192 assert((CopyAssignOperator->isDefaulted() &&
15193 CopyAssignOperator->isOverloadedOperator() &&
15194 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15195 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15196 !CopyAssignOperator->isDeleted()) &&
15197 "DefineImplicitCopyAssignment called for wrong function");
15198 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15199 return;
15200
15201 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15202 if (ClassDecl->isInvalidDecl()) {
15203 CopyAssignOperator->setInvalidDecl();
15204 return;
15205 }
15206
15207 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15208
15209 // The exception specification is needed because we are defining the
15210 // function.
15211 ResolveExceptionSpec(CurrentLocation,
15212 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15213
15214 // Add a context note for diagnostics produced after this point.
15215 Scope.addContextNote(CurrentLocation);
15216
15217 // C++11 [class.copy]p18:
15218 // The [definition of an implicitly declared copy assignment operator] is
15219 // deprecated if the class has a user-declared copy constructor or a
15220 // user-declared destructor.
15221 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15222 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15223
15224 // C++0x [class.copy]p30:
15225 // The implicitly-defined or explicitly-defaulted copy assignment operator
15226 // for a non-union class X performs memberwise copy assignment of its
15227 // subobjects. The direct base classes of X are assigned first, in the
15228 // order of their declaration in the base-specifier-list, and then the
15229 // immediate non-static data members of X are assigned, in the order in
15230 // which they were declared in the class definition.
15231
15232 // The statements that form the synthesized function body.
15233 SmallVector<Stmt*, 8> Statements;
15234
15235 // The parameter for the "other" object, which we are copying from.
15236 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15237 Qualifiers OtherQuals = Other->getType().getQualifiers();
15238 QualType OtherRefType = Other->getType();
15239 if (OtherRefType->isLValueReferenceType()) {
15240 OtherRefType = OtherRefType->getPointeeType();
15241 OtherQuals = OtherRefType.getQualifiers();
15242 }
15243
15244 // Our location for everything implicitly-generated.
15245 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15246 ? CopyAssignOperator->getEndLoc()
15247 : CopyAssignOperator->getLocation();
15248
15249 // Builds a DeclRefExpr for the "other" object.
15250 RefBuilder OtherRef(Other, OtherRefType);
15251
15252 // Builds the function object parameter.
15253 std::optional<ThisBuilder> This;
15254 std::optional<DerefBuilder> DerefThis;
15255 std::optional<RefBuilder> ExplicitObject;
15256 bool IsArrow = false;
15257 QualType ObjectType;
15258 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15259 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15260 if (ObjectType->isReferenceType())
15261 ObjectType = ObjectType->getPointeeType();
15262 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15263 } else {
15264 ObjectType = getCurrentThisType();
15265 This.emplace();
15266 DerefThis.emplace(*This);
15267 IsArrow = !LangOpts.HLSL;
15268 }
15269 ExprBuilder &ObjectParameter =
15270 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15271 : static_cast<ExprBuilder &>(*This);
15272
15273 // Assign base classes.
15274 bool Invalid = false;
15275 for (auto &Base : ClassDecl->bases()) {
15276 // Form the assignment:
15277 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15278 QualType BaseType = Base.getType().getUnqualifiedType();
15279 if (!BaseType->isRecordType()) {
15280 Invalid = true;
15281 continue;
15282 }
15283
15284 CXXCastPath BasePath;
15285 BasePath.push_back(&Base);
15286
15287 // Construct the "from" expression, which is an implicit cast to the
15288 // appropriately-qualified base type.
15289 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15290 VK_LValue, BasePath);
15291
15292 // Dereference "this".
15293 CastBuilder To(
15294 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15295 : static_cast<ExprBuilder &>(*DerefThis),
15296 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15297 VK_LValue, BasePath);
15298
15299 // Build the copy.
15300 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15301 To, From,
15302 /*CopyingBaseSubobject=*/true,
15303 /*Copying=*/true);
15304 if (Copy.isInvalid()) {
15305 CopyAssignOperator->setInvalidDecl();
15306 return;
15307 }
15308
15309 // Success! Record the copy.
15310 Statements.push_back(Copy.getAs<Expr>());
15311 }
15312
15313 // Assign non-static members.
15314 for (auto *Field : ClassDecl->fields()) {
15315 // FIXME: We should form some kind of AST representation for the implied
15316 // memcpy in a union copy operation.
15317 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15318 continue;
15319
15320 if (Field->isInvalidDecl()) {
15321 Invalid = true;
15322 continue;
15323 }
15324
15325 // Check for members of reference type; we can't copy those.
15326 if (Field->getType()->isReferenceType()) {
15327 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15328 << Context.getCanonicalTagType(ClassDecl) << 0
15329 << Field->getDeclName();
15330 Diag(Field->getLocation(), diag::note_declared_at);
15331 Invalid = true;
15332 continue;
15333 }
15334
15335 // Check for members of const-qualified, non-class type.
15336 QualType BaseType = Context.getBaseElementType(Field->getType());
15337 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15338 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15339 << Context.getCanonicalTagType(ClassDecl) << 1
15340 << Field->getDeclName();
15341 Diag(Field->getLocation(), diag::note_declared_at);
15342 Invalid = true;
15343 continue;
15344 }
15345
15346 // Suppress assigning zero-width bitfields.
15347 if (Field->isZeroLengthBitField())
15348 continue;
15349
15350 QualType FieldType = Field->getType().getNonReferenceType();
15351 if (FieldType->isIncompleteArrayType()) {
15352 assert(ClassDecl->hasFlexibleArrayMember() &&
15353 "Incomplete array type is not valid");
15354 continue;
15355 }
15356
15357 // Build references to the field in the object we're copying from and to.
15358 CXXScopeSpec SS; // Intentionally empty
15359 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15361 MemberLookup.addDecl(Field);
15362 MemberLookup.resolveKind();
15363
15364 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15365 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15366 // Build the copy of this field.
15367 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15368 To, From,
15369 /*CopyingBaseSubobject=*/false,
15370 /*Copying=*/true);
15371 if (Copy.isInvalid()) {
15372 CopyAssignOperator->setInvalidDecl();
15373 return;
15374 }
15375
15376 // Success! Record the copy.
15377 Statements.push_back(Copy.getAs<Stmt>());
15378 }
15379
15380 if (!Invalid) {
15381 // Add a "return *this;"
15382 Expr *ThisExpr =
15383 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15384 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15385 : static_cast<ExprBuilder &>(*DerefThis))
15386 .build(*this, Loc);
15387 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15388 if (Return.isInvalid())
15389 Invalid = true;
15390 else
15391 Statements.push_back(Return.getAs<Stmt>());
15392 }
15393
15394 if (Invalid) {
15395 CopyAssignOperator->setInvalidDecl();
15396 return;
15397 }
15398
15399 StmtResult Body;
15400 {
15401 CompoundScopeRAII CompoundScope(*this);
15402 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15403 /*isStmtExpr=*/false);
15404 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15405 }
15406 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15407 CopyAssignOperator->markUsed(Context);
15408
15410 L->CompletedImplicitDefinition(CopyAssignOperator);
15411 }
15412}
15413
15415 assert(ClassDecl->needsImplicitMoveAssignment());
15416
15417 DeclaringSpecialMember DSM(*this, ClassDecl,
15419 if (DSM.isAlreadyBeingDeclared())
15420 return nullptr;
15421
15422 // Note: The following rules are largely analoguous to the move
15423 // constructor rules.
15424
15426 /*Qualifier=*/std::nullopt, ClassDecl,
15427 /*OwnsTag=*/false);
15429 if (AS != LangAS::Default)
15430 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15431 QualType RetType = Context.getLValueReferenceType(ArgType);
15432 ArgType = Context.getRValueReferenceType(ArgType);
15433
15435 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15436
15437 // An implicitly-declared move assignment operator is an inline public
15438 // member of its class.
15439 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15440 SourceLocation ClassLoc = ClassDecl->getLocation();
15441 DeclarationNameInfo NameInfo(Name, ClassLoc);
15443 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15444 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15445 getCurFPFeatures().isFPConstrained(),
15446 /*isInline=*/true,
15448 SourceLocation());
15449 MoveAssignment->setAccess(AS_public);
15450 MoveAssignment->setDefaulted();
15451 MoveAssignment->setImplicit();
15452
15453 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15454
15455 if (getLangOpts().CUDA)
15456 CUDA().inferTargetForImplicitSpecialMember(
15458 /* ConstRHS */ false,
15459 /* Diagnose */ false);
15460
15461 // Add the parameter to the operator.
15463 ClassLoc, ClassLoc,
15464 /*Id=*/nullptr, ArgType,
15465 /*TInfo=*/nullptr, SC_None,
15466 nullptr);
15467 MoveAssignment->setParams(FromParam);
15468
15469 MoveAssignment->setTrivial(
15473 : ClassDecl->hasTrivialMoveAssignment());
15474
15475 // Note that we have added this copy-assignment operator.
15476 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15477
15478 Scope *S = getScopeForContext(ClassDecl);
15480
15484 SetDeclDeleted(MoveAssignment, ClassLoc);
15485 }
15486
15487 if (S)
15489 ClassDecl->addDecl(MoveAssignment);
15490
15491 return MoveAssignment;
15492}
15493
15494/// Check if we're implicitly defining a move assignment operator for a class
15495/// with virtual bases. Such a move assignment might move-assign the virtual
15496/// base multiple times.
15498 SourceLocation CurrentLocation) {
15499 assert(!Class->isDependentContext() && "should not define dependent move");
15500
15501 // Only a virtual base could get implicitly move-assigned multiple times.
15502 // Only a non-trivial move assignment can observe this. We only want to
15503 // diagnose if we implicitly define an assignment operator that assigns
15504 // two base classes, both of which move-assign the same virtual base.
15505 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15506 Class->getNumBases() < 2)
15507 return;
15508
15510 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15511 VBaseMap VBases;
15512
15513 for (auto &BI : Class->bases()) {
15514 Worklist.push_back(&BI);
15515 while (!Worklist.empty()) {
15516 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15517 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15518
15519 // If the base has no non-trivial move assignment operators,
15520 // we don't care about moves from it.
15521 if (!Base->hasNonTrivialMoveAssignment())
15522 continue;
15523
15524 // If there's nothing virtual here, skip it.
15525 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15526 continue;
15527
15528 // If we're not actually going to call a move assignment for this base,
15529 // or the selected move assignment is trivial, skip it.
15532 /*ConstArg*/ false, /*VolatileArg*/ false,
15533 /*RValueThis*/ true, /*ConstThis*/ false,
15534 /*VolatileThis*/ false);
15535 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15537 continue;
15538
15539 if (BaseSpec->isVirtual()) {
15540 // We're going to move-assign this virtual base, and its move
15541 // assignment operator is not trivial. If this can happen for
15542 // multiple distinct direct bases of Class, diagnose it. (If it
15543 // only happens in one base, we'll diagnose it when synthesizing
15544 // that base class's move assignment operator.)
15545 CXXBaseSpecifier *&Existing =
15546 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15547 .first->second;
15548 if (Existing && Existing != &BI) {
15549 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15550 << Class << Base;
15551 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15552 << (Base->getCanonicalDecl() ==
15554 << Base << Existing->getType() << Existing->getSourceRange();
15555 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15556 << (Base->getCanonicalDecl() ==
15557 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15558 << Base << BI.getType() << BaseSpec->getSourceRange();
15559
15560 // Only diagnose each vbase once.
15561 Existing = nullptr;
15562 }
15563 } else {
15564 // Only walk over bases that have defaulted move assignment operators.
15565 // We assume that any user-provided move assignment operator handles
15566 // the multiple-moves-of-vbase case itself somehow.
15567 if (!SMOR.getMethod()->isDefaulted())
15568 continue;
15569
15570 // We're going to move the base classes of Base. Add them to the list.
15571 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15572 }
15573 }
15574 }
15575}
15576
15578 CXXMethodDecl *MoveAssignOperator) {
15579 assert((MoveAssignOperator->isDefaulted() &&
15580 MoveAssignOperator->isOverloadedOperator() &&
15581 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15582 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15583 !MoveAssignOperator->isDeleted()) &&
15584 "DefineImplicitMoveAssignment called for wrong function");
15585 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15586 return;
15587
15588 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15589 if (ClassDecl->isInvalidDecl()) {
15590 MoveAssignOperator->setInvalidDecl();
15591 return;
15592 }
15593
15594 // C++0x [class.copy]p28:
15595 // The implicitly-defined or move assignment operator for a non-union class
15596 // X performs memberwise move assignment of its subobjects. The direct base
15597 // classes of X are assigned first, in the order of their declaration in the
15598 // base-specifier-list, and then the immediate non-static data members of X
15599 // are assigned, in the order in which they were declared in the class
15600 // definition.
15601
15602 // Issue a warning if our implicit move assignment operator will move
15603 // from a virtual base more than once.
15604 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15605
15606 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15607
15608 // The exception specification is needed because we are defining the
15609 // function.
15610 ResolveExceptionSpec(CurrentLocation,
15611 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15612
15613 // Add a context note for diagnostics produced after this point.
15614 Scope.addContextNote(CurrentLocation);
15615
15616 // The statements that form the synthesized function body.
15617 SmallVector<Stmt*, 8> Statements;
15618
15619 // The parameter for the "other" object, which we are move from.
15620 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15621 QualType OtherRefType =
15622 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15623
15624 // Our location for everything implicitly-generated.
15625 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15626 ? MoveAssignOperator->getEndLoc()
15627 : MoveAssignOperator->getLocation();
15628
15629 // Builds a reference to the "other" object.
15630 RefBuilder OtherRef(Other, OtherRefType);
15631 // Cast to rvalue.
15632 MoveCastBuilder MoveOther(OtherRef);
15633
15634 // Builds the function object parameter.
15635 std::optional<ThisBuilder> This;
15636 std::optional<DerefBuilder> DerefThis;
15637 std::optional<RefBuilder> ExplicitObject;
15638 QualType ObjectType;
15639 bool IsArrow = false;
15640 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15641 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15642 if (ObjectType->isReferenceType())
15643 ObjectType = ObjectType->getPointeeType();
15644 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15645 } else {
15646 ObjectType = getCurrentThisType();
15647 This.emplace();
15648 DerefThis.emplace(*This);
15649 IsArrow = !getLangOpts().HLSL;
15650 }
15651 ExprBuilder &ObjectParameter =
15652 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15653
15654 // Assign base classes.
15655 bool Invalid = false;
15656 for (auto &Base : ClassDecl->bases()) {
15657 // C++11 [class.copy]p28:
15658 // It is unspecified whether subobjects representing virtual base classes
15659 // are assigned more than once by the implicitly-defined copy assignment
15660 // operator.
15661 // FIXME: Do not assign to a vbase that will be assigned by some other base
15662 // class. For a move-assignment, this can result in the vbase being moved
15663 // multiple times.
15664
15665 // Form the assignment:
15666 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15667 QualType BaseType = Base.getType().getUnqualifiedType();
15668 if (!BaseType->isRecordType()) {
15669 Invalid = true;
15670 continue;
15671 }
15672
15673 CXXCastPath BasePath;
15674 BasePath.push_back(&Base);
15675
15676 // Construct the "from" expression, which is an implicit cast to the
15677 // appropriately-qualified base type.
15678 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15679
15680 // Implicitly cast "this" to the appropriately-qualified base type.
15681 // Dereference "this".
15682 CastBuilder To(
15683 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15684 : static_cast<ExprBuilder &>(*DerefThis),
15685 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15686 VK_LValue, BasePath);
15687
15688 // Build the move.
15689 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15690 To, From,
15691 /*CopyingBaseSubobject=*/true,
15692 /*Copying=*/false);
15693 if (Move.isInvalid()) {
15694 MoveAssignOperator->setInvalidDecl();
15695 return;
15696 }
15697
15698 // Success! Record the move.
15699 Statements.push_back(Move.getAs<Expr>());
15700 }
15701
15702 // Assign non-static members.
15703 for (auto *Field : ClassDecl->fields()) {
15704 // FIXME: We should form some kind of AST representation for the implied
15705 // memcpy in a union copy operation.
15706 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15707 continue;
15708
15709 if (Field->isInvalidDecl()) {
15710 Invalid = true;
15711 continue;
15712 }
15713
15714 // Check for members of reference type; we can't move those.
15715 if (Field->getType()->isReferenceType()) {
15716 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15717 << Context.getCanonicalTagType(ClassDecl) << 0
15718 << Field->getDeclName();
15719 Diag(Field->getLocation(), diag::note_declared_at);
15720 Invalid = true;
15721 continue;
15722 }
15723
15724 // Check for members of const-qualified, non-class type.
15725 QualType BaseType = Context.getBaseElementType(Field->getType());
15726 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15727 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15728 << Context.getCanonicalTagType(ClassDecl) << 1
15729 << Field->getDeclName();
15730 Diag(Field->getLocation(), diag::note_declared_at);
15731 Invalid = true;
15732 continue;
15733 }
15734
15735 // Suppress assigning zero-width bitfields.
15736 if (Field->isZeroLengthBitField())
15737 continue;
15738
15739 QualType FieldType = Field->getType().getNonReferenceType();
15740 if (FieldType->isIncompleteArrayType()) {
15741 assert(ClassDecl->hasFlexibleArrayMember() &&
15742 "Incomplete array type is not valid");
15743 continue;
15744 }
15745
15746 // Build references to the field in the object we're copying from and to.
15747 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15749 MemberLookup.addDecl(Field);
15750 MemberLookup.resolveKind();
15751 MemberBuilder From(MoveOther, OtherRefType,
15752 /*IsArrow=*/false, MemberLookup);
15753 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15754
15755 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15756 "Member reference with rvalue base must be rvalue except for reference "
15757 "members, which aren't allowed for move assignment.");
15758
15759 // Build the move of this field.
15760 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15761 To, From,
15762 /*CopyingBaseSubobject=*/false,
15763 /*Copying=*/false);
15764 if (Move.isInvalid()) {
15765 MoveAssignOperator->setInvalidDecl();
15766 return;
15767 }
15768
15769 // Success! Record the copy.
15770 Statements.push_back(Move.getAs<Stmt>());
15771 }
15772
15773 if (!Invalid) {
15774 // Add a "return *this;"
15775 Expr *ThisExpr =
15776 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15777 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15778 : static_cast<ExprBuilder &>(*DerefThis))
15779 .build(*this, Loc);
15780
15781 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15782 if (Return.isInvalid())
15783 Invalid = true;
15784 else
15785 Statements.push_back(Return.getAs<Stmt>());
15786 }
15787
15788 if (Invalid) {
15789 MoveAssignOperator->setInvalidDecl();
15790 return;
15791 }
15792
15793 StmtResult Body;
15794 {
15795 CompoundScopeRAII CompoundScope(*this);
15796 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15797 /*isStmtExpr=*/false);
15798 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15799 }
15800 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15801 MoveAssignOperator->markUsed(Context);
15802
15804 L->CompletedImplicitDefinition(MoveAssignOperator);
15805 }
15806}
15807
15809 CXXRecordDecl *ClassDecl) {
15810 // C++ [class.copy]p4:
15811 // If the class definition does not explicitly declare a copy
15812 // constructor, one is declared implicitly.
15813 assert(ClassDecl->needsImplicitCopyConstructor());
15814
15815 DeclaringSpecialMember DSM(*this, ClassDecl,
15817 if (DSM.isAlreadyBeingDeclared())
15818 return nullptr;
15819
15820 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15821 /*Qualifier=*/std::nullopt, ClassDecl,
15822 /*OwnsTag=*/false);
15823 QualType ArgType = ClassType;
15824 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15825 if (Const)
15826 ArgType = ArgType.withConst();
15827
15829 if (AS != LangAS::Default)
15830 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15831
15832 ArgType = Context.getLValueReferenceType(ArgType);
15833
15835 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15836
15837 DeclarationName Name
15838 = Context.DeclarationNames.getCXXConstructorName(
15839 Context.getCanonicalType(ClassType));
15840 SourceLocation ClassLoc = ClassDecl->getLocation();
15841 DeclarationNameInfo NameInfo(Name, ClassLoc);
15842
15843 // An implicitly-declared copy constructor is an inline public
15844 // member of its class.
15846 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15847 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15848 /*isInline=*/true,
15849 /*isImplicitlyDeclared=*/true,
15852 CopyConstructor->setAccess(AS_public);
15853 CopyConstructor->setDefaulted();
15854
15855 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15856
15857 if (getLangOpts().CUDA)
15858 CUDA().inferTargetForImplicitSpecialMember(
15860 /* ConstRHS */ Const,
15861 /* Diagnose */ false);
15862
15863 // During template instantiation of special member functions we need a
15864 // reliable TypeSourceInfo for the parameter types in order to allow functions
15865 // to be substituted.
15866 TypeSourceInfo *TSI = nullptr;
15867 if (inTemplateInstantiation() && ClassDecl->isLambda())
15868 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15869
15870 // Add the parameter to the constructor.
15871 ParmVarDecl *FromParam =
15872 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15873 /*IdentifierInfo=*/nullptr, ArgType,
15874 /*TInfo=*/TSI, SC_None, nullptr);
15875 CopyConstructor->setParams(FromParam);
15876
15877 CopyConstructor->setTrivial(
15881 : ClassDecl->hasTrivialCopyConstructor());
15882
15883 CopyConstructor->setTrivialForCall(
15884 ClassDecl->hasAttr<TrivialABIAttr>() ||
15889 : ClassDecl->hasTrivialCopyConstructorForCall()));
15890
15891 // Note that we have declared this constructor.
15892 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15893
15894 Scope *S = getScopeForContext(ClassDecl);
15896
15901 }
15902
15903 if (S)
15905 ClassDecl->addDecl(CopyConstructor);
15906
15907 return CopyConstructor;
15908}
15909
15912 assert((CopyConstructor->isDefaulted() &&
15913 CopyConstructor->isCopyConstructor() &&
15914 !CopyConstructor->doesThisDeclarationHaveABody() &&
15915 !CopyConstructor->isDeleted()) &&
15916 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15917 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15918 return;
15919
15920 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15921 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15922
15924
15925 // The exception specification is needed because we are defining the
15926 // function.
15927 ResolveExceptionSpec(CurrentLocation,
15928 CopyConstructor->getType()->castAs<FunctionProtoType>());
15929 MarkVTableUsed(CurrentLocation, ClassDecl);
15930
15931 // Add a context note for diagnostics produced after this point.
15932 Scope.addContextNote(CurrentLocation);
15933
15934 // C++11 [class.copy]p7:
15935 // The [definition of an implicitly declared copy constructor] is
15936 // deprecated if the class has a user-declared copy assignment operator
15937 // or a user-declared destructor.
15938 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15940
15941 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15942 CopyConstructor->setInvalidDecl();
15943 } else {
15944 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15945 ? CopyConstructor->getEndLoc()
15946 : CopyConstructor->getLocation();
15947 Sema::CompoundScopeRAII CompoundScope(*this);
15948 CopyConstructor->setBody(
15949 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15950 CopyConstructor->markUsed(Context);
15951 }
15952
15954 L->CompletedImplicitDefinition(CopyConstructor);
15955 }
15956}
15957
15959 CXXRecordDecl *ClassDecl) {
15960 assert(ClassDecl->needsImplicitMoveConstructor());
15961
15962 DeclaringSpecialMember DSM(*this, ClassDecl,
15964 if (DSM.isAlreadyBeingDeclared())
15965 return nullptr;
15966
15967 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15968 /*Qualifier=*/std::nullopt, ClassDecl,
15969 /*OwnsTag=*/false);
15970
15971 QualType ArgType = ClassType;
15973 if (AS != LangAS::Default)
15974 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15975 ArgType = Context.getRValueReferenceType(ArgType);
15976
15978 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15979
15980 DeclarationName Name
15981 = Context.DeclarationNames.getCXXConstructorName(
15982 Context.getCanonicalType(ClassType));
15983 SourceLocation ClassLoc = ClassDecl->getLocation();
15984 DeclarationNameInfo NameInfo(Name, ClassLoc);
15985
15986 // C++11 [class.copy]p11:
15987 // An implicitly-declared copy/move constructor is an inline public
15988 // member of its class.
15990 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15991 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15992 /*isInline=*/true,
15993 /*isImplicitlyDeclared=*/true,
15996 MoveConstructor->setAccess(AS_public);
15997 MoveConstructor->setDefaulted();
15998
15999 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16000
16001 if (getLangOpts().CUDA)
16002 CUDA().inferTargetForImplicitSpecialMember(
16004 /* ConstRHS */ false,
16005 /* Diagnose */ false);
16006
16007 // Add the parameter to the constructor.
16009 ClassLoc, ClassLoc,
16010 /*IdentifierInfo=*/nullptr,
16011 ArgType, /*TInfo=*/nullptr,
16012 SC_None, nullptr);
16013 MoveConstructor->setParams(FromParam);
16014
16015 MoveConstructor->setTrivial(
16019 : ClassDecl->hasTrivialMoveConstructor());
16020
16021 MoveConstructor->setTrivialForCall(
16022 ClassDecl->hasAttr<TrivialABIAttr>() ||
16027 : ClassDecl->hasTrivialMoveConstructorForCall()));
16028
16029 // Note that we have declared this constructor.
16030 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16031
16032 Scope *S = getScopeForContext(ClassDecl);
16034
16039 }
16040
16041 if (S)
16043 ClassDecl->addDecl(MoveConstructor);
16044
16045 return MoveConstructor;
16046}
16047
16050 assert((MoveConstructor->isDefaulted() &&
16051 MoveConstructor->isMoveConstructor() &&
16052 !MoveConstructor->doesThisDeclarationHaveABody() &&
16053 !MoveConstructor->isDeleted()) &&
16054 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16055 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16056 return;
16057
16058 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16059 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16060
16062
16063 // The exception specification is needed because we are defining the
16064 // function.
16065 ResolveExceptionSpec(CurrentLocation,
16066 MoveConstructor->getType()->castAs<FunctionProtoType>());
16067 MarkVTableUsed(CurrentLocation, ClassDecl);
16068
16069 // Add a context note for diagnostics produced after this point.
16070 Scope.addContextNote(CurrentLocation);
16071
16072 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16073 MoveConstructor->setInvalidDecl();
16074 } else {
16075 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16076 ? MoveConstructor->getEndLoc()
16077 : MoveConstructor->getLocation();
16078 Sema::CompoundScopeRAII CompoundScope(*this);
16079 MoveConstructor->setBody(
16080 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16081 MoveConstructor->markUsed(Context);
16082 }
16083
16085 L->CompletedImplicitDefinition(MoveConstructor);
16086 }
16087}
16088
16090 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16091}
16092
16094 SourceLocation CurrentLocation,
16095 CXXConversionDecl *Conv) {
16096 SynthesizedFunctionScope Scope(*this, Conv);
16097 assert(!Conv->getReturnType()->isUndeducedType());
16098
16099 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16100 CallingConv CC =
16101 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16102
16103 CXXRecordDecl *Lambda = Conv->getParent();
16104 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16105 FunctionDecl *Invoker =
16106 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16107 ? CallOp
16108 : Lambda->getLambdaStaticInvoker(CC);
16109
16110 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16112 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16113 if (!CallOp)
16114 return;
16115
16116 if (CallOp != Invoker) {
16118 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16119 CurrentLocation);
16120 if (!Invoker)
16121 return;
16122 }
16123 }
16124
16125 if (CallOp->isInvalidDecl())
16126 return;
16127
16128 // Mark the call operator referenced (and add to pending instantiations
16129 // if necessary).
16130 // For both the conversion and static-invoker template specializations
16131 // we construct their body's in this function, so no need to add them
16132 // to the PendingInstantiations.
16133 MarkFunctionReferenced(CurrentLocation, CallOp);
16134
16135 if (Invoker != CallOp) {
16136 // Fill in the __invoke function with a dummy implementation. IR generation
16137 // will fill in the actual details. Update its type in case it contained
16138 // an 'auto'.
16139 Invoker->markUsed(Context);
16140 Invoker->setReferenced();
16141 Invoker->setType(Conv->getReturnType()->getPointeeType());
16142 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16143 }
16144
16145 // Construct the body of the conversion function { return __invoke; }.
16146 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16147 Conv->getLocation());
16148 assert(FunctionRef && "Can't refer to __invoke function?");
16149 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16151 Conv->getLocation(), Conv->getLocation()));
16152 Conv->markUsed(Context);
16153 Conv->setReferenced();
16154
16156 L->CompletedImplicitDefinition(Conv);
16157 if (Invoker != CallOp)
16158 L->CompletedImplicitDefinition(Invoker);
16159 }
16160}
16161
16163 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16164 assert(!Conv->getParent()->isGenericLambda());
16165
16166 SynthesizedFunctionScope Scope(*this, Conv);
16167
16168 // Copy-initialize the lambda object as needed to capture it.
16169 Expr *This = ActOnCXXThis(CurrentLocation).get();
16170 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16171
16172 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16173 Conv->getLocation(),
16174 Conv, DerefThis);
16175
16176 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16177 // behavior. Note that only the general conversion function does this
16178 // (since it's unusable otherwise); in the case where we inline the
16179 // block literal, it has block literal lifetime semantics.
16180 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16181 BuildBlock = ImplicitCastExpr::Create(
16182 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16183 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16184
16185 if (BuildBlock.isInvalid()) {
16186 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16187 Conv->setInvalidDecl();
16188 return;
16189 }
16190
16191 // Create the return statement that returns the block from the conversion
16192 // function.
16193 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16194 if (Return.isInvalid()) {
16195 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16196 Conv->setInvalidDecl();
16197 return;
16198 }
16199
16200 // Set the body of the conversion function.
16201 Stmt *ReturnS = Return.get();
16203 Conv->getLocation(), Conv->getLocation()));
16204 Conv->markUsed(Context);
16205
16206 // We're done; notify the mutation listener, if any.
16208 L->CompletedImplicitDefinition(Conv);
16209 }
16210}
16211
16212/// Determine whether the given list arguments contains exactly one
16213/// "real" (non-default) argument.
16215 switch (Args.size()) {
16216 case 0:
16217 return false;
16218
16219 default:
16220 if (!Args[1]->isDefaultArgument())
16221 return false;
16222
16223 [[fallthrough]];
16224 case 1:
16225 return !Args[0]->isDefaultArgument();
16226 }
16227
16228 return false;
16229}
16230
16232 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16234 bool HadMultipleCandidates, bool IsListInitialization,
16235 bool IsStdInitListInitialization, bool RequiresZeroInit,
16236 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16237 bool Elidable = false;
16238
16239 // C++0x [class.copy]p34:
16240 // When certain criteria are met, an implementation is allowed to
16241 // omit the copy/move construction of a class object, even if the
16242 // copy/move constructor and/or destructor for the object have
16243 // side effects. [...]
16244 // - when a temporary class object that has not been bound to a
16245 // reference (12.2) would be copied/moved to a class object
16246 // with the same cv-unqualified type, the copy/move operation
16247 // can be omitted by constructing the temporary object
16248 // directly into the target of the omitted copy/move
16249 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16250 // FIXME: Converting constructors should also be accepted.
16251 // But to fix this, the logic that digs down into a CXXConstructExpr
16252 // to find the source object needs to handle it.
16253 // Right now it assumes the source object is passed directly as the
16254 // first argument.
16255 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16256 Expr *SubExpr = ExprArgs[0];
16257 // FIXME: Per above, this is also incorrect if we want to accept
16258 // converting constructors, as isTemporaryObject will
16259 // reject temporaries with different type from the
16260 // CXXRecord itself.
16261 Elidable = SubExpr->isTemporaryObject(
16263 }
16264
16265 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16266 FoundDecl, Constructor,
16267 Elidable, ExprArgs, HadMultipleCandidates,
16268 IsListInitialization,
16269 IsStdInitListInitialization, RequiresZeroInit,
16270 ConstructKind, ParenRange);
16271}
16272
16274 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16275 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16276 bool HadMultipleCandidates, bool IsListInitialization,
16277 bool IsStdInitListInitialization, bool RequiresZeroInit,
16278 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16279 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16280 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16281 // The only way to get here is if we did overload resolution to find the
16282 // shadow decl, so we don't need to worry about re-checking the trailing
16283 // requires clause.
16284 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16285 return ExprError();
16286 }
16287
16288 return BuildCXXConstructExpr(
16289 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16290 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16291 RequiresZeroInit, ConstructKind, ParenRange);
16292}
16293
16294/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16295/// including handling of its default argument expressions.
16297 SourceLocation ConstructLoc, QualType DeclInitType,
16298 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16299 bool HadMultipleCandidates, bool IsListInitialization,
16300 bool IsStdInitListInitialization, bool RequiresZeroInit,
16301 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16302 assert(declaresSameEntity(
16303 Constructor->getParent(),
16304 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16305 "given constructor for wrong type");
16306 MarkFunctionReferenced(ConstructLoc, Constructor);
16307 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16308 return ExprError();
16309
16312 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16313 HadMultipleCandidates, IsListInitialization,
16314 IsStdInitListInitialization, RequiresZeroInit,
16315 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16316 Constructor);
16317}
16318
16320 if (VD->isInvalidDecl()) return;
16321 // If initializing the variable failed, don't also diagnose problems with
16322 // the destructor, they're likely related.
16323 if (VD->getInit() && VD->getInit()->containsErrors())
16324 return;
16325
16326 ClassDecl = ClassDecl->getDefinitionOrSelf();
16327 if (ClassDecl->isInvalidDecl()) return;
16328 if (ClassDecl->hasIrrelevantDestructor()) return;
16329 if (ClassDecl->isDependentContext()) return;
16330
16331 if (VD->isNoDestroy(getASTContext()))
16332 return;
16333
16335 // The result of `LookupDestructor` might be nullptr if the destructor is
16336 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16337 // will not be selected by `CXXRecordDecl::getDestructor()`.
16338 if (!Destructor)
16339 return;
16340 // If this is an array, we'll require the destructor during initialization, so
16341 // we can skip over this. We still want to emit exit-time destructor warnings
16342 // though.
16343 if (!VD->getType()->isArrayType()) {
16346 PDiag(diag::err_access_dtor_var)
16347 << VD->getDeclName() << VD->getType());
16349 }
16350
16351 if (Destructor->isTrivial()) return;
16352
16353 // If the destructor is constexpr, check whether the variable has constant
16354 // destruction now.
16355 if (Destructor->isConstexpr()) {
16356 bool HasConstantInit = false;
16357 if (VD->getInit() && !VD->getInit()->isValueDependent())
16358 HasConstantInit = VD->evaluateValue();
16360 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16361 HasConstantInit) {
16362 Diag(VD->getLocation(),
16363 diag::err_constexpr_var_requires_const_destruction) << VD;
16364 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16365 Diag(Notes[I].first, Notes[I].second);
16366 }
16367 }
16368
16369 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16370 return;
16371
16372 // Emit warning for non-trivial dtor in global scope (a real global,
16373 // class-static, function-static).
16374 if (!VD->hasAttr<AlwaysDestroyAttr>())
16375 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16376
16377 // TODO: this should be re-enabled for static locals by !CXAAtExit
16378 if (!VD->isStaticLocal())
16379 Diag(VD->getLocation(), diag::warn_global_destructor);
16380}
16381
16383 QualType DeclInitType, MultiExprArg ArgsPtr,
16384 SourceLocation Loc,
16385 SmallVectorImpl<Expr *> &ConvertedArgs,
16386 bool AllowExplicit,
16387 bool IsListInitialization) {
16388 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16389 unsigned NumArgs = ArgsPtr.size();
16390 Expr **Args = ArgsPtr.data();
16391
16392 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16393 unsigned NumParams = Proto->getNumParams();
16394
16395 // If too few arguments are available, we'll fill in the rest with defaults.
16396 if (NumArgs < NumParams)
16397 ConvertedArgs.reserve(NumParams);
16398 else
16399 ConvertedArgs.reserve(NumArgs);
16400
16401 VariadicCallType CallType = Proto->isVariadic()
16404 SmallVector<Expr *, 8> AllArgs;
16406 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16407 CallType, AllowExplicit, IsListInitialization);
16408 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16409
16410 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16411
16412 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16413 Proto, Loc);
16414
16415 return Invalid;
16416}
16417
16419 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16420 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16421}
16422
16425 QualType DeallocType, SourceLocation Loc) {
16426 if (DeallocType.isNull())
16427 return nullptr;
16428
16429 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16430 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16431 return nullptr;
16432
16433 if (FnDecl->isVariadic())
16434 return nullptr;
16435
16436 unsigned NumParams = FnDecl->getNumParams();
16437 constexpr unsigned RequiredParameterCount =
16439 // A usual deallocation function has no placement parameters
16440 if (NumParams != RequiredParameterCount)
16441 return nullptr;
16442
16443 // A type aware allocation is only usual if the only dependent parameter is
16444 // the first parameter.
16445 if (llvm::any_of(FnDecl->parameters().drop_front(),
16446 [](const ParmVarDecl *ParamDecl) {
16447 return ParamDecl->getType()->isDependentType();
16448 }))
16449 return nullptr;
16450
16451 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16452 if (SpecializedTypeIdentity.isNull())
16453 return nullptr;
16454
16456 ArgTypes.reserve(NumParams);
16457
16458 // The first parameter to a type aware operator delete is by definition the
16459 // type-identity argument, so we explicitly set this to the target
16460 // type-identity type, the remaining usual parameters should then simply match
16461 // the type declared in the function template.
16462 ArgTypes.push_back(SpecializedTypeIdentity);
16463 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16464 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16465
16467 QualType ExpectedFunctionType =
16468 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16471 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16473 return nullptr;
16474 return Result;
16475}
16476
16477static inline bool
16479 const FunctionDecl *FnDecl) {
16480 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16481 if (isa<NamespaceDecl>(DC)) {
16482 return SemaRef.Diag(FnDecl->getLocation(),
16483 diag::err_operator_new_delete_declared_in_namespace)
16484 << FnDecl->getDeclName();
16485 }
16486
16487 if (isa<TranslationUnitDecl>(DC) &&
16488 FnDecl->getStorageClass() == SC_Static) {
16489 return SemaRef.Diag(FnDecl->getLocation(),
16490 diag::err_operator_new_delete_declared_static)
16491 << FnDecl->getDeclName();
16492 }
16493
16494 return false;
16495}
16496
16498 const PointerType *PtrTy) {
16499 auto &Ctx = SemaRef.Context;
16500 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16501 PtrQuals.removeAddressSpace();
16503 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16504}
16505
16507
16509 const FunctionDecl *FD,
16510 bool *WasMalformed) {
16511 const Decl *MalformedDecl = nullptr;
16512 if (FD->getNumParams() > 0 &&
16513 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16514 /*TypeArgument=*/nullptr, &MalformedDecl))
16515 return true;
16516
16517 if (!MalformedDecl)
16518 return false;
16519
16520 if (WasMalformed)
16521 *WasMalformed = true;
16522
16523 return true;
16524}
16525
16527 auto *RD = Type->getAsCXXRecordDecl();
16528 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16529 RD->getIdentifier()->isStr("destroying_delete_t");
16530}
16531
16533 const FunctionDecl *FD) {
16534 // C++ P0722:
16535 // Within a class C, a single object deallocation function with signature
16536 // (T, std::destroying_delete_t, <more params>)
16537 // is a destroying operator delete.
16538 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16539 SemaRef, FD, /*WasMalformed=*/nullptr);
16540 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16541 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16542 FD->getNumParams() > DestroyingDeleteIdx &&
16543 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16544}
16545
16547 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16548 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16549 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16550 auto NormalizeType = [&SemaRef](QualType T) {
16551 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16552 // The operator is valid on any address space for OpenCL.
16553 // Drop address space from actual and expected result types.
16554 if (const auto PtrTy = T->template getAs<PointerType>())
16555 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16556 }
16557 return SemaRef.Context.getCanonicalType(T);
16558 };
16559
16560 const unsigned NumParams = FnDecl->getNumParams();
16561 unsigned FirstNonTypeParam = 0;
16562 bool MalformedTypeIdentity = false;
16563 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16564 SemaRef, FnDecl, &MalformedTypeIdentity);
16565 unsigned MinimumMandatoryArgumentCount = 1;
16566 unsigned SizeParameterIndex = 0;
16567 if (IsPotentiallyTypeAware) {
16568 // We don't emit this diagnosis for template instantiations as we will
16569 // have already emitted it for the original template declaration.
16570 if (!FnDecl->isTemplateInstantiation())
16571 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16572
16573 if (OperatorKind == AllocationOperatorKind::New) {
16574 SizeParameterIndex = 1;
16575 MinimumMandatoryArgumentCount =
16577 } else {
16578 SizeParameterIndex = 2;
16579 MinimumMandatoryArgumentCount =
16581 }
16582 FirstNonTypeParam = 1;
16583 }
16584
16585 bool IsPotentiallyDestroyingDelete =
16587
16588 if (IsPotentiallyDestroyingDelete) {
16589 ++MinimumMandatoryArgumentCount;
16590 ++SizeParameterIndex;
16591 }
16592
16593 if (NumParams < MinimumMandatoryArgumentCount)
16594 return SemaRef.Diag(FnDecl->getLocation(),
16595 diag::err_operator_new_delete_too_few_parameters)
16596 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16597 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16598
16599 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16600 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16601 if (ParamDecl->hasDefaultArg())
16602 return SemaRef.Diag(FnDecl->getLocation(),
16603 diag::err_operator_new_default_arg)
16604 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16605 }
16606
16607 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16608 QualType CanResultType = NormalizeType(FnType->getReturnType());
16609 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16610 QualType CanExpectedSizeOrAddressParamType =
16611 NormalizeType(ExpectedSizeOrAddressParamType);
16612
16613 // Check that the result type is what we expect.
16614 if (CanResultType != CanExpectedResultType) {
16615 // Reject even if the type is dependent; an operator delete function is
16616 // required to have a non-dependent result type.
16617 return SemaRef.Diag(
16618 FnDecl->getLocation(),
16619 CanResultType->isDependentType()
16620 ? diag::err_operator_new_delete_dependent_result_type
16621 : diag::err_operator_new_delete_invalid_result_type)
16622 << FnDecl->getDeclName() << ExpectedResultType;
16623 }
16624
16625 // A function template must have at least 2 parameters.
16626 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16627 return SemaRef.Diag(FnDecl->getLocation(),
16628 diag::err_operator_new_delete_template_too_few_parameters)
16629 << FnDecl->getDeclName();
16630
16631 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16632 auto FallbackType) -> bool {
16633 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16634 if (ExpectedType.isNull()) {
16635 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16636 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16637 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16638 << ParamDecl->getSourceRange();
16639 }
16640 CanQualType CanExpectedTy =
16641 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16642 auto ActualParamType =
16643 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16644 if (ActualParamType == CanExpectedTy)
16645 return false;
16646 unsigned Diagnostic = ActualParamType->isDependentType()
16647 ? DependentParamTypeDiag
16648 : InvalidParamTypeDiag;
16649 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16650 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16651 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16652 << FallbackType << ParamDecl->getSourceRange();
16653 };
16654
16655 // Check that the first parameter type is what we expect.
16656 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16657 return true;
16658
16659 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16660
16661 // If the first parameter type is not a type-identity we're done, otherwise
16662 // we need to ensure the size and alignment parameters have the correct type
16663 if (!IsPotentiallyTypeAware)
16664 return false;
16665
16666 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16667 return true;
16668 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16669 CanQualType StdAlignValT =
16670 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16671 : CanQualType();
16672 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16673 return true;
16674
16676 return MalformedTypeIdentity;
16677}
16678
16679static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16680 // C++ [basic.stc.dynamic.allocation]p1:
16681 // A program is ill-formed if an allocation function is declared in a
16682 // namespace scope other than global scope or declared static in global
16683 // scope.
16684 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16685 return true;
16686
16687 CanQualType SizeTy =
16688 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16689
16690 // C++ [basic.stc.dynamic.allocation]p1:
16691 // The return type shall be void*. The first parameter shall have type
16692 // std::size_t.
16694 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16695 SizeTy, diag::err_operator_new_dependent_param_type,
16696 diag::err_operator_new_param_type);
16697}
16698
16699static bool
16701 // C++ [basic.stc.dynamic.deallocation]p1:
16702 // A program is ill-formed if deallocation functions are declared in a
16703 // namespace scope other than global scope or declared static in global
16704 // scope.
16705 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16706 return true;
16707
16708 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16709 auto ConstructDestroyingDeleteAddressType = [&]() {
16710 assert(MD);
16711 return SemaRef.Context.getPointerType(
16712 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16713 };
16714
16715 // C++ P2719: A destroying operator delete cannot be type aware
16716 // so for QoL we actually check for this explicitly by considering
16717 // an destroying-delete appropriate address type and the presence of
16718 // any parameter of type destroying_delete_t as an erroneous attempt
16719 // to declare a type aware destroying delete, rather than emitting a
16720 // pile of incorrect parameter type errors.
16722 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16723 QualType AddressParamType =
16724 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16725 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16726 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16727 // The address parameter type implies an author trying to construct a
16728 // type aware destroying delete, so we'll see if we can find a parameter
16729 // of type `std::destroying_delete_t`, and if we find it we'll report
16730 // this as being an attempt at a type aware destroying delete just stop
16731 // here. If we don't do this, the resulting incorrect parameter ordering
16732 // results in a pile mismatched argument type errors that don't explain
16733 // the core problem.
16734 for (auto Param : MD->parameters()) {
16735 if (isDestroyingDeleteT(Param->getType())) {
16736 SemaRef.Diag(MD->getLocation(),
16737 diag::err_type_aware_destroying_operator_delete)
16738 << Param->getSourceRange();
16739 return true;
16740 }
16741 }
16742 }
16743 }
16744
16745 // C++ P0722:
16746 // Within a class C, the first parameter of a destroying operator delete
16747 // shall be of type C *. The first parameter of any other deallocation
16748 // function shall be of type void *.
16749 CanQualType ExpectedAddressParamType =
16750 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16751 ? SemaRef.Context.getPointerType(
16752 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16753 : SemaRef.Context.VoidPtrTy;
16754
16755 // C++ [basic.stc.dynamic.deallocation]p2:
16756 // Each deallocation function shall return void
16758 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16759 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16760 diag::err_operator_delete_dependent_param_type,
16761 diag::err_operator_delete_param_type))
16762 return true;
16763
16764 // C++ P0722:
16765 // A destroying operator delete shall be a usual deallocation function.
16766 if (MD && !MD->getParent()->isDependentContext() &&
16768 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16769 SemaRef.Diag(MD->getLocation(),
16770 diag::err_destroying_operator_delete_not_usual);
16771 return true;
16772 }
16773 }
16774
16775 return false;
16776}
16777
16779 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16780 "Expected an overloaded operator declaration");
16781
16783
16784 // C++ [over.oper]p5:
16785 // The allocation and deallocation functions, operator new,
16786 // operator new[], operator delete and operator delete[], are
16787 // described completely in 3.7.3. The attributes and restrictions
16788 // found in the rest of this subclause do not apply to them unless
16789 // explicitly stated in 3.7.3.
16790 if (Op == OO_Delete || Op == OO_Array_Delete)
16791 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16792
16793 if (Op == OO_New || Op == OO_Array_New)
16794 return CheckOperatorNewDeclaration(*this, FnDecl);
16795
16796 // C++ [over.oper]p7:
16797 // An operator function shall either be a member function or
16798 // be a non-member function and have at least one parameter
16799 // whose type is a class, a reference to a class, an enumeration,
16800 // or a reference to an enumeration.
16801 // Note: Before C++23, a member function could not be static. The only member
16802 // function allowed to be static is the call operator function.
16803 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16804 if (MethodDecl->isStatic()) {
16805 if (Op == OO_Call || Op == OO_Subscript)
16806 Diag(FnDecl->getLocation(),
16807 (LangOpts.CPlusPlus23
16808 ? diag::warn_cxx20_compat_operator_overload_static
16809 : diag::ext_operator_overload_static))
16810 << FnDecl;
16811 else
16812 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16813 << FnDecl;
16814 }
16815 } else {
16816 bool ClassOrEnumParam = false;
16817 for (auto *Param : FnDecl->parameters()) {
16818 QualType ParamType = Param->getType().getNonReferenceType();
16819 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16820 ParamType->isEnumeralType()) {
16821 ClassOrEnumParam = true;
16822 break;
16823 }
16824 }
16825
16826 if (!ClassOrEnumParam)
16827 return Diag(FnDecl->getLocation(),
16828 diag::err_operator_overload_needs_class_or_enum)
16829 << FnDecl->getDeclName();
16830 }
16831
16832 // C++ [over.oper]p8:
16833 // An operator function cannot have default arguments (8.3.6),
16834 // except where explicitly stated below.
16835 //
16836 // Only the function-call operator (C++ [over.call]p1) and the subscript
16837 // operator (CWG2507) allow default arguments.
16838 if (Op != OO_Call) {
16839 ParmVarDecl *FirstDefaultedParam = nullptr;
16840 for (auto *Param : FnDecl->parameters()) {
16841 if (Param->hasDefaultArg()) {
16842 FirstDefaultedParam = Param;
16843 break;
16844 }
16845 }
16846 if (FirstDefaultedParam) {
16847 if (Op == OO_Subscript) {
16848 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16849 ? diag::ext_subscript_overload
16850 : diag::error_subscript_overload)
16851 << FnDecl->getDeclName() << 1
16852 << FirstDefaultedParam->getDefaultArgRange();
16853 } else {
16854 return Diag(FirstDefaultedParam->getLocation(),
16855 diag::err_operator_overload_default_arg)
16856 << FnDecl->getDeclName()
16857 << FirstDefaultedParam->getDefaultArgRange();
16858 }
16859 }
16860 }
16861
16862 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16863 { false, false, false }
16864#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16865 , { Unary, Binary, MemberOnly }
16866#include "clang/Basic/OperatorKinds.def"
16867 };
16868
16869 bool CanBeUnaryOperator = OperatorUses[Op][0];
16870 bool CanBeBinaryOperator = OperatorUses[Op][1];
16871 bool MustBeMemberOperator = OperatorUses[Op][2];
16872
16873 // C++ [over.oper]p8:
16874 // [...] Operator functions cannot have more or fewer parameters
16875 // than the number required for the corresponding operator, as
16876 // described in the rest of this subclause.
16877 unsigned NumParams = FnDecl->getNumParams() +
16878 (isa<CXXMethodDecl>(FnDecl) &&
16880 ? 1
16881 : 0);
16882 if (Op != OO_Call && Op != OO_Subscript &&
16883 ((NumParams == 1 && !CanBeUnaryOperator) ||
16884 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16885 (NumParams > 2))) {
16886 // We have the wrong number of parameters.
16887 unsigned ErrorKind;
16888 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16889 ErrorKind = 2; // 2 -> unary or binary.
16890 } else if (CanBeUnaryOperator) {
16891 ErrorKind = 0; // 0 -> unary
16892 } else {
16893 assert(CanBeBinaryOperator &&
16894 "All non-call overloaded operators are unary or binary!");
16895 ErrorKind = 1; // 1 -> binary
16896 }
16897 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16898 << FnDecl->getDeclName() << NumParams << ErrorKind;
16899 }
16900
16901 if (Op == OO_Subscript && NumParams != 2) {
16902 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16903 ? diag::ext_subscript_overload
16904 : diag::error_subscript_overload)
16905 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16906 }
16907
16908 // Overloaded operators other than operator() and operator[] cannot be
16909 // variadic.
16910 if (Op != OO_Call &&
16911 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16912 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16913 << FnDecl->getDeclName();
16914 }
16915
16916 // Some operators must be member functions.
16917 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16918 return Diag(FnDecl->getLocation(),
16919 diag::err_operator_overload_must_be_member)
16920 << FnDecl->getDeclName();
16921 }
16922
16923 // C++ [over.inc]p1:
16924 // The user-defined function called operator++ implements the
16925 // prefix and postfix ++ operator. If this function is a member
16926 // function with no parameters, or a non-member function with one
16927 // parameter of class or enumeration type, it defines the prefix
16928 // increment operator ++ for objects of that type. If the function
16929 // is a member function with one parameter (which shall be of type
16930 // int) or a non-member function with two parameters (the second
16931 // of which shall be of type int), it defines the postfix
16932 // increment operator ++ for objects of that type.
16933 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16934 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16935 QualType ParamType = LastParam->getType();
16936
16937 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16938 !ParamType->isDependentType())
16939 return Diag(LastParam->getLocation(),
16940 diag::err_operator_overload_post_incdec_must_be_int)
16941 << LastParam->getType() << (Op == OO_MinusMinus);
16942 }
16943
16944 return false;
16945}
16946
16947static bool
16949 FunctionTemplateDecl *TpDecl) {
16950 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16951
16952 // Must have one or two template parameters.
16953 if (TemplateParams->size() == 1) {
16954 NonTypeTemplateParmDecl *PmDecl =
16955 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16956
16957 // The template parameter must be a char parameter pack.
16958 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16959 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16960 return false;
16961
16962 // C++20 [over.literal]p5:
16963 // A string literal operator template is a literal operator template
16964 // whose template-parameter-list comprises a single non-type
16965 // template-parameter of class type.
16966 //
16967 // As a DR resolution, we also allow placeholders for deduced class
16968 // template specializations.
16969 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16970 !PmDecl->isTemplateParameterPack() &&
16971 (PmDecl->getType()->isRecordType() ||
16972 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16973 return false;
16974 } else if (TemplateParams->size() == 2) {
16975 TemplateTypeParmDecl *PmType =
16976 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16977 NonTypeTemplateParmDecl *PmArgs =
16978 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16979
16980 // The second template parameter must be a parameter pack with the
16981 // first template parameter as its type.
16982 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16983 PmArgs->isTemplateParameterPack()) {
16984 if (const auto *TArgs =
16985 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
16986 TArgs && TArgs->getDepth() == PmType->getDepth() &&
16987 TArgs->getIndex() == PmType->getIndex()) {
16988 if (!SemaRef.inTemplateInstantiation())
16989 SemaRef.Diag(TpDecl->getLocation(),
16990 diag::ext_string_literal_operator_template);
16991 return false;
16992 }
16993 }
16994 }
16995
16996 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16997 diag::err_literal_operator_template)
16998 << TpDecl->getTemplateParameters()->getSourceRange();
16999 return true;
17000}
17001
17003 if (isa<CXXMethodDecl>(FnDecl)) {
17004 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17005 << FnDecl->getDeclName();
17006 return true;
17007 }
17008
17009 if (FnDecl->isExternC()) {
17010 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17011 if (const LinkageSpecDecl *LSD =
17012 FnDecl->getDeclContext()->getExternCContext())
17013 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17014 return true;
17015 }
17016
17017 // This might be the definition of a literal operator template.
17019
17020 // This might be a specialization of a literal operator template.
17021 if (!TpDecl)
17022 TpDecl = FnDecl->getPrimaryTemplate();
17023
17024 // template <char...> type operator "" name() and
17025 // template <class T, T...> type operator "" name() are the only valid
17026 // template signatures, and the only valid signatures with no parameters.
17027 //
17028 // C++20 also allows template <SomeClass T> type operator "" name().
17029 if (TpDecl) {
17030 if (FnDecl->param_size() != 0) {
17031 Diag(FnDecl->getLocation(),
17032 diag::err_literal_operator_template_with_params);
17033 return true;
17034 }
17035
17037 return true;
17038
17039 } else if (FnDecl->param_size() == 1) {
17040 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17041
17042 QualType ParamType = Param->getType().getUnqualifiedType();
17043
17044 // Only unsigned long long int, long double, any character type, and const
17045 // char * are allowed as the only parameters.
17046 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17047 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17048 Context.hasSameType(ParamType, Context.CharTy) ||
17049 Context.hasSameType(ParamType, Context.WideCharTy) ||
17050 Context.hasSameType(ParamType, Context.Char8Ty) ||
17051 Context.hasSameType(ParamType, Context.Char16Ty) ||
17052 Context.hasSameType(ParamType, Context.Char32Ty)) {
17053 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17054 QualType InnerType = Ptr->getPointeeType();
17055
17056 // Pointer parameter must be a const char *.
17057 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17058 Context.CharTy) &&
17059 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17060 Diag(Param->getSourceRange().getBegin(),
17061 diag::err_literal_operator_param)
17062 << ParamType << "'const char *'" << Param->getSourceRange();
17063 return true;
17064 }
17065
17066 } else if (ParamType->isRealFloatingType()) {
17067 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17068 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17069 return true;
17070
17071 } else if (ParamType->isIntegerType()) {
17072 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17073 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17074 return true;
17075
17076 } else {
17077 Diag(Param->getSourceRange().getBegin(),
17078 diag::err_literal_operator_invalid_param)
17079 << ParamType << Param->getSourceRange();
17080 return true;
17081 }
17082
17083 } else if (FnDecl->param_size() == 2) {
17084 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17085
17086 // First, verify that the first parameter is correct.
17087
17088 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17089
17090 // Two parameter function must have a pointer to const as a
17091 // first parameter; let's strip those qualifiers.
17092 const PointerType *PT = FirstParamType->getAs<PointerType>();
17093
17094 if (!PT) {
17095 Diag((*Param)->getSourceRange().getBegin(),
17096 diag::err_literal_operator_param)
17097 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17098 return true;
17099 }
17100
17101 QualType PointeeType = PT->getPointeeType();
17102 // First parameter must be const
17103 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17104 Diag((*Param)->getSourceRange().getBegin(),
17105 diag::err_literal_operator_param)
17106 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17107 return true;
17108 }
17109
17110 QualType InnerType = PointeeType.getUnqualifiedType();
17111 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17112 // const char32_t* are allowed as the first parameter to a two-parameter
17113 // function
17114 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17115 Context.hasSameType(InnerType, Context.WideCharTy) ||
17116 Context.hasSameType(InnerType, Context.Char8Ty) ||
17117 Context.hasSameType(InnerType, Context.Char16Ty) ||
17118 Context.hasSameType(InnerType, Context.Char32Ty))) {
17119 Diag((*Param)->getSourceRange().getBegin(),
17120 diag::err_literal_operator_param)
17121 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17122 return true;
17123 }
17124
17125 // Move on to the second and final parameter.
17126 ++Param;
17127
17128 // The second parameter must be a std::size_t.
17129 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17130 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17131 Diag((*Param)->getSourceRange().getBegin(),
17132 diag::err_literal_operator_param)
17133 << SecondParamType << Context.getSizeType()
17134 << (*Param)->getSourceRange();
17135 return true;
17136 }
17137 } else {
17138 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17139 return true;
17140 }
17141
17142 // Parameters are good.
17143
17144 // A parameter-declaration-clause containing a default argument is not
17145 // equivalent to any of the permitted forms.
17146 for (auto *Param : FnDecl->parameters()) {
17147 if (Param->hasDefaultArg()) {
17148 Diag(Param->getDefaultArgRange().getBegin(),
17149 diag::err_literal_operator_default_argument)
17150 << Param->getDefaultArgRange();
17151 break;
17152 }
17153 }
17154
17155 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17158 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17159 // C++23 [usrlit.suffix]p1:
17160 // Literal suffix identifiers that do not start with an underscore are
17161 // reserved for future standardization. Literal suffix identifiers that
17162 // contain a double underscore __ are reserved for use by C++
17163 // implementations.
17164 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17165 << static_cast<int>(Status)
17167 }
17168
17169 return false;
17170}
17171
17173 Expr *LangStr,
17174 SourceLocation LBraceLoc) {
17175 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17176 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17177
17178 StringRef Lang = Lit->getString();
17180 if (Lang == "C")
17182 else if (Lang == "C++")
17184 else {
17185 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17186 << LangStr->getSourceRange();
17187 return nullptr;
17188 }
17189
17190 // FIXME: Add all the various semantics of linkage specifications
17191
17193 LangStr->getExprLoc(), Language,
17194 LBraceLoc.isValid());
17195
17196 /// C++ [module.unit]p7.2.3
17197 /// - Otherwise, if the declaration
17198 /// - ...
17199 /// - ...
17200 /// - appears within a linkage-specification,
17201 /// it is attached to the global module.
17202 ///
17203 /// If the declaration is already in global module fragment, we don't
17204 /// need to attach it again.
17205 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17206 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17207 D->setLocalOwningModule(GlobalModule);
17208 }
17209
17210 CurContext->addDecl(D);
17211 PushDeclContext(S, D);
17212 return D;
17213}
17214
17216 Decl *LinkageSpec,
17217 SourceLocation RBraceLoc) {
17218 if (RBraceLoc.isValid()) {
17219 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17220 LSDecl->setRBraceLoc(RBraceLoc);
17221 }
17222
17223 // If the current module doesn't has Parent, it implies that the
17224 // LinkageSpec isn't in the module created by itself. So we don't
17225 // need to pop it.
17226 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17227 getCurrentModule()->isImplicitGlobalModule() &&
17228 getCurrentModule()->Parent)
17229 PopImplicitGlobalModuleFragment();
17230
17232 return LinkageSpec;
17233}
17234
17236 const ParsedAttributesView &AttrList,
17237 SourceLocation SemiLoc) {
17238 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17239 // Attribute declarations appertain to empty declaration so we handle
17240 // them here.
17241 ProcessDeclAttributeList(S, ED, AttrList);
17242
17243 CurContext->addDecl(ED);
17244 return ED;
17245}
17246
17248 SourceLocation StartLoc,
17249 SourceLocation Loc,
17250 const IdentifierInfo *Name) {
17251 bool Invalid = false;
17252 QualType ExDeclType = TInfo->getType();
17253
17254 // Arrays and functions decay.
17255 if (ExDeclType->isArrayType())
17256 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17257 else if (ExDeclType->isFunctionType())
17258 ExDeclType = Context.getPointerType(ExDeclType);
17259
17260 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17261 // The exception-declaration shall not denote a pointer or reference to an
17262 // incomplete type, other than [cv] void*.
17263 // N2844 forbids rvalue references.
17264 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17265 Diag(Loc, diag::err_catch_rvalue_ref);
17266 Invalid = true;
17267 }
17268
17269 if (ExDeclType->isVariablyModifiedType()) {
17270 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17271 Invalid = true;
17272 }
17273
17274 QualType BaseType = ExDeclType;
17275 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17276 unsigned DK = diag::err_catch_incomplete;
17277 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17278 BaseType = Ptr->getPointeeType();
17279 Mode = 1;
17280 DK = diag::err_catch_incomplete_ptr;
17281 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17282 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17283 BaseType = Ref->getPointeeType();
17284 Mode = 2;
17285 DK = diag::err_catch_incomplete_ref;
17286 }
17287 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17288 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17289 Invalid = true;
17290
17291 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17292 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17293 Invalid = true;
17294 }
17295
17296 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17297 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17298 Invalid = true;
17299 }
17300
17301 if (!Invalid && !ExDeclType->isDependentType() &&
17302 RequireNonAbstractType(Loc, ExDeclType,
17303 diag::err_abstract_type_in_decl,
17305 Invalid = true;
17306
17307 // Only the non-fragile NeXT runtime currently supports C++ catches
17308 // of ObjC types, and no runtime supports catching ObjC types by value.
17309 if (!Invalid && getLangOpts().ObjC) {
17310 QualType T = ExDeclType;
17311 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17312 T = RT->getPointeeType();
17313
17314 if (T->isObjCObjectType()) {
17315 Diag(Loc, diag::err_objc_object_catch);
17316 Invalid = true;
17317 } else if (T->isObjCObjectPointerType()) {
17318 // FIXME: should this be a test for macosx-fragile specifically?
17320 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17321 }
17322 }
17323
17324 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17325 ExDeclType, TInfo, SC_None);
17326 ExDecl->setExceptionVariable(true);
17327
17328 // In ARC, infer 'retaining' for variables of retainable type.
17329 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17330 Invalid = true;
17331
17332 if (!Invalid && !ExDeclType->isDependentType()) {
17333 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17334 // Insulate this from anything else we might currently be parsing.
17337
17338 // C++ [except.handle]p16:
17339 // The object declared in an exception-declaration or, if the
17340 // exception-declaration does not specify a name, a temporary (12.2) is
17341 // copy-initialized (8.5) from the exception object. [...]
17342 // The object is destroyed when the handler exits, after the destruction
17343 // of any automatic objects initialized within the handler.
17344 //
17345 // We just pretend to initialize the object with itself, then make sure
17346 // it can be destroyed later.
17347 QualType initType = Context.getExceptionObjectType(ExDeclType);
17348
17349 InitializedEntity entity =
17351 InitializationKind initKind =
17353
17354 Expr *opaqueValue =
17355 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17356 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17357 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17358 if (result.isInvalid())
17359 Invalid = true;
17360 else {
17361 // If the constructor used was non-trivial, set this as the
17362 // "initializer".
17363 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17364 if (!construct->getConstructor()->isTrivial()) {
17365 Expr *init = MaybeCreateExprWithCleanups(construct);
17366 ExDecl->setInit(init);
17367 }
17368
17369 // And make sure it's destructable.
17370 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17371 }
17372 }
17373 }
17374
17375 if (Invalid)
17376 ExDecl->setInvalidDecl();
17377
17378 return ExDecl;
17379}
17380
17383 bool Invalid = D.isInvalidType();
17384
17385 // Check for unexpanded parameter packs.
17388 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17389 D.getIdentifierLoc());
17390 Invalid = true;
17391 }
17392
17393 const IdentifierInfo *II = D.getIdentifier();
17394 if (NamedDecl *PrevDecl =
17397 // The scope should be freshly made just for us. There is just no way
17398 // it contains any previous declaration, except for function parameters in
17399 // a function-try-block's catch statement.
17400 assert(!S->isDeclScope(PrevDecl));
17401 if (isDeclInScope(PrevDecl, CurContext, S)) {
17402 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17403 << D.getIdentifier();
17404 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17405 Invalid = true;
17406 } else if (PrevDecl->isTemplateParameter())
17407 // Maybe we will complain about the shadowed template parameter.
17409 }
17410
17411 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17412 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17413 << D.getCXXScopeSpec().getRange();
17414 Invalid = true;
17415 }
17416
17418 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17419 if (Invalid)
17420 ExDecl->setInvalidDecl();
17421
17422 // Add the exception declaration into this scope.
17423 if (II)
17424 PushOnScopeChains(ExDecl, S);
17425 else
17426 CurContext->addDecl(ExDecl);
17427
17428 ProcessDeclAttributes(S, ExDecl, D);
17429 return ExDecl;
17430}
17431
17433 Expr *AssertExpr,
17434 Expr *AssertMessageExpr,
17435 SourceLocation RParenLoc) {
17437 return nullptr;
17438
17439 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17440 AssertMessageExpr, RParenLoc, false);
17441}
17442
17443static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17444 switch (BTK) {
17445 case BuiltinType::Char_S:
17446 case BuiltinType::Char_U:
17447 break;
17448 case BuiltinType::Char8:
17449 OS << "u8";
17450 break;
17451 case BuiltinType::Char16:
17452 OS << 'u';
17453 break;
17454 case BuiltinType::Char32:
17455 OS << 'U';
17456 break;
17457 case BuiltinType::WChar_S:
17458 case BuiltinType::WChar_U:
17459 OS << 'L';
17460 break;
17461 default:
17462 llvm_unreachable("Non-character type");
17463 }
17464}
17465
17466/// Convert character's value, interpreted as a code unit, to a string.
17467/// The value needs to be zero-extended to 32-bits.
17468/// FIXME: This assumes Unicode literal encodings
17469static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17470 unsigned TyWidth,
17471 SmallVectorImpl<char> &Str) {
17472 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17473 char *Ptr = Arr;
17474 BuiltinType::Kind K = BTy->getKind();
17475 llvm::raw_svector_ostream OS(Str);
17476
17477 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17478 // other types.
17479 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17480 K == BuiltinType::Char8 || Value <= 0x7F) {
17481 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17482 if (!Escaped.empty())
17483 EscapeStringForDiagnostic(Escaped, Str);
17484 else
17485 OS << static_cast<char>(Value);
17486 return;
17487 }
17488
17489 switch (K) {
17490 case BuiltinType::Char16:
17491 case BuiltinType::Char32:
17492 case BuiltinType::WChar_S:
17493 case BuiltinType::WChar_U: {
17494 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17495 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17496 else
17497 OS << "\\x"
17498 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17499 break;
17500 }
17501 default:
17502 llvm_unreachable("Non-character type is passed");
17503 }
17504}
17505
17506/// Convert \V to a string we can present to the user in a diagnostic
17507/// \T is the type of the expression that has been evaluated into \V
17510 ASTContext &Context) {
17511 if (!V.hasValue())
17512 return false;
17513
17514 switch (V.getKind()) {
17516 if (T->isBooleanType()) {
17517 // Bools are reduced to ints during evaluation, but for
17518 // diagnostic purposes we want to print them as
17519 // true or false.
17520 int64_t BoolValue = V.getInt().getExtValue();
17521 assert((BoolValue == 0 || BoolValue == 1) &&
17522 "Bool type, but value is not 0 or 1");
17523 llvm::raw_svector_ostream OS(Str);
17524 OS << (BoolValue ? "true" : "false");
17525 } else {
17526 llvm::raw_svector_ostream OS(Str);
17527 // Same is true for chars.
17528 // We want to print the character representation for textual types
17529 const auto *BTy = T->getAs<BuiltinType>();
17530 if (BTy) {
17531 switch (BTy->getKind()) {
17532 case BuiltinType::Char_S:
17533 case BuiltinType::Char_U:
17534 case BuiltinType::Char8:
17535 case BuiltinType::Char16:
17536 case BuiltinType::Char32:
17537 case BuiltinType::WChar_S:
17538 case BuiltinType::WChar_U: {
17539 unsigned TyWidth = Context.getIntWidth(T);
17540 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17541 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17542 WriteCharTypePrefix(BTy->getKind(), OS);
17543 OS << '\'';
17544 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17545 OS << "' (0x"
17546 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17547 /*Upper=*/true)
17548 << ", " << V.getInt() << ')';
17549 return true;
17550 }
17551 default:
17552 break;
17553 }
17554 }
17555 V.getInt().toString(Str);
17556 }
17557
17558 break;
17559
17561 V.getFloat().toString(Str);
17562 break;
17563
17565 if (V.isNullPointer()) {
17566 llvm::raw_svector_ostream OS(Str);
17567 OS << "nullptr";
17568 } else
17569 return false;
17570 break;
17571
17573 llvm::raw_svector_ostream OS(Str);
17574 OS << '(';
17575 V.getComplexFloatReal().toString(Str);
17576 OS << " + ";
17577 V.getComplexFloatImag().toString(Str);
17578 OS << "i)";
17579 } break;
17580
17582 llvm::raw_svector_ostream OS(Str);
17583 OS << '(';
17584 V.getComplexIntReal().toString(Str);
17585 OS << " + ";
17586 V.getComplexIntImag().toString(Str);
17587 OS << "i)";
17588 } break;
17589
17590 default:
17591 return false;
17592 }
17593
17594 return true;
17595}
17596
17597/// Some Expression types are not useful to print notes about,
17598/// e.g. literals and values that have already been expanded
17599/// before such as int-valued template parameters.
17600static bool UsefulToPrintExpr(const Expr *E) {
17601 E = E->IgnoreParenImpCasts();
17602 // Literals are pretty easy for humans to understand.
17605 return false;
17606
17607 // These have been substituted from template parameters
17608 // and appear as literals in the static assert error.
17610 return false;
17611
17612 // -5 is also simple to understand.
17613 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17614 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17615
17616 // Only print nested arithmetic operators.
17617 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17618 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17619 BO->isBitwiseOp());
17620
17621 return true;
17622}
17623
17625 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17626 Op && Op->getOpcode() != BO_LOr) {
17627 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17628 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17629
17630 // Ignore comparisons of boolean expressions with a boolean literal.
17631 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17632 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17633 return;
17634
17635 // Don't print obvious expressions.
17636 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17637 return;
17638
17639 struct {
17640 const clang::Expr *Cond;
17642 SmallString<12> ValueString;
17643 bool Print;
17644 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17645 {RHS, Expr::EvalResult(), {}, false}};
17646 for (unsigned I = 0; I < 2; I++) {
17647 const Expr *Side = DiagSide[I].Cond;
17648
17649 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17650
17651 DiagSide[I].Print =
17652 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17653 DiagSide[I].ValueString, Context);
17654 }
17655 if (DiagSide[0].Print && DiagSide[1].Print) {
17656 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17657 << DiagSide[0].ValueString << Op->getOpcodeStr()
17658 << DiagSide[1].ValueString << Op->getSourceRange();
17659 }
17660 } else {
17662 }
17663}
17664
17665template <typename ResultType>
17666static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17667 ResultType &Result, ASTContext &Ctx,
17669 bool ErrorOnInvalidMessage) {
17670
17671 assert(Message);
17672 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17673 "can't evaluate a dependant static assert message");
17674
17675 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17676 assert(SL->isUnevaluated() && "expected an unevaluated string");
17677 if constexpr (std::is_same_v<APValue, ResultType>) {
17678 Result =
17679 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17680 const ConstantArrayType *CAT =
17681 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17682 assert(CAT && "string literal isn't an array");
17683 QualType CharType = CAT->getElementType();
17684 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17685 CharType->isUnsignedIntegerType());
17686 for (unsigned I = 0; I < SL->getLength(); I++) {
17687 Value = SL->getCodeUnit(I);
17688 Result.getArrayInitializedElt(I) = APValue(Value);
17689 }
17690 } else {
17691 Result.assign(SL->getString().begin(), SL->getString().end());
17692 }
17693 return true;
17694 }
17695
17696 SourceLocation Loc = Message->getBeginLoc();
17697 QualType T = Message->getType().getNonReferenceType();
17698 auto *RD = T->getAsCXXRecordDecl();
17699 if (!RD) {
17700 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17701 return false;
17702 }
17703
17704 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17706 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17707 SemaRef.LookupQualifiedName(MemberLookup, RD);
17708 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17710 if (MemberLookup.empty())
17711 return std::nullopt;
17712 return std::move(MemberLookup);
17713 };
17714
17715 std::optional<LookupResult> SizeMember = FindMember("size");
17716 std::optional<LookupResult> DataMember = FindMember("data");
17717 if (!SizeMember || !DataMember) {
17718 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17719 << EvalContext
17720 << ((!SizeMember && !DataMember) ? 2
17721 : !SizeMember ? 0
17722 : 1);
17723 return false;
17724 }
17725
17726 auto BuildExpr = [&](LookupResult &LR) {
17728 Message, Message->getType(), Message->getBeginLoc(), false,
17729 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17730 if (Res.isInvalid())
17731 return ExprError();
17732 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17733 false, true);
17734 if (Res.isInvalid())
17735 return ExprError();
17736 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17737 return ExprError();
17738 return SemaRef.TemporaryMaterializationConversion(Res.get());
17739 };
17740
17741 ExprResult SizeE = BuildExpr(*SizeMember);
17742 ExprResult DataE = BuildExpr(*DataMember);
17743
17744 QualType SizeT = SemaRef.Context.getSizeType();
17745 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17746 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17747
17748 ExprResult EvaluatedSize =
17749 SizeE.isInvalid()
17750 ? ExprError()
17753 if (EvaluatedSize.isInvalid()) {
17754 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17755 << EvalContext << /*size*/ 0;
17756 return false;
17757 }
17758
17759 ExprResult EvaluatedData =
17760 DataE.isInvalid()
17761 ? ExprError()
17763 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17764 if (EvaluatedData.isInvalid()) {
17765 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17766 << EvalContext << /*data*/ 1;
17767 return false;
17768 }
17769
17770 if (!ErrorOnInvalidMessage &&
17771 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17772 return true;
17773
17774 Expr::EvalResult Status;
17776 Status.Diag = &Notes;
17777 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17778 EvaluatedData.get(), Ctx, Status) ||
17779 !Notes.empty()) {
17780 SemaRef.Diag(Message->getBeginLoc(),
17781 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17782 : diag::warn_user_defined_msg_constexpr)
17783 << EvalContext;
17784 for (const auto &Note : Notes)
17785 SemaRef.Diag(Note.first, Note.second);
17786 return !ErrorOnInvalidMessage;
17787 }
17788 return true;
17789}
17790
17792 StringEvaluationContext EvalContext,
17793 bool ErrorOnInvalidMessage) {
17794 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17795 ErrorOnInvalidMessage);
17796}
17797
17798bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17799 StringEvaluationContext EvalContext,
17800 bool ErrorOnInvalidMessage) {
17801 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17802 ErrorOnInvalidMessage);
17803}
17804
17806 Expr *AssertExpr, Expr *AssertMessage,
17807 SourceLocation RParenLoc,
17808 bool Failed) {
17809 assert(AssertExpr != nullptr && "Expected non-null condition");
17810 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17811 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17812 !AssertMessage->isValueDependent())) &&
17813 !Failed) {
17814 // In a static_assert-declaration, the constant-expression shall be a
17815 // constant expression that can be contextually converted to bool.
17816 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17817 if (Converted.isInvalid())
17818 Failed = true;
17819
17820 ExprResult FullAssertExpr =
17821 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17822 /*DiscardedValue*/ false,
17823 /*IsConstexpr*/ true);
17824 if (FullAssertExpr.isInvalid())
17825 Failed = true;
17826 else
17827 AssertExpr = FullAssertExpr.get();
17828
17829 llvm::APSInt Cond;
17830 Expr *BaseExpr = AssertExpr;
17832
17833 if (!getLangOpts().CPlusPlus) {
17834 // In C mode, allow folding as an extension for better compatibility with
17835 // C++ in terms of expressions like static_assert("test") or
17836 // static_assert(nullptr).
17837 FoldKind = AllowFoldKind::Allow;
17838 }
17839
17840 if (!Failed && VerifyIntegerConstantExpression(
17841 BaseExpr, &Cond,
17842 diag::err_static_assert_expression_is_not_constant,
17843 FoldKind).isInvalid())
17844 Failed = true;
17845
17846 // If the static_assert passes, only verify that
17847 // the message is grammatically valid without evaluating it.
17848 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17849 std::string Str;
17850 EvaluateAsString(AssertMessage, Str, Context,
17852 /*ErrorOnInvalidMessage=*/false);
17853 }
17854
17855 // CWG2518
17856 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17857 // template definition, the declaration has no effect.
17858 bool InTemplateDefinition =
17859 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17860
17861 if (!Failed && !Cond && !InTemplateDefinition) {
17862 SmallString<256> MsgBuffer;
17863 llvm::raw_svector_ostream Msg(MsgBuffer);
17864 bool HasMessage = AssertMessage;
17865 if (AssertMessage) {
17866 std::string Str;
17867 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
17869 /*ErrorOnInvalidMessage=*/true) ||
17870 !Str.empty();
17871 Msg << Str;
17872 }
17873 Expr *InnerCond = nullptr;
17874 std::string InnerCondDescription;
17875 std::tie(InnerCond, InnerCondDescription) =
17876 findFailedBooleanCondition(Converted.get());
17877 if (const auto *ConceptIDExpr =
17878 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
17879 // Drill down into concept specialization expressions to see why they
17880 // weren't satisfied.
17881 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17882 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17883 ConstraintSatisfaction Satisfaction;
17884 if (!CheckConstraintSatisfaction(ConceptIDExpr, Satisfaction))
17885 DiagnoseUnsatisfiedConstraint(Satisfaction);
17886 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
17887 !isa<IntegerLiteral>(InnerCond)) {
17888 Diag(InnerCond->getBeginLoc(),
17889 diag::err_static_assert_requirement_failed)
17890 << InnerCondDescription << !HasMessage << Msg.str()
17891 << InnerCond->getSourceRange();
17892 DiagnoseStaticAssertDetails(InnerCond);
17893 } else {
17894 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17895 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17897 }
17898 Failed = true;
17899 }
17900 } else {
17901 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17902 /*DiscardedValue*/false,
17903 /*IsConstexpr*/true);
17904 if (FullAssertExpr.isInvalid())
17905 Failed = true;
17906 else
17907 AssertExpr = FullAssertExpr.get();
17908 }
17909
17911 AssertExpr, AssertMessage, RParenLoc,
17912 Failed);
17913
17914 CurContext->addDecl(Decl);
17915 return Decl;
17916}
17917
17919 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17920 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17921 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17922 MultiTemplateParamsArg TempParamLists) {
17924
17925 bool IsMemberSpecialization = false;
17926 bool Invalid = false;
17927
17928 if (TemplateParameterList *TemplateParams =
17930 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17931 IsMemberSpecialization, Invalid)) {
17932 if (TemplateParams->size() > 0) {
17933 // This is a declaration of a class template.
17934 if (Invalid)
17935 return true;
17936
17937 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17938 Name, NameLoc, Attr, TemplateParams, AS_public,
17939 /*ModulePrivateLoc=*/SourceLocation(),
17940 FriendLoc, TempParamLists.size() - 1,
17941 TempParamLists.data())
17942 .get();
17943 } else {
17944 // The "template<>" header is extraneous.
17945 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17946 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17947 IsMemberSpecialization = true;
17948 }
17949 }
17950
17951 if (Invalid) return true;
17952
17953 bool isAllExplicitSpecializations = true;
17954 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17955 if (TempParamLists[I]->size()) {
17956 isAllExplicitSpecializations = false;
17957 break;
17958 }
17959 }
17960
17961 // FIXME: don't ignore attributes.
17962
17963 // If it's explicit specializations all the way down, just forget
17964 // about the template header and build an appropriate non-templated
17965 // friend. TODO: for source fidelity, remember the headers.
17967 if (isAllExplicitSpecializations) {
17968 if (SS.isEmpty()) {
17969 bool Owned = false;
17970 bool IsDependent = false;
17971 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17972 Attr, AS_public,
17973 /*ModulePrivateLoc=*/SourceLocation(),
17974 MultiTemplateParamsArg(), Owned, IsDependent,
17975 /*ScopedEnumKWLoc=*/SourceLocation(),
17976 /*ScopedEnumUsesClassTag=*/false,
17977 /*UnderlyingType=*/TypeResult(),
17978 /*IsTypeSpecifier=*/false,
17979 /*IsTemplateParamOrArg=*/false,
17980 /*OOK=*/OffsetOfKind::Outside);
17981 }
17982
17983 TypeSourceInfo *TSI = nullptr;
17986 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
17987 NameLoc, &TSI, /*DeducedTSTContext=*/true);
17988 if (T.isNull())
17989 return true;
17990
17992 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
17993 EllipsisLoc, TempParamLists);
17994 Friend->setAccess(AS_public);
17995 CurContext->addDecl(Friend);
17996 return Friend;
17997 }
17998
17999 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18000
18001 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18002 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18003 // shall not have been introduced by the template-declaration.
18005 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18006 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18007 for (UnexpandedParameterPack &U : Unexpanded) {
18008 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18009 DI && DI->first >= FriendDeclDepth) {
18010 auto *ND = dyn_cast<NamedDecl *>(U.first);
18011 if (!ND)
18012 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18013 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18014 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18015 return true;
18016 }
18017 }
18018
18019 // Handle the case of a templated-scope friend class. e.g.
18020 // template <class T> class A<T>::B;
18021 // FIXME: we don't support these right now.
18022 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18025 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18026 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18028 TL.setElaboratedKeywordLoc(TagLoc);
18030 TL.setNameLoc(NameLoc);
18031
18033 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18034 EllipsisLoc, TempParamLists);
18035 Friend->setAccess(AS_public);
18036 Friend->setUnsupportedFriend(true);
18037 CurContext->addDecl(Friend);
18038 return Friend;
18039}
18040
18042 MultiTemplateParamsArg TempParams,
18043 SourceLocation EllipsisLoc) {
18044 SourceLocation Loc = DS.getBeginLoc();
18045 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18046
18047 assert(DS.isFriendSpecified());
18049
18050 // C++ [class.friend]p3:
18051 // A friend declaration that does not declare a function shall have one of
18052 // the following forms:
18053 // friend elaborated-type-specifier ;
18054 // friend simple-type-specifier ;
18055 // friend typename-specifier ;
18056 //
18057 // If the friend keyword isn't first, or if the declarations has any type
18058 // qualifiers, then the declaration doesn't have that form.
18060 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18061 if (DS.getTypeQualifiers()) {
18063 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18065 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18067 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18069 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18071 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18072 }
18073
18074 // Try to convert the decl specifier to a type. This works for
18075 // friend templates because ActOnTag never produces a ClassTemplateDecl
18076 // for a TagUseKind::Friend.
18077 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18079 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18080 QualType T = TSI->getType();
18081 if (TheDeclarator.isInvalidType())
18082 return nullptr;
18083
18084 // If '...' is present, the type must contain an unexpanded parameter
18085 // pack, and vice versa.
18086 bool Invalid = false;
18087 if (EllipsisLoc.isInvalid() &&
18089 return nullptr;
18090 if (EllipsisLoc.isValid() &&
18092 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18093 << TSI->getTypeLoc().getSourceRange();
18094 Invalid = true;
18095 }
18096
18097 if (!T->isElaboratedTypeSpecifier()) {
18098 if (TempParams.size()) {
18099 // C++23 [dcl.pre]p5:
18100 // In a simple-declaration, the optional init-declarator-list can be
18101 // omitted only when declaring a class or enumeration, that is, when
18102 // the decl-specifier-seq contains either a class-specifier, an
18103 // elaborated-type-specifier with a class-key, or an enum-specifier.
18104 //
18105 // The declaration of a template-declaration or explicit-specialization
18106 // is never a member-declaration, so this must be a simple-declaration
18107 // with no init-declarator-list. Therefore, this is ill-formed.
18108 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18109 return nullptr;
18110 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18111 SmallString<16> InsertionText(" ");
18112 InsertionText += RD->getKindName();
18113
18115 ? diag::warn_cxx98_compat_unelaborated_friend_type
18116 : diag::ext_unelaborated_friend_type)
18117 << (unsigned)RD->getTagKind() << T
18119 InsertionText);
18120 } else {
18121 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18122 << T << DS.getSourceRange();
18123 }
18124 }
18125
18126 // C++98 [class.friend]p1: A friend of a class is a function
18127 // or class that is not a member of the class . . .
18128 // This is fixed in DR77, which just barely didn't make the C++03
18129 // deadline. It's also a very silly restriction that seriously
18130 // affects inner classes and which nobody else seems to implement;
18131 // thus we never diagnose it, not even in -pedantic.
18132 //
18133 // But note that we could warn about it: it's always useless to
18134 // friend one of your own members (it's not, however, worthless to
18135 // friend a member of an arbitrary specialization of your template).
18136
18137 Decl *D;
18138 if (!TempParams.empty())
18139 // TODO: Support variadic friend template decls?
18140 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18141 FriendLoc);
18142 else
18144 TSI, FriendLoc, EllipsisLoc);
18145
18146 if (!D)
18147 return nullptr;
18148
18149 D->setAccess(AS_public);
18150 CurContext->addDecl(D);
18151
18152 if (Invalid)
18153 D->setInvalidDecl();
18154
18155 return D;
18156}
18157
18159 MultiTemplateParamsArg TemplateParams) {
18160 const DeclSpec &DS = D.getDeclSpec();
18161
18162 assert(DS.isFriendSpecified());
18164
18167
18168 // C++ [class.friend]p1
18169 // A friend of a class is a function or class....
18170 // Note that this sees through typedefs, which is intended.
18171 // It *doesn't* see through dependent types, which is correct
18172 // according to [temp.arg.type]p3:
18173 // If a declaration acquires a function type through a
18174 // type dependent on a template-parameter and this causes
18175 // a declaration that does not use the syntactic form of a
18176 // function declarator to have a function type, the program
18177 // is ill-formed.
18178 if (!TInfo->getType()->isFunctionType()) {
18179 Diag(Loc, diag::err_unexpected_friend);
18180
18181 // It might be worthwhile to try to recover by creating an
18182 // appropriate declaration.
18183 return nullptr;
18184 }
18185
18186 // C++ [namespace.memdef]p3
18187 // - If a friend declaration in a non-local class first declares a
18188 // class or function, the friend class or function is a member
18189 // of the innermost enclosing namespace.
18190 // - The name of the friend is not found by simple name lookup
18191 // until a matching declaration is provided in that namespace
18192 // scope (either before or after the class declaration granting
18193 // friendship).
18194 // - If a friend function is called, its name may be found by the
18195 // name lookup that considers functions from namespaces and
18196 // classes associated with the types of the function arguments.
18197 // - When looking for a prior declaration of a class or a function
18198 // declared as a friend, scopes outside the innermost enclosing
18199 // namespace scope are not considered.
18200
18201 CXXScopeSpec &SS = D.getCXXScopeSpec();
18203 assert(NameInfo.getName());
18204
18205 // Check for unexpanded parameter packs.
18209 return nullptr;
18210
18211 // The context we found the declaration in, or in which we should
18212 // create the declaration.
18213 DeclContext *DC;
18214 Scope *DCScope = S;
18215 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18217
18218 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18219
18220 // There are five cases here.
18221 // - There's no scope specifier and we're in a local class. Only look
18222 // for functions declared in the immediately-enclosing block scope.
18223 // We recover from invalid scope qualifiers as if they just weren't there.
18224 FunctionDecl *FunctionContainingLocalClass = nullptr;
18225 if ((SS.isInvalid() || !SS.isSet()) &&
18226 (FunctionContainingLocalClass =
18227 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18228 // C++11 [class.friend]p11:
18229 // If a friend declaration appears in a local class and the name
18230 // specified is an unqualified name, a prior declaration is
18231 // looked up without considering scopes that are outside the
18232 // innermost enclosing non-class scope. For a friend function
18233 // declaration, if there is no prior declaration, the program is
18234 // ill-formed.
18235
18236 // Find the innermost enclosing non-class scope. This is the block
18237 // scope containing the local class definition (or for a nested class,
18238 // the outer local class).
18239 DCScope = S->getFnParent();
18240
18241 // Look up the function name in the scope.
18243 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18244
18245 if (!Previous.empty()) {
18246 // All possible previous declarations must have the same context:
18247 // either they were declared at block scope or they are members of
18248 // one of the enclosing local classes.
18249 DC = Previous.getRepresentativeDecl()->getDeclContext();
18250 } else {
18251 // This is ill-formed, but provide the context that we would have
18252 // declared the function in, if we were permitted to, for error recovery.
18253 DC = FunctionContainingLocalClass;
18254 }
18256
18257 // - There's no scope specifier, in which case we just go to the
18258 // appropriate scope and look for a function or function template
18259 // there as appropriate.
18260 } else if (SS.isInvalid() || !SS.isSet()) {
18261 // C++11 [namespace.memdef]p3:
18262 // If the name in a friend declaration is neither qualified nor
18263 // a template-id and the declaration is a function or an
18264 // elaborated-type-specifier, the lookup to determine whether
18265 // the entity has been previously declared shall not consider
18266 // any scopes outside the innermost enclosing namespace.
18267
18268 // Find the appropriate context according to the above.
18269 DC = CurContext;
18270
18271 // Skip class contexts. If someone can cite chapter and verse
18272 // for this behavior, that would be nice --- it's what GCC and
18273 // EDG do, and it seems like a reasonable intent, but the spec
18274 // really only says that checks for unqualified existing
18275 // declarations should stop at the nearest enclosing namespace,
18276 // not that they should only consider the nearest enclosing
18277 // namespace.
18278 while (DC->isRecord())
18279 DC = DC->getParent();
18280
18281 DeclContext *LookupDC = DC->getNonTransparentContext();
18282 while (true) {
18283 LookupQualifiedName(Previous, LookupDC);
18284
18285 if (!Previous.empty()) {
18286 DC = LookupDC;
18287 break;
18288 }
18289
18290 if (isTemplateId) {
18291 if (isa<TranslationUnitDecl>(LookupDC)) break;
18292 } else {
18293 if (LookupDC->isFileContext()) break;
18294 }
18295 LookupDC = LookupDC->getParent();
18296 }
18297
18298 DCScope = getScopeForDeclContext(S, DC);
18299
18300 // - There's a non-dependent scope specifier, in which case we
18301 // compute it and do a previous lookup there for a function
18302 // or function template.
18303 } else if (!SS.getScopeRep().isDependent()) {
18304 DC = computeDeclContext(SS);
18305 if (!DC) return nullptr;
18306
18307 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18308
18310
18311 // C++ [class.friend]p1: A friend of a class is a function or
18312 // class that is not a member of the class . . .
18313 if (DC->Equals(CurContext))
18316 diag::warn_cxx98_compat_friend_is_member :
18317 diag::err_friend_is_member);
18318
18319 // - There's a scope specifier that does not match any template
18320 // parameter lists, in which case we use some arbitrary context,
18321 // create a method or method template, and wait for instantiation.
18322 // - There's a scope specifier that does match some template
18323 // parameter lists, which we don't handle right now.
18324 } else {
18325 DC = CurContext;
18326 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18327 }
18328
18329 if (!DC->isRecord()) {
18330 int DiagArg = -1;
18331 switch (D.getName().getKind()) {
18334 DiagArg = 0;
18335 break;
18337 DiagArg = 1;
18338 break;
18340 DiagArg = 2;
18341 break;
18343 DiagArg = 3;
18344 break;
18350 break;
18351 }
18352 // This implies that it has to be an operator or function.
18353 if (DiagArg >= 0) {
18354 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18355 return nullptr;
18356 }
18357 }
18358
18359 // FIXME: This is an egregious hack to cope with cases where the scope stack
18360 // does not contain the declaration context, i.e., in an out-of-line
18361 // definition of a class.
18362 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18363 if (!DCScope) {
18364 FakeDCScope.setEntity(DC);
18365 DCScope = &FakeDCScope;
18366 }
18367
18368 bool AddToScope = true;
18369 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18370 TemplateParams, AddToScope);
18371 if (!ND) return nullptr;
18372
18373 assert(ND->getLexicalDeclContext() == CurContext);
18374
18375 // If we performed typo correction, we might have added a scope specifier
18376 // and changed the decl context.
18377 DC = ND->getDeclContext();
18378
18379 // Add the function declaration to the appropriate lookup tables,
18380 // adjusting the redeclarations list as necessary. We don't
18381 // want to do this yet if the friending class is dependent.
18382 //
18383 // Also update the scope-based lookup if the target context's
18384 // lookup context is in lexical scope.
18385 if (!CurContext->isDependentContext()) {
18386 DC = DC->getRedeclContext();
18388 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18389 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18390 }
18391
18393 D.getIdentifierLoc(), ND,
18394 DS.getFriendSpecLoc());
18395 FrD->setAccess(AS_public);
18396 CurContext->addDecl(FrD);
18397
18398 if (ND->isInvalidDecl()) {
18399 FrD->setInvalidDecl();
18400 } else {
18401 if (DC->isRecord()) CheckFriendAccess(ND);
18402
18403 FunctionDecl *FD;
18404 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18405 FD = FTD->getTemplatedDecl();
18406 else
18407 FD = cast<FunctionDecl>(ND);
18408
18409 // C++ [class.friend]p6:
18410 // A function may be defined in a friend declaration of a class if and
18411 // only if the class is a non-local class, and the function name is
18412 // unqualified.
18413 if (D.isFunctionDefinition()) {
18414 // Qualified friend function definition.
18415 if (SS.isNotEmpty()) {
18416 // FIXME: We should only do this if the scope specifier names the
18417 // innermost enclosing namespace; otherwise the fixit changes the
18418 // meaning of the code.
18420 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18421
18422 DB << SS.getScopeRep();
18423 if (DC->isFileContext())
18425
18426 // Friend function defined in a local class.
18427 } else if (FunctionContainingLocalClass) {
18428 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18429
18430 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18431 // a template-id, the function name is not unqualified because these is
18432 // no name. While the wording requires some reading in-between the
18433 // lines, GCC, MSVC, and EDG all consider a friend function
18434 // specialization definitions to be de facto explicit specialization
18435 // and diagnose them as such.
18436 } else if (isTemplateId) {
18437 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18438 }
18439 }
18440
18441 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18442 // default argument expression, that declaration shall be a definition
18443 // and shall be the only declaration of the function or function
18444 // template in the translation unit.
18446 // We can't look at FD->getPreviousDecl() because it may not have been set
18447 // if we're in a dependent context. If the function is known to be a
18448 // redeclaration, we will have narrowed Previous down to the right decl.
18449 if (D.isRedeclaration()) {
18450 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18451 Diag(Previous.getRepresentativeDecl()->getLocation(),
18452 diag::note_previous_declaration);
18453 } else if (!D.isFunctionDefinition())
18454 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18455 }
18456
18457 // Mark templated-scope function declarations as unsupported.
18458 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18459 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18460 << SS.getScopeRep() << SS.getRange()
18462 FrD->setUnsupportedFriend(true);
18463 }
18464 }
18465
18467
18468 return ND;
18469}
18470
18472 StringLiteral *Message) {
18474
18475 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18476 if (!Fn) {
18477 Diag(DelLoc, diag::err_deleted_non_function);
18478 return;
18479 }
18480
18481 // Deleted function does not have a body.
18482 Fn->setWillHaveBody(false);
18483
18484 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18485 // Don't consider the implicit declaration we generate for explicit
18486 // specializations. FIXME: Do not generate these implicit declarations.
18487 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18488 Prev->getPreviousDecl()) &&
18489 !Prev->isDefined()) {
18490 Diag(DelLoc, diag::err_deleted_decl_not_first);
18491 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18492 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18493 : diag::note_previous_declaration);
18494 // We can't recover from this; the declaration might have already
18495 // been used.
18496 Fn->setInvalidDecl();
18497 return;
18498 }
18499
18500 // To maintain the invariant that functions are only deleted on their first
18501 // declaration, mark the implicitly-instantiated declaration of the
18502 // explicitly-specialized function as deleted instead of marking the
18503 // instantiated redeclaration.
18504 Fn = Fn->getCanonicalDecl();
18505 }
18506
18507 // dllimport/dllexport cannot be deleted.
18508 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18509 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18510 Fn->setInvalidDecl();
18511 }
18512
18513 // C++11 [basic.start.main]p3:
18514 // A program that defines main as deleted [...] is ill-formed.
18515 if (Fn->isMain())
18516 Diag(DelLoc, diag::err_deleted_main);
18517
18518 // C++11 [dcl.fct.def.delete]p4:
18519 // A deleted function is implicitly inline.
18520 Fn->setImplicitlyInline();
18521 Fn->setDeletedAsWritten(true, Message);
18522}
18523
18525 if (!Dcl || Dcl->isInvalidDecl())
18526 return;
18527
18528 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18529 if (!FD) {
18530 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18531 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18532 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18533 return;
18534 }
18535 }
18536
18537 Diag(DefaultLoc, diag::err_default_special_members)
18538 << getLangOpts().CPlusPlus20;
18539 return;
18540 }
18541
18542 // Reject if this can't possibly be a defaultable function.
18544 if (!DefKind &&
18545 // A dependent function that doesn't locally look defaultable can
18546 // still instantiate to a defaultable function if it's a constructor
18547 // or assignment operator.
18548 (!FD->isDependentContext() ||
18550 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18551 Diag(DefaultLoc, diag::err_default_special_members)
18552 << getLangOpts().CPlusPlus20;
18553 return;
18554 }
18555
18556 // Issue compatibility warning. We already warned if the operator is
18557 // 'operator<=>' when parsing the '<=>' token.
18558 if (DefKind.isComparison() &&
18560 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18561 ? diag::warn_cxx17_compat_defaulted_comparison
18562 : diag::ext_defaulted_comparison);
18563 }
18564
18565 FD->setDefaulted();
18566 FD->setExplicitlyDefaulted();
18567 FD->setDefaultLoc(DefaultLoc);
18568
18569 // Defer checking functions that are defaulted in a dependent context.
18570 if (FD->isDependentContext())
18571 return;
18572
18573 // Unset that we will have a body for this function. We might not,
18574 // if it turns out to be trivial, and we don't need this marking now
18575 // that we've marked it as defaulted.
18576 FD->setWillHaveBody(false);
18577
18578 if (DefKind.isComparison()) {
18579 // If this comparison's defaulting occurs within the definition of its
18580 // lexical class context, we have to do the checking when complete.
18581 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18582 if (!RD->isCompleteDefinition())
18583 return;
18584 }
18585
18586 // If this member fn was defaulted on its first declaration, we will have
18587 // already performed the checking in CheckCompletedCXXClass. Such a
18588 // declaration doesn't trigger an implicit definition.
18589 if (isa<CXXMethodDecl>(FD)) {
18590 const FunctionDecl *Primary = FD;
18591 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18592 // Ask the template instantiation pattern that actually had the
18593 // '= default' on it.
18594 Primary = Pattern;
18595 if (Primary->getCanonicalDecl()->isDefaulted())
18596 return;
18597 }
18598
18599 if (DefKind.isComparison()) {
18600 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18601 FD->setInvalidDecl();
18602 else
18603 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18604 } else {
18605 auto *MD = cast<CXXMethodDecl>(FD);
18606
18608 DefaultLoc))
18609 MD->setInvalidDecl();
18610 else
18611 DefineDefaultedFunction(*this, MD, DefaultLoc);
18612 }
18613}
18614
18616 for (Stmt *SubStmt : S->children()) {
18617 if (!SubStmt)
18618 continue;
18619 if (isa<ReturnStmt>(SubStmt))
18620 Self.Diag(SubStmt->getBeginLoc(),
18621 diag::err_return_in_constructor_handler);
18622 if (!isa<Expr>(SubStmt))
18623 SearchForReturnInStmt(Self, SubStmt);
18624 }
18625}
18626
18628 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18629 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18630 SearchForReturnInStmt(*this, Handler);
18631 }
18632}
18633
18635 StringLiteral *DeletedMessage) {
18636 switch (BodyKind) {
18637 case FnBodyKind::Delete:
18638 SetDeclDeleted(D, Loc, DeletedMessage);
18639 break;
18641 SetDeclDefaulted(D, Loc);
18642 break;
18643 case FnBodyKind::Other:
18644 llvm_unreachable(
18645 "Parsed function body should be '= delete;' or '= default;'");
18646 }
18647}
18648
18650 const CXXMethodDecl *Old) {
18651 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18652 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18653
18654 if (OldFT->hasExtParameterInfos()) {
18655 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18656 // A parameter of the overriding method should be annotated with noescape
18657 // if the corresponding parameter of the overridden method is annotated.
18658 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18659 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18660 Diag(New->getParamDecl(I)->getLocation(),
18661 diag::warn_overriding_method_missing_noescape);
18662 Diag(Old->getParamDecl(I)->getLocation(),
18663 diag::note_overridden_marked_noescape);
18664 }
18665 }
18666
18667 // SME attributes must match when overriding a function declaration.
18668 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18669 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18670 << New << New->getType() << Old->getType();
18671 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18672 return true;
18673 }
18674
18675 // Virtual overrides must have the same code_seg.
18676 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18677 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18678 if ((NewCSA || OldCSA) &&
18679 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18680 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18681 Diag(Old->getLocation(), diag::note_previous_declaration);
18682 return true;
18683 }
18684
18685 // Virtual overrides: check for matching effects.
18686 if (Context.hasAnyFunctionEffects()) {
18687 const auto OldFX = Old->getFunctionEffects();
18688 const auto NewFXOrig = New->getFunctionEffects();
18689
18690 if (OldFX != NewFXOrig) {
18691 FunctionEffectSet NewFX(NewFXOrig);
18692 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18694 for (const auto &Diff : Diffs) {
18695 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18697 break;
18699 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18700 << Diff.effectName();
18701 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18702 << Old->getReturnTypeSourceRange();
18703 break;
18705 NewFX.insert(Diff.Old.value(), Errs);
18706 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18707 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18709 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18710 NewFT->getParamTypes(), EPI);
18711 New->setType(ModQT);
18712 if (Errs.empty()) {
18713 // A warning here is somewhat pedantic. Skip this if there was
18714 // already a merge conflict, which is more serious.
18715 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18716 << Diff.effectName();
18717 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18718 << Old->getReturnTypeSourceRange();
18719 }
18720 break;
18721 }
18722 }
18723 }
18724 if (!Errs.empty())
18725 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18726 Old->getLocation());
18727 }
18728 }
18729
18730 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18731
18732 // If the calling conventions match, everything is fine
18733 if (NewCC == OldCC)
18734 return false;
18735
18736 // If the calling conventions mismatch because the new function is static,
18737 // suppress the calling convention mismatch error; the error about static
18738 // function override (err_static_overrides_virtual from
18739 // Sema::CheckFunctionDeclaration) is more clear.
18740 if (New->getStorageClass() == SC_Static)
18741 return false;
18742
18743 Diag(New->getLocation(),
18744 diag::err_conflicting_overriding_cc_attributes)
18745 << New->getDeclName() << New->getType() << Old->getType();
18746 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18747 return true;
18748}
18749
18751 const CXXMethodDecl *Old) {
18752 // CWG2553
18753 // A virtual function shall not be an explicit object member function.
18754 if (!New->isExplicitObjectMemberFunction())
18755 return true;
18756 Diag(New->getParamDecl(0)->getBeginLoc(),
18757 diag::err_explicit_object_parameter_nonmember)
18758 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18760 New->setInvalidDecl();
18761 return false;
18762}
18763
18765 const CXXMethodDecl *Old) {
18766 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18767 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18768
18769 if (Context.hasSameType(NewTy, OldTy) ||
18770 NewTy->isDependentType() || OldTy->isDependentType())
18771 return false;
18772
18773 // Check if the return types are covariant
18774 QualType NewClassTy, OldClassTy;
18775
18776 /// Both types must be pointers or references to classes.
18777 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18778 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18779 NewClassTy = NewPT->getPointeeType();
18780 OldClassTy = OldPT->getPointeeType();
18781 }
18782 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18783 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18784 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18785 NewClassTy = NewRT->getPointeeType();
18786 OldClassTy = OldRT->getPointeeType();
18787 }
18788 }
18789 }
18790
18791 // The return types aren't either both pointers or references to a class type.
18792 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18793 Diag(New->getLocation(),
18794 diag::err_different_return_type_for_overriding_virtual_function)
18795 << New->getDeclName() << NewTy << OldTy
18796 << New->getReturnTypeSourceRange();
18797 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18798 << Old->getReturnTypeSourceRange();
18799
18800 return true;
18801 }
18802
18803 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18804 // C++14 [class.virtual]p8:
18805 // If the class type in the covariant return type of D::f differs from
18806 // that of B::f, the class type in the return type of D::f shall be
18807 // complete at the point of declaration of D::f or shall be the class
18808 // type D.
18809 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18810 if (!RD->isBeingDefined() &&
18811 RequireCompleteType(New->getLocation(), NewClassTy,
18812 diag::err_covariant_return_incomplete,
18813 New->getDeclName()))
18814 return true;
18815 }
18816
18817 // Check if the new class derives from the old class.
18818 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18819 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18820 << New->getDeclName() << NewTy << OldTy
18821 << New->getReturnTypeSourceRange();
18822 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18823 << Old->getReturnTypeSourceRange();
18824 return true;
18825 }
18826
18827 // Check if we the conversion from derived to base is valid.
18829 NewClassTy, OldClassTy,
18830 diag::err_covariant_return_inaccessible_base,
18831 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18832 New->getLocation(), New->getReturnTypeSourceRange(),
18833 New->getDeclName(), nullptr)) {
18834 // FIXME: this note won't trigger for delayed access control
18835 // diagnostics, and it's impossible to get an undelayed error
18836 // here from access control during the original parse because
18837 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18838 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18839 << Old->getReturnTypeSourceRange();
18840 return true;
18841 }
18842 }
18843
18844 // The qualifiers of the return types must be the same.
18845 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18846 Diag(New->getLocation(),
18847 diag::err_covariant_return_type_different_qualifications)
18848 << New->getDeclName() << NewTy << OldTy
18849 << New->getReturnTypeSourceRange();
18850 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18851 << Old->getReturnTypeSourceRange();
18852 return true;
18853 }
18854
18855
18856 // The new class type must have the same or less qualifiers as the old type.
18857 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18858 Diag(New->getLocation(),
18859 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18860 << New->getDeclName() << NewTy << OldTy
18861 << New->getReturnTypeSourceRange();
18862 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18863 << Old->getReturnTypeSourceRange();
18864 return true;
18865 }
18866
18867 return false;
18868}
18869
18871 SourceLocation EndLoc = InitRange.getEnd();
18872 if (EndLoc.isValid())
18873 Method->setRangeEnd(EndLoc);
18874
18875 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18876 Method->setIsPureVirtual();
18877 return false;
18878 }
18879
18880 if (!Method->isInvalidDecl())
18881 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18882 << Method->getDeclName() << InitRange;
18883 return true;
18884}
18885
18887 if (D->getFriendObjectKind())
18888 Diag(D->getLocation(), diag::err_pure_friend);
18889 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18890 CheckPureMethod(M, ZeroLoc);
18891 else
18892 Diag(D->getLocation(), diag::err_illegal_initializer);
18893}
18894
18895/// Invoked when we are about to parse an initializer for the declaration
18896/// 'Dcl'.
18897///
18898/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18899/// static data member of class X, names should be looked up in the scope of
18900/// class X. If the declaration had a scope specifier, a scope will have
18901/// been created and passed in for this purpose. Otherwise, S will be null.
18903 assert(D && !D->isInvalidDecl());
18904
18905 // We will always have a nested name specifier here, but this declaration
18906 // might not be out of line if the specifier names the current namespace:
18907 // extern int n;
18908 // int ::n = 0;
18909 if (S && D->isOutOfLine())
18911
18915}
18916
18918 assert(D);
18919
18920 if (S && D->isOutOfLine())
18922
18924}
18925
18927 // C++ 6.4p2:
18928 // The declarator shall not specify a function or an array.
18929 // The type-specifier-seq shall not contain typedef and shall not declare a
18930 // new class or enumeration.
18932 "Parser allowed 'typedef' as storage class of condition decl.");
18933
18934 Decl *Dcl = ActOnDeclarator(S, D);
18935 if (!Dcl)
18936 return true;
18937
18938 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18939 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18940 << D.getSourceRange();
18941 return true;
18942 }
18943
18944 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18945 VD->setCXXCondDecl();
18946
18947 return Dcl;
18948}
18949
18951 if (!ExternalSource)
18952 return;
18953
18955 ExternalSource->ReadUsedVTables(VTables);
18957 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18958 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18959 = VTablesUsed.find(VTables[I].Record);
18960 // Even if a definition wasn't required before, it may be required now.
18961 if (Pos != VTablesUsed.end()) {
18962 if (!Pos->second && VTables[I].DefinitionRequired)
18963 Pos->second = true;
18964 continue;
18965 }
18966
18967 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18968 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18969 }
18970
18971 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18972}
18973
18975 bool DefinitionRequired) {
18976 // Ignore any vtable uses in unevaluated operands or for classes that do
18977 // not have a vtable.
18978 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18979 CurContext->isDependentContext() || isUnevaluatedContext())
18980 return;
18981 // Do not mark as used if compiling for the device outside of the target
18982 // region.
18983 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18984 !OpenMP().isInOpenMPDeclareTargetContext() &&
18985 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18986 if (!DefinitionRequired)
18988 return;
18989 }
18990
18991 // Try to insert this class into the map.
18993 Class = Class->getCanonicalDecl();
18994 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18995 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18996 if (!Pos.second) {
18997 // If we already had an entry, check to see if we are promoting this vtable
18998 // to require a definition. If so, we need to reappend to the VTableUses
18999 // list, since we may have already processed the first entry.
19000 if (DefinitionRequired && !Pos.first->second) {
19001 Pos.first->second = true;
19002 } else {
19003 // Otherwise, we can early exit.
19004 return;
19005 }
19006 } else {
19007 // The Microsoft ABI requires that we perform the destructor body
19008 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19009 // the deleting destructor is emitted with the vtable, not with the
19010 // destructor definition as in the Itanium ABI.
19011 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19012 CXXDestructorDecl *DD = Class->getDestructor();
19013 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19014 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19015 // If this is an out-of-line declaration, marking it referenced will
19016 // not do anything. Manually call CheckDestructor to look up operator
19017 // delete().
19018 ContextRAII SavedContext(*this, DD);
19019 CheckDestructor(DD);
19020 } else {
19021 MarkFunctionReferenced(Loc, Class->getDestructor());
19022 }
19023 }
19024 }
19025 }
19026
19027 // Local classes need to have their virtual members marked
19028 // immediately. For all other classes, we mark their virtual members
19029 // at the end of the translation unit.
19030 if (Class->isLocalClass())
19031 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19032 else
19033 VTableUses.push_back(std::make_pair(Class, Loc));
19034}
19035
19038 if (VTableUses.empty())
19039 return false;
19040
19041 // Note: The VTableUses vector could grow as a result of marking
19042 // the members of a class as "used", so we check the size each
19043 // time through the loop and prefer indices (which are stable) to
19044 // iterators (which are not).
19045 bool DefinedAnything = false;
19046 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19047 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19048 if (!Class)
19049 continue;
19051 Class->getTemplateSpecializationKind();
19052
19053 SourceLocation Loc = VTableUses[I].second;
19054
19055 bool DefineVTable = true;
19056
19057 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19058 // V-tables for non-template classes with an owning module are always
19059 // uniquely emitted in that module.
19060 if (Class->isInCurrentModuleUnit()) {
19061 DefineVTable = true;
19062 } else if (KeyFunction && !KeyFunction->hasBody()) {
19063 // If this class has a key function, but that key function is
19064 // defined in another translation unit, we don't need to emit the
19065 // vtable even though we're using it.
19066 // The key function is in another translation unit.
19067 DefineVTable = false;
19069 KeyFunction->getTemplateSpecializationKind();
19072 "Instantiations don't have key functions");
19073 (void)TSK;
19074 } else if (!KeyFunction) {
19075 // If we have a class with no key function that is the subject
19076 // of an explicit instantiation declaration, suppress the
19077 // vtable; it will live with the explicit instantiation
19078 // definition.
19079 bool IsExplicitInstantiationDeclaration =
19081 for (auto *R : Class->redecls()) {
19083 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19085 IsExplicitInstantiationDeclaration = true;
19086 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19087 IsExplicitInstantiationDeclaration = false;
19088 break;
19089 }
19090 }
19091
19092 if (IsExplicitInstantiationDeclaration)
19093 DefineVTable = false;
19094 }
19095
19096 // The exception specifications for all virtual members may be needed even
19097 // if we are not providing an authoritative form of the vtable in this TU.
19098 // We may choose to emit it available_externally anyway.
19099 if (!DefineVTable) {
19101 continue;
19102 }
19103
19104 // Mark all of the virtual members of this class as referenced, so
19105 // that we can build a vtable. Then, tell the AST consumer that a
19106 // vtable for this class is required.
19107 DefinedAnything = true;
19109 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19110 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19111 Consumer.HandleVTable(Class);
19112
19113 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19114 // no key function or the key function is inlined. Don't warn in C++ ABIs
19115 // that lack key functions, since the user won't be able to make one.
19116 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19117 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19119 const FunctionDecl *KeyFunctionDef = nullptr;
19120 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19121 KeyFunctionDef->isInlined()))
19122 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19123 }
19124 }
19125 VTableUses.clear();
19126
19127 return DefinedAnything;
19128}
19129
19131 const CXXRecordDecl *RD) {
19132 for (const auto *I : RD->methods())
19133 if (I->isVirtual() && !I->isPureVirtual())
19134 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19135}
19136
19138 const CXXRecordDecl *RD,
19139 bool ConstexprOnly) {
19140 // Mark all functions which will appear in RD's vtable as used.
19141 CXXFinalOverriderMap FinalOverriders;
19142 RD->getFinalOverriders(FinalOverriders);
19143 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
19144 E = FinalOverriders.end();
19145 I != E; ++I) {
19146 for (OverridingMethods::const_iterator OI = I->second.begin(),
19147 OE = I->second.end();
19148 OI != OE; ++OI) {
19149 assert(OI->second.size() > 0 && "no final overrider");
19150 CXXMethodDecl *Overrider = OI->second.front().Method;
19151
19152 // C++ [basic.def.odr]p2:
19153 // [...] A virtual member function is used if it is not pure. [...]
19154 if (!Overrider->isPureVirtual() &&
19155 (!ConstexprOnly || Overrider->isConstexpr()))
19156 MarkFunctionReferenced(Loc, Overrider);
19157 }
19158 }
19159
19160 // Only classes that have virtual bases need a VTT.
19161 if (RD->getNumVBases() == 0)
19162 return;
19163
19164 for (const auto &I : RD->bases()) {
19165 const auto *Base = I.getType()->castAsCXXRecordDecl();
19166 if (Base->getNumVBases() == 0)
19167 continue;
19169 }
19170}
19171
19172static
19177 Sema &S) {
19178 if (Ctor->isInvalidDecl())
19179 return;
19180
19182
19183 // Target may not be determinable yet, for instance if this is a dependent
19184 // call in an uninstantiated template.
19185 if (Target) {
19186 const FunctionDecl *FNTarget = nullptr;
19187 (void)Target->hasBody(FNTarget);
19188 Target = const_cast<CXXConstructorDecl*>(
19189 cast_or_null<CXXConstructorDecl>(FNTarget));
19190 }
19191
19192 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19193 // Avoid dereferencing a null pointer here.
19194 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19195
19196 if (!Current.insert(Canonical).second)
19197 return;
19198
19199 // We know that beyond here, we aren't chaining into a cycle.
19200 if (!Target || !Target->isDelegatingConstructor() ||
19201 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19202 Valid.insert_range(Current);
19203 Current.clear();
19204 // We've hit a cycle.
19205 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19206 Current.count(TCanonical)) {
19207 // If we haven't diagnosed this cycle yet, do so now.
19208 if (!Invalid.count(TCanonical)) {
19209 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19210 diag::warn_delegating_ctor_cycle)
19211 << Ctor;
19212
19213 // Don't add a note for a function delegating directly to itself.
19214 if (TCanonical != Canonical)
19215 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19216
19218 while (C->getCanonicalDecl() != Canonical) {
19219 const FunctionDecl *FNTarget = nullptr;
19220 (void)C->getTargetConstructor()->hasBody(FNTarget);
19221 assert(FNTarget && "Ctor cycle through bodiless function");
19222
19223 C = const_cast<CXXConstructorDecl*>(
19224 cast<CXXConstructorDecl>(FNTarget));
19225 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19226 }
19227 }
19228
19229 Invalid.insert_range(Current);
19230 Current.clear();
19231 } else {
19233 }
19234}
19235
19236
19239
19240 for (DelegatingCtorDeclsType::iterator
19241 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19242 E = DelegatingCtorDecls.end();
19243 I != E; ++I)
19244 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19245
19246 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
19247 (*CI)->setInvalidDecl();
19248}
19249
19250namespace {
19251 /// AST visitor that finds references to the 'this' expression.
19252class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19253 Sema &S;
19254
19255public:
19256 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19257
19258 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19259 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19260 << E->isImplicit();
19261 return false;
19262 }
19263};
19264}
19265
19267 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19268 if (!TSInfo)
19269 return false;
19270
19271 TypeLoc TL = TSInfo->getTypeLoc();
19273 if (!ProtoTL)
19274 return false;
19275
19276 // C++11 [expr.prim.general]p3:
19277 // [The expression this] shall not appear before the optional
19278 // cv-qualifier-seq and it shall not appear within the declaration of a
19279 // static member function (although its type and value category are defined
19280 // within a static member function as they are within a non-static member
19281 // function). [ Note: this is because declaration matching does not occur
19282 // until the complete declarator is known. - end note ]
19283 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19284 FindCXXThisExpr Finder(*this);
19285
19286 // If the return type came after the cv-qualifier-seq, check it now.
19287 if (Proto->hasTrailingReturn() &&
19288 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19289 return true;
19290
19291 // Check the exception specification.
19293 return true;
19294
19295 // Check the trailing requires clause
19296 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19297 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19298 return true;
19299
19301}
19302
19304 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19305 if (!TSInfo)
19306 return false;
19307
19308 TypeLoc TL = TSInfo->getTypeLoc();
19310 if (!ProtoTL)
19311 return false;
19312
19313 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19314 FindCXXThisExpr Finder(*this);
19315
19316 switch (Proto->getExceptionSpecType()) {
19317 case EST_Unparsed:
19318 case EST_Uninstantiated:
19319 case EST_Unevaluated:
19320 case EST_BasicNoexcept:
19321 case EST_NoThrow:
19322 case EST_DynamicNone:
19323 case EST_MSAny:
19324 case EST_None:
19325 break;
19326
19328 case EST_NoexceptFalse:
19329 case EST_NoexceptTrue:
19330 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19331 return true;
19332 [[fallthrough]];
19333
19334 case EST_Dynamic:
19335 for (const auto &E : Proto->exceptions()) {
19336 if (!Finder.TraverseType(E))
19337 return true;
19338 }
19339 break;
19340 }
19341
19342 return false;
19343}
19344
19346 FindCXXThisExpr Finder(*this);
19347
19348 // Check attributes.
19349 for (const auto *A : Method->attrs()) {
19350 // FIXME: This should be emitted by tblgen.
19351 Expr *Arg = nullptr;
19352 ArrayRef<Expr *> Args;
19353 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19354 Arg = G->getArg();
19355 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19356 Arg = G->getArg();
19357 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19358 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19359 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19360 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19361 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19362 Arg = LR->getArg();
19363 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19364 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19365 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19366 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19367 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19368 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19369 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19370 Arg = AC->getSuccessValue();
19371 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19372 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19373 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19374
19375 if (Arg && !Finder.TraverseStmt(Arg))
19376 return true;
19377
19378 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19379 if (!Finder.TraverseStmt(Args[I]))
19380 return true;
19381 }
19382 }
19383
19384 return false;
19385}
19386
19388 bool IsTopLevel, ExceptionSpecificationType EST,
19389 ArrayRef<ParsedType> DynamicExceptions,
19390 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19391 SmallVectorImpl<QualType> &Exceptions,
19393 Exceptions.clear();
19394 ESI.Type = EST;
19395 if (EST == EST_Dynamic) {
19396 Exceptions.reserve(DynamicExceptions.size());
19397 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19398 // FIXME: Preserve type source info.
19399 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19400
19401 if (IsTopLevel) {
19403 collectUnexpandedParameterPacks(ET, Unexpanded);
19404 if (!Unexpanded.empty()) {
19406 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19407 Unexpanded);
19408 continue;
19409 }
19410 }
19411
19412 // Check that the type is valid for an exception spec, and
19413 // drop it if not.
19414 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19415 Exceptions.push_back(ET);
19416 }
19417 ESI.Exceptions = Exceptions;
19418 return;
19419 }
19420
19421 if (isComputedNoexcept(EST)) {
19422 assert((NoexceptExpr->isTypeDependent() ||
19423 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19424 Context.BoolTy) &&
19425 "Parser should have made sure that the expression is boolean");
19426 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19427 ESI.Type = EST_BasicNoexcept;
19428 return;
19429 }
19430
19431 ESI.NoexceptExpr = NoexceptExpr;
19432 return;
19433 }
19434}
19435
19437 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19438 ArrayRef<ParsedType> DynamicExceptions,
19439 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19440 if (!D)
19441 return;
19442
19443 // Dig out the function we're referring to.
19444 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19445 D = FTD->getTemplatedDecl();
19446
19447 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19448 if (!FD)
19449 return;
19450
19451 // Check the exception specification.
19454 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19455 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19456 ESI);
19457
19458 // Update the exception specification on the function type.
19459 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19460
19461 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19462 if (MD->isStatic())
19464
19465 if (MD->isVirtual()) {
19466 // Check overrides, which we previously had to delay.
19467 for (const CXXMethodDecl *O : MD->overridden_methods())
19469 }
19470 }
19471}
19472
19473/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19474///
19476 SourceLocation DeclStart, Declarator &D,
19477 Expr *BitWidth,
19478 InClassInitStyle InitStyle,
19479 AccessSpecifier AS,
19480 const ParsedAttr &MSPropertyAttr) {
19481 const IdentifierInfo *II = D.getIdentifier();
19482 if (!II) {
19483 Diag(DeclStart, diag::err_anonymous_property);
19484 return nullptr;
19485 }
19487
19489 QualType T = TInfo->getType();
19490 if (getLangOpts().CPlusPlus) {
19492
19495 D.setInvalidType();
19496 T = Context.IntTy;
19497 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19498 }
19499 }
19500
19502
19504 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19505 << getLangOpts().CPlusPlus17;
19508 diag::err_invalid_thread)
19510
19511 // Check to see if this name was declared as a member previously
19512 NamedDecl *PrevDecl = nullptr;
19513 LookupResult Previous(*this, II, Loc, LookupMemberName,
19515 LookupName(Previous, S);
19516 switch (Previous.getResultKind()) {
19519 PrevDecl = Previous.getAsSingle<NamedDecl>();
19520 break;
19521
19523 PrevDecl = Previous.getRepresentativeDecl();
19524 break;
19525
19529 break;
19530 }
19531
19532 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19533 // Maybe we will complain about the shadowed template parameter.
19535 // Just pretend that we didn't see the previous declaration.
19536 PrevDecl = nullptr;
19537 }
19538
19539 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19540 PrevDecl = nullptr;
19541
19542 SourceLocation TSSL = D.getBeginLoc();
19543 MSPropertyDecl *NewPD =
19544 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19545 MSPropertyAttr.getPropertyDataGetter(),
19546 MSPropertyAttr.getPropertyDataSetter());
19547 ProcessDeclAttributes(TUScope, NewPD, D);
19548 NewPD->setAccess(AS);
19549
19550 if (NewPD->isInvalidDecl())
19551 Record->setInvalidDecl();
19552
19554 NewPD->setModulePrivate();
19555
19556 if (NewPD->isInvalidDecl() && PrevDecl) {
19557 // Don't introduce NewFD into scope; there's already something
19558 // with the same name in the same scope.
19559 } else if (II) {
19560 PushOnScopeChains(NewPD, S);
19561 } else
19562 Record->addDecl(NewPD);
19563
19564 return NewPD;
19565}
19566
19568 Declarator &Declarator, unsigned TemplateParameterDepth) {
19569 auto &Info = InventedParameterInfos.emplace_back();
19570 TemplateParameterList *ExplicitParams = nullptr;
19571 ArrayRef<TemplateParameterList *> ExplicitLists =
19573 if (!ExplicitLists.empty()) {
19574 bool IsMemberSpecialization, IsInvalid;
19577 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19578 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19579 /*SuppressDiagnostic=*/true);
19580 }
19581 // C++23 [dcl.fct]p23:
19582 // An abbreviated function template can have a template-head. The invented
19583 // template-parameters are appended to the template-parameter-list after
19584 // the explicitly declared template-parameters.
19585 //
19586 // A template-head must have one or more template-parameters (read:
19587 // 'template<>' is *not* a template-head). Only append the invented
19588 // template parameters if we matched the nested-name-specifier to a non-empty
19589 // TemplateParameterList.
19590 if (ExplicitParams && !ExplicitParams->empty()) {
19591 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19592 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19593 Info.NumExplicitTemplateParams = ExplicitParams->size();
19594 } else {
19595 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19596 Info.NumExplicitTemplateParams = 0;
19597 }
19598}
19599
19601 auto &FSI = InventedParameterInfos.back();
19602 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19603 if (FSI.NumExplicitTemplateParams != 0) {
19604 TemplateParameterList *ExplicitParams =
19608 Context, ExplicitParams->getTemplateLoc(),
19609 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19610 ExplicitParams->getRAngleLoc(),
19611 ExplicitParams->getRequiresClause()));
19612 } else {
19615 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19616 SourceLocation(), /*RequiresClause=*/nullptr));
19617 }
19618 }
19619 InventedParameterInfos.pop_back();
19620}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
This file declares semantic analysis for CUDA constructs.
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, llvm::SmallVectorImpl< Expr * > &Converted, const MultiLevelTemplateArgumentList &TemplateArgsLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind, CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static ClassTemplateDecl * LookupStdClassTemplate(Sema &S, SourceLocation Loc, const char *ClassName, bool *WasMalformed)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location, FieldDecl *Field)
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location, CXXRecordDecl *ClassDecl)
static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc, const CXXRecordDecl *OrigRD, QualType DecompType, DeclAccessPair BasePair)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
DeclarationNameTable DeclarationNames
Definition ASTContext.h:741
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:737
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:790
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType BuiltinFnTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:856
CanQualType getCanonicalTagType(const TagDecl *TD) const
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
TypeLoc getElementLoc() const
Definition TypeLoc.h:1787
QualType getElementType() const
Definition TypeBase.h:3732
Attr - This represents one attribute.
Definition Attr.h:44
attr::Kind getKind() const
Definition Attr.h:90
bool isInherited() const
Definition Attr.h:99
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:97
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3496
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3574
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3403
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3566
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3412
Expr * getLHS() const
Definition Expr.h:4022
Expr * getRHS() const
Definition Expr.h:4024
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:4979
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
Opcode getOpcode() const
Definition Expr.h:4017
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2137
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3594
void setBinding(QualType DeclaredType, Expr *Binding)
Set the binding for this BindingDecl, along with its declared type (which should be a possibly-cv-qua...
Definition DeclCXX.h:4223
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4229
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Wrapper for source info for block pointers.
Definition TypeLoc.h:1506
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
CXXBasePath & front()
bool isRecordingPaths() const
Whether we are recording paths.
paths_iterator begin()
paths_iterator end()
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
void setOrigin(const CXXRecordDecl *Rec)
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
void clear()
Clear the base-paths results.
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:723
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition ExprCXX.cpp:1180
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool isImmediateEscalating() const
Definition ExprCXX.h:1707
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2847
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:3013
ExplicitSpecifier getExplicitSpecifier()
Definition DeclCXX.h:2676
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2701
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:2990
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:3008
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2842
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2983
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2541
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2916
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2903
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2449
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2503
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2515
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3098
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:1753
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:741
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2703
bool isVirtual() const
Definition DeclCXX.h:2184
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2488
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2283
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2232
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2778
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2772
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2762
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isInstance() const
Definition DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2279
bool isStatic() const
Definition DeclCXX.cpp:2401
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
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:1270
friend_range friends() const
Definition DeclFriend.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1341
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:607
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1240
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1673
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1001
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:820
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:714
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1420
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1391
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1370
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:706
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1500
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:961
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1356
base_class_range bases()
Definition DeclCXX.h:608
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:600
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1301
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:892
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:910
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:931
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1721
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1263
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1278
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:973
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:595
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:697
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1282
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:726
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1328
base_class_range vbases()
Definition DeclCXX.h:625
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
ctor_range ctors() const
Definition DeclCXX.h:670
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:867
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1221
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1236
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:858
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:799
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1402
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1293
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1200
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:793
bool hasDefinition() const
Definition DeclCXX.h:561
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:916
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1007
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition DeclCXX.h:902
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:994
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1380
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1013
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1414
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1748
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:805
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:555
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:846
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:983
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:925
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1306
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:946
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
Represents the this expression in C++.
Definition ExprCXX.h:1155
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1175
bool isImplicit() const
Definition ExprCXX.h:1178
SourceLocation getLocation() const
Definition ExprCXX.h:1172
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
arg_range arguments()
Definition Expr.h:3129
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastKind getCastKind() const
Definition Expr.h:3654
Expr * getSubExpr()
Definition Expr.h:3660
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
body_range body()
Definition Stmt.h:1783
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:390
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3677
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3741
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3385
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition DeclBase.h:1382
DeclListNode::iterator iterator
Definition DeclBase.h:1392
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2393
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2578
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2375
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
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:484
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
SourceLocation getBeginLoc() const
Definition Expr.h:1349
bool isImmediateEscalating() const
Definition Expr.h:1478
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
bool isModulePrivateSpecified() const
Definition DeclSpec.h:799
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:661
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:619
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:234
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:530
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
TST getTypeSpecType() const
Definition DeclSpec.h:507
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:586
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:797
ParsedType getRepAsType() const
Definition DeclSpec.h:517
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:795
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:593
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:587
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:625
Expr * getRepAsExpr() const
Definition DeclSpec.h:525
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:588
TypeSpecifierType TST
Definition DeclSpec.h:247
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition DeclSpec.cpp:991
void ClearConstexprSpec()
Definition DeclSpec.h:811
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:590
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:552
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:591
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:589
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:791
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
static const TST TST_auto
Definition DeclSpec.h:288
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
decl_range decls()
Definition Stmt.h:1659
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1637
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
bool isInStdNamespace() const
Definition DeclBase.cpp:427
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:568
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:588
unsigned getIdentifierNamespace() const
Definition DeclBase.h:889
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
void setLocalOwningModule(Module *M)
Definition DeclBase.h:829
void setImplicit(bool I=true)
Definition DeclBase.h:594
void setReferenced(bool R=true)
Definition DeclBase.h:623
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:553
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:881
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:779
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:854
unsigned getNumTemplateParameterLists() const
Definition Decl.h:861
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:813
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition DeclSpec.cpp:296
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2484
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2313
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2385
bool hasGroupingParens() const
Definition DeclSpec.h:2693
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2687
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isRedeclaration() const
Definition DeclSpec.h:2739
DeclaratorContext getContext() const
Definition DeclSpec.h:2046
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2042
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isFunctionDefinition() const
Definition DeclSpec.h:2711
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2623
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2630
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2185
bool isInvalidType() const
Definition DeclSpec.h:2688
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2300
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
A decomposition declaration.
Definition DeclCXX.h:4249
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4287
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1762
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1802
SourceRange getSourceRange() const
Definition DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1808
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:950
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5762
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:3420
Represents an enum.
Definition Decl.h:4004
enumerator_range enumerators() const
Definition Decl.h:4141
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
const Expr * getExpr() const
Definition DeclCXX.h:1933
void setExpr(Expr *E)
Definition DeclCXX.h:1958
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1957
This represents one expression.
Definition Expr.h:112
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3248
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3257
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4666
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3337
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4656
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3331
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4676
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3404
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3263
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:115
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3132
Represents a function declaration or definition.
Definition Decl.h:1999
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2641
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3271
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2866
bool isTrivialForCall() const
Definition Decl.h:2379
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2475
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3788
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2313
bool isImmediateFunction() const
Definition Decl.cpp:3328
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3152
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3965
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3539
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
SourceLocation getDefaultLoc() const
Definition Decl.h:2397
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2388
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2779
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
param_iterator param_begin()
Definition Decl.h:2783
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2820
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2325
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2539
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2485
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3131
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4198
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2885
bool isStatic() const
Definition Decl.h:2926
void setTrivial(bool IT)
Definition Decl.h:2377
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2637
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2352
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3559
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3303
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3543
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3547
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3551
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4490
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2930
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2472
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
void setDefaulted(bool D=true)
Definition Decl.h:2385
bool isConsteval() const
Definition Decl.h:2481
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2409
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:2859
void setBody(Stmt *B)
Definition Decl.cpp:3283
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2343
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3820
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
size_t param_size() const
Definition Decl.h:2787
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2210
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
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:3238
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition Decl.cpp:3186
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2802
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2682
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5200
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5592
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5232
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5064
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1816
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
unsigned getNumParams() const
Definition TypeBase.h:5542
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5684
const QualType * param_type_iterator
Definition TypeBase.h:5702
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5629
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5718
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5733
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Wrapper for source info for functions.
Definition TypeLoc.h:1624
unsigned getNumParams() const
Definition TypeLoc.h:1696
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1702
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1703
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1705
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4683
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
CallingConv getCallConv() const
Definition TypeBase.h:4815
QualType getReturnType() const
Definition TypeBase.h:4800
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2259
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1731
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3485
void setInherited(bool I)
Definition Attr.h:156
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2587
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
Describes an C or C++ initializer list.
Definition Expr.h:5233
unsigned getNumInits() const
Definition Expr.h:5263
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
child_range children()
Definition Expr.h:5432
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3615
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1358
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1371
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:1020
Represents a linkage specification.
Definition DeclCXX.h:3015
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3200
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3057
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void 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.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
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
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
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:4344
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3669
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
Wrapper for source info for member pointers.
Definition TypeLoc.h:1524
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
Describes a module or submodule.
Definition Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
bool isExplicitGlobalModule() const
Definition Module.h:242
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
Represents a C++ namespace alias.
Definition DeclCXX.h:3201
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3301
Represents C++ namespaces and their aliases.
Definition Decl.h:572
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3238
Represent a C++ namespace.
Definition Decl.h:591
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:647
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3261
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:674
void setRBraceLoc(SourceLocation L)
Definition Decl.h:693
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:290
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4851
Represents a parameter to a function.
Definition Decl.h:1789
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3014
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1930
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1918
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3019
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3039
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1822
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1922
bool hasInheritedDefaultArg() const
Definition Decl.h:1934
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:2946
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3044
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3050
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1938
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2969
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:470
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:464
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:903
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
bool isAddressDiscriminated() const
Definition TypeBase.h:265
Wrapper for source info for pointers.
Definition TypeLoc.h:1493
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6762
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8470
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8331
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2695
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8450
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
void removeAddressSpace()
Definition TypeBase.h:596
void removeVolatile()
Definition TypeBase.h:469
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
Represents a struct/union/class.
Definition Decl.h:4309
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
bool hasObjectMember() const
Definition Decl.h:4369
field_iterator field_end() const
Definition Decl.h:4515
field_range fields() const
Definition Decl.h:4512
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4497
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4361
bool field_empty() const
Definition Decl.h:4520
field_iterator field_begin() const
Definition Decl.cpp:5154
RedeclarableTemplateDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5309
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:409
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition Scope.h:643
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
A RAII object to enter scope of a compound statement.
Definition Sema.h:1289
A RAII object to temporarily push a declaration context.
Definition Sema.h:3475
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6320
DefaultedComparisonKind asComparison() const
Definition Sema.h:6352
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6349
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5418
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5460
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:9248
CXXMethodDecl * getMethod() const
Definition Sema.h:9260
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13391
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7675
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:853
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12943
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6509
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6271
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9290
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9317
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9325
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9313
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9298
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:405
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13518
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1504
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6246
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1240
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6482
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:6463
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1444
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7796
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition Sema.h:1659
@ AR_accessible
Definition Sema.h:1657
@ AR_inaccessible
Definition Sema.h:1658
@ AR_delayed
Definition Sema.h:1660
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:2442
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:2311
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4131
@ Default
= default ;
Definition Sema.h:4133
@ Delete
deleted-function-body
Definition Sema.h:4139
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:48
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2048
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:1282
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.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1489
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:924
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6489
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6573
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
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:6041
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6055
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6052
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6049
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6043
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6046
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6504
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:1190
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12080
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1666
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8314
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2330
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:919
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
@ UPPC_RequiresClause
Definition Sema.h:14295
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14250
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14268
@ UPPC_Initializer
An initializer.
Definition Sema.h:14259
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14229
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14253
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14262
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14232
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14235
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14241
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:917
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:5820
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1281
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1280
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6467
SemaHLSL & HLSL()
Definition Sema.h:1454
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:5826
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5200
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5207
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6460
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6565
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6497
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void ExitDeclaratorContext(Scope *S)
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:12955
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:5816
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15330
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:9816
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)
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:6934
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6474
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1417
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6493
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8129
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13798
SourceManager & getSourceManager() const
Definition Sema.h:922
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9276
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:5936
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
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:218
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15285
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6485
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1555
ASTConsumer & Consumer
Definition Sema.h:1283
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:4629
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6695
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6705
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6674
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1245
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1285
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:1284
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7745
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6469
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1559
void PopDeclContext()
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6501
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:337
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6245
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
Decl * ActOnDeclarator(Scope *S, Declarator &D)
AbstractDiagSelID
Definition Sema.h:6191
@ AbstractVariableType
Definition Sema.h:6195
@ AbstractReturnType
Definition Sema.h:6193
@ AbstractNone
Definition Sema.h:6192
@ AbstractFieldType
Definition Sema.h:6196
@ AbstractArrayType
Definition Sema.h:6199
@ AbstractParamType
Definition Sema.h:6194
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8318
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6380
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6385
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6382
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:436
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3468
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:653
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8608
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() 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:3567
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
child_range children()
Definition Stmt.cpp:295
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
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:1799
bool isUnevaluated() const
Definition Expr.h:1921
StringRef getString() const
Definition Expr.h:1867
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3829
StringRef getKindName() const
Definition Decl.h:3904
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
TagKind getTagKind() const
Definition Decl.h:3908
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3854
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:810
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1897
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
The top declaration context.
Definition Decl.h:104
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3685
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5684
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3704
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:3510
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1417
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:116
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1921
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
bool isUndeducedAutoType() const
Definition TypeBase.h:8708
bool isRValueReferenceType() const
Definition TypeBase.h:8554
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8621
bool isPointerType() const
Definition TypeBase.h:8522
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:65
bool isLValueReferenceType() const
Definition TypeBase.h:8550
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9051
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9021
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8518
bool isStructureOrClassType() const
Definition Type.cpp:706
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isRecordType() const
Definition TypeBase.h:8649
bool isUnionType() const
Definition Type.cpp:718
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
QualType getUnderlyingType() const
Definition Decl.h:3614
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
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:5036
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1034
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1210
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1042
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1056
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1045
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
The iterator over UnresolvedSets.
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4118
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3546
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:787
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4037
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3525
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3940
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3497
Represents a C++ using-declaration.
Definition DeclCXX.h:3591
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3640
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3628
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3632
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3434
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3618
Represents C++ using-directive.
Definition DeclCXX.h:3096
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3217
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3792
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3455
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3477
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3435
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5465
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2151
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1568
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2260
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2190
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2836
void setCXXCondDecl()
Definition Decl.h:1614
bool isInlineSpecified() const
Definition Decl.h:1553
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2575
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1225
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:1207
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2851
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1176
const Expr * getInit() const
Definition Decl.h:1367
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:951
void setInit(Expr *I)
Definition Decl.cpp:2477
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1167
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:2528
void setExceptionVariable(bool EV)
Definition Decl.h:1496
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2754
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2774
SourceLocation getLastLocation() const
Definition DeclSpec.h:2786
bool isOverrideSpecified() const
Definition DeclSpec.h:2773
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2778
bool isFinalSpecified() const
Definition DeclSpec.h:2776
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2777
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition ScopeInfo.h:179
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition Interp.h:985
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:865
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_decltype
Definition Specifiers.h:89
@ TST_typename_pack_indexing
Definition Specifiers.h:97
@ TST_decltype_auto
Definition Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:819
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:815
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:811
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:510
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3007
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:664
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:274
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1541
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:630
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:235
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
@ AS_private
Definition Specifiers.h:126
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Language
The language for the input, used to select and validate the language standard and possible actions.
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
const FunctionProtoType * T
llvm::Expected< QualType > ExpectedType
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
ReservedLiteralSuffixIdStatus
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5888
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5893
@ Struct
The "struct" keyword.
Definition TypeBase.h:5890
@ Class
The "class" keyword.
Definition TypeBase.h:5899
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:559
@ Type
The name was classified as a type.
Definition Sema.h:561
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4288
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4302
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4297
AllowFoldKind
Definition Sema.h:652
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:424
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Concept_template
The name refers to a concept.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:117
TypeAwareAllocationMode
Definition ExprCXX.h:2253
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:642
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:647
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:644
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:376
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:382
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2260
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:834
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:832
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:830
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5863
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
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:1338
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1398
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1347
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1401
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1499
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1528
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1531
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1437
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1524
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1313
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
SourceRange getSourceRange() const
Definition DeclSpec.h:1233
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
Holds information about the various types of exception specification.
Definition TypeBase.h:5321
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5333
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5323
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5326
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5329
Extra information about a function prototype.
Definition TypeBase.h:5349
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5927
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12960
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13083
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13054
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13051
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13004
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13022
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13086
Abstract class used to diagnose incomplete types.
Definition Sema.h:8210
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:105