clang 19.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
46#include "clang/Sema/Template.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/ScopeExit.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/Support/ConvertUTF.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include <map>
55#include <optional>
56#include <set>
57
58using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// CheckDefaultArgumentVisitor
62//===----------------------------------------------------------------------===//
63
64namespace {
65/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66/// the default argument of a parameter to determine whether it
67/// contains any ill-formed subexpressions. For example, this will
68/// diagnose the use of local variables or parameters within the
69/// default argument expression.
70class CheckDefaultArgumentVisitor
71 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
72 Sema &S;
73 const Expr *DefaultArg;
74
75public:
76 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
77 : S(S), DefaultArg(DefaultArg) {}
78
79 bool VisitExpr(const Expr *Node);
80 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
81 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
82 bool VisitLambdaExpr(const LambdaExpr *Lambda);
83 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
84};
85
86/// VisitExpr - Visit all of the children of this expression.
87bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
88 bool IsInvalid = false;
89 for (const Stmt *SubStmt : Node->children())
90 if (SubStmt)
91 IsInvalid |= Visit(SubStmt);
92 return IsInvalid;
93}
94
95/// VisitDeclRefExpr - Visit a reference to a declaration, to
96/// determine whether this declaration can be used in the default
97/// argument expression.
98bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
99 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
100
101 if (!isa<VarDecl, BindingDecl>(Decl))
102 return false;
103
104 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
105 // C++ [dcl.fct.default]p9:
106 // [...] parameters of a function shall not be used in default
107 // argument expressions, even if they are not evaluated. [...]
108 //
109 // C++17 [dcl.fct.default]p9 (by CWG 2082):
110 // [...] A parameter shall not appear as a potentially-evaluated
111 // expression in a default argument. [...]
112 //
113 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
114 return S.Diag(DRE->getBeginLoc(),
115 diag::err_param_default_argument_references_param)
116 << Param->getDeclName() << DefaultArg->getSourceRange();
117 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
118 // C++ [dcl.fct.default]p7:
119 // Local variables shall not be used in default argument
120 // expressions.
121 //
122 // C++17 [dcl.fct.default]p7 (by CWG 2082):
123 // A local variable shall not appear as a potentially-evaluated
124 // expression in a default argument.
125 //
126 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127 // Note: A local variable cannot be odr-used (6.3) in a default
128 // argument.
129 //
130 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
131 return S.Diag(DRE->getBeginLoc(),
132 diag::err_param_default_argument_references_local)
133 << Decl << DefaultArg->getSourceRange();
134 }
135 return false;
136}
137
138/// VisitCXXThisExpr - Visit a C++ "this" expression.
139bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
140 // C++ [dcl.fct.default]p8:
141 // The keyword this shall not be used in a default argument of a
142 // member function.
143 return S.Diag(ThisE->getBeginLoc(),
144 diag::err_param_default_argument_references_this)
145 << ThisE->getSourceRange();
146}
147
148bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149 const PseudoObjectExpr *POE) {
150 bool Invalid = false;
151 for (const Expr *E : POE->semantics()) {
152 // Look through bindings.
153 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
154 E = OVE->getSourceExpr();
155 assert(E && "pseudo-object binding without source expression?");
156 }
157
158 Invalid |= Visit(E);
159 }
160 return Invalid;
161}
162
163bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
164 // [expr.prim.lambda.capture]p9
165 // a lambda-expression appearing in a default argument cannot implicitly or
166 // explicitly capture any local entity. Such a lambda-expression can still
167 // have an init-capture if any full-expression in its initializer satisfies
168 // the constraints of an expression appearing in a default argument.
169 bool Invalid = false;
170 for (const LambdaCapture &LC : Lambda->captures()) {
171 if (!Lambda->isInitCapture(&LC))
172 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
173 // Init captures are always VarDecl.
174 auto *D = cast<VarDecl>(LC.getCapturedVar());
175 Invalid |= Visit(D->getInit());
176 }
177 return Invalid;
178}
179} // namespace
180
181void
183 const CXXMethodDecl *Method) {
184 // If we have an MSAny spec already, don't bother.
185 if (!Method || ComputedEST == EST_MSAny)
186 return;
187
188 const FunctionProtoType *Proto
189 = Method->getType()->getAs<FunctionProtoType>();
190 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
191 if (!Proto)
192 return;
193
195
196 // If we have a throw-all spec at this point, ignore the function.
197 if (ComputedEST == EST_None)
198 return;
199
200 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
201 EST = EST_BasicNoexcept;
202
203 switch (EST) {
204 case EST_Unparsed:
206 case EST_Unevaluated:
207 llvm_unreachable("should not see unresolved exception specs here");
208
209 // If this function can throw any exceptions, make a note of that.
210 case EST_MSAny:
211 case EST_None:
212 // FIXME: Whichever we see last of MSAny and None determines our result.
213 // We should make a consistent, order-independent choice here.
214 ClearExceptions();
215 ComputedEST = EST;
216 return;
218 ClearExceptions();
219 ComputedEST = EST_None;
220 return;
221 // FIXME: If the call to this decl is using any of its default arguments, we
222 // need to search them for potentially-throwing calls.
223 // If this function has a basic noexcept, it doesn't affect the outcome.
225 case EST_NoexceptTrue:
226 case EST_NoThrow:
227 return;
228 // If we're still at noexcept(true) and there's a throw() callee,
229 // change to that specification.
230 case EST_DynamicNone:
231 if (ComputedEST == EST_BasicNoexcept)
232 ComputedEST = EST_DynamicNone;
233 return;
235 llvm_unreachable(
236 "should not generate implicit declarations for dependent cases");
237 case EST_Dynamic:
238 break;
239 }
240 assert(EST == EST_Dynamic && "EST case not considered earlier.");
241 assert(ComputedEST != EST_None &&
242 "Shouldn't collect exceptions when throw-all is guaranteed.");
243 ComputedEST = EST_Dynamic;
244 // Record the exceptions in this function's exception specification.
245 for (const auto &E : Proto->exceptions())
246 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
247 Exceptions.push_back(E);
248}
249
251 if (!S || ComputedEST == EST_MSAny)
252 return;
253
254 // FIXME:
255 //
256 // C++0x [except.spec]p14:
257 // [An] implicit exception-specification specifies the type-id T if and
258 // only if T is allowed by the exception-specification of a function directly
259 // invoked by f's implicit definition; f shall allow all exceptions if any
260 // function it directly invokes allows all exceptions, and f shall allow no
261 // exceptions if every function it directly invokes allows no exceptions.
262 //
263 // Note in particular that if an implicit exception-specification is generated
264 // for a function containing a throw-expression, that specification can still
265 // be noexcept(true).
266 //
267 // Note also that 'directly invoked' is not defined in the standard, and there
268 // is no indication that we should only consider potentially-evaluated calls.
269 //
270 // Ultimately we should implement the intent of the standard: the exception
271 // specification should be the set of exceptions which can be thrown by the
272 // implicit definition. For now, we assume that any non-nothrow expression can
273 // throw any exception.
274
275 if (Self->canThrow(S))
276 ComputedEST = EST_None;
277}
278
280 SourceLocation EqualLoc) {
281 if (RequireCompleteType(Param->getLocation(), Param->getType(),
282 diag::err_typecheck_decl_incomplete_type))
283 return true;
284
285 // C++ [dcl.fct.default]p5
286 // A default argument expression is implicitly converted (clause
287 // 4) to the parameter type. The default argument expression has
288 // the same semantic constraints as the initializer expression in
289 // a declaration of a variable of the parameter type, using the
290 // copy-initialization semantics (8.5).
292 Param);
294 EqualLoc);
295 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
297 if (Result.isInvalid())
298 return true;
299 Arg = Result.getAs<Expr>();
300
301 CheckCompletedExpr(Arg, EqualLoc);
303
304 return Arg;
305}
306
308 SourceLocation EqualLoc) {
309 // Add the default argument to the parameter
310 Param->setDefaultArg(Arg);
311
312 // We have already instantiated this parameter; provide each of the
313 // instantiations with the uninstantiated default argument.
314 UnparsedDefaultArgInstantiationsMap::iterator InstPos
316 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
317 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
318 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
319
320 // We're done tracking this parameter's instantiations.
322 }
323}
324
325/// ActOnParamDefaultArgument - Check whether the default argument
326/// provided for a function parameter is well-formed. If so, attach it
327/// to the parameter declaration.
328void
330 Expr *DefaultArg) {
331 if (!param || !DefaultArg)
332 return;
333
334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
335 UnparsedDefaultArgLocs.erase(Param);
336
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus) {
339 Diag(EqualLoc, diag::err_param_default_argument)
340 << DefaultArg->getSourceRange();
341 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
342 }
343
344 // Check for unexpanded parameter packs.
346 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
347
348 // C++11 [dcl.fct.default]p3
349 // A default argument expression [...] shall not be specified for a
350 // parameter pack.
351 if (Param->isParameterPack()) {
352 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353 << DefaultArg->getSourceRange();
354 // Recover by discarding the default argument.
355 Param->setDefaultArg(nullptr);
356 return;
357 }
358
359 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
360 if (Result.isInvalid())
361 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
362
363 DefaultArg = Result.getAs<Expr>();
364
365 // Check that the default argument is well-formed
366 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367 if (DefaultArgChecker.Visit(DefaultArg))
368 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
369
370 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371}
372
373/// ActOnParamUnparsedDefaultArgument - We've seen a default
374/// argument for a function parameter, but we can't parse it yet
375/// because we're inside a class definition. Note that this default
376/// argument will be parsed later.
378 SourceLocation EqualLoc,
379 SourceLocation ArgLoc) {
380 if (!param)
381 return;
382
383 ParmVarDecl *Param = cast<ParmVarDecl>(param);
384 Param->setUnparsedDefaultArg();
385 UnparsedDefaultArgLocs[Param] = ArgLoc;
386}
387
388/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389/// the default argument for the parameter param failed.
391 Expr *DefaultArg) {
392 if (!param)
393 return;
394
395 ParmVarDecl *Param = cast<ParmVarDecl>(param);
396 Param->setInvalidDecl();
397 UnparsedDefaultArgLocs.erase(Param);
398 ExprResult RE;
399 if (DefaultArg) {
400 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
401 Param->getType().getNonReferenceType());
402 } else {
403 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
404 Param->getType().getNonReferenceType());
405 }
406 Param->setDefaultArg(RE.get());
407}
408
409/// CheckExtraCXXDefaultArguments - Check for any extra default
410/// arguments in the declarator, which is not a function declaration
411/// or definition and therefore is not permitted to have default
412/// arguments. This routine should be invoked for every declarator
413/// that is not a function declaration or definition.
415 // C++ [dcl.fct.default]p3
416 // A default argument expression shall be specified only in the
417 // parameter-declaration-clause of a function declaration or in a
418 // template-parameter (14.1). It shall not be specified for a
419 // parameter pack. If it is specified in a
420 // parameter-declaration-clause, it shall not occur within a
421 // declarator or abstract-declarator of a parameter-declaration.
422 bool MightBeFunction = D.isFunctionDeclarationContext();
423 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
424 DeclaratorChunk &chunk = D.getTypeObject(i);
425 if (chunk.Kind == DeclaratorChunk::Function) {
426 if (MightBeFunction) {
427 // This is a function declaration. It can have default arguments, but
428 // keep looking in case its return type is a function type with default
429 // arguments.
430 MightBeFunction = false;
431 continue;
432 }
433 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
434 ++argIdx) {
435 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
436 if (Param->hasUnparsedDefaultArg()) {
437 std::unique_ptr<CachedTokens> Toks =
438 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
439 SourceRange SR;
440 if (Toks->size() > 1)
441 SR = SourceRange((*Toks)[1].getLocation(),
442 Toks->back().getLocation());
443 else
444 SR = UnparsedDefaultArgLocs[Param];
445 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
446 << SR;
447 } else if (Param->getDefaultArg()) {
448 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449 << Param->getDefaultArg()->getSourceRange();
450 Param->setDefaultArg(nullptr);
451 }
452 }
453 } else if (chunk.Kind != DeclaratorChunk::Paren) {
454 MightBeFunction = false;
455 }
456 }
457}
458
460 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
461 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
462 });
463}
464
465/// MergeCXXFunctionDecl - Merge two declarations of the same C++
466/// function, once we already know that they have the same
467/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468/// error, false otherwise.
470 Scope *S) {
471 bool Invalid = false;
472
473 // The declaration context corresponding to the scope is the semantic
474 // parent, unless this is a local function declaration, in which case
475 // it is that surrounding function.
476 DeclContext *ScopeDC = New->isLocalExternDecl()
477 ? New->getLexicalDeclContext()
478 : New->getDeclContext();
479
480 // Find the previous declaration for the purpose of default arguments.
481 FunctionDecl *PrevForDefaultArgs = Old;
482 for (/**/; PrevForDefaultArgs;
483 // Don't bother looking back past the latest decl if this is a local
484 // extern declaration; nothing else could work.
485 PrevForDefaultArgs = New->isLocalExternDecl()
486 ? nullptr
487 : PrevForDefaultArgs->getPreviousDecl()) {
488 // Ignore hidden declarations.
489 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
490 continue;
491
492 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
493 !New->isCXXClassMember()) {
494 // Ignore default arguments of old decl if they are not in
495 // the same scope and this is not an out-of-line definition of
496 // a member function.
497 continue;
498 }
499
500 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
501 // If only one of these is a local function declaration, then they are
502 // declared in different scopes, even though isDeclInScope may think
503 // they're in the same scope. (If both are local, the scope check is
504 // sufficient, and if neither is local, then they are in the same scope.)
505 continue;
506 }
507
508 // We found the right previous declaration.
509 break;
510 }
511
512 // C++ [dcl.fct.default]p4:
513 // For non-template functions, default arguments can be added in
514 // later declarations of a function in the same
515 // scope. Declarations in different scopes have completely
516 // distinct sets of default arguments. That is, declarations in
517 // inner scopes do not acquire default arguments from
518 // declarations in outer scopes, and vice versa. In a given
519 // function declaration, all parameters subsequent to a
520 // parameter with a default argument shall have default
521 // arguments supplied in this or previous declarations. A
522 // default argument shall not be redefined by a later
523 // declaration (not even to the same value).
524 //
525 // C++ [dcl.fct.default]p6:
526 // Except for member functions of class templates, the default arguments
527 // in a member function definition that appears outside of the class
528 // definition are added to the set of default arguments provided by the
529 // member function declaration in the class definition.
530 for (unsigned p = 0, NumParams = PrevForDefaultArgs
531 ? PrevForDefaultArgs->getNumParams()
532 : 0;
533 p < NumParams; ++p) {
534 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
535 ParmVarDecl *NewParam = New->getParamDecl(p);
536
537 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
538 bool NewParamHasDfl = NewParam->hasDefaultArg();
539
540 if (OldParamHasDfl && NewParamHasDfl) {
541 unsigned DiagDefaultParamID =
542 diag::err_param_default_argument_redefinition;
543
544 // MSVC accepts that default parameters be redefined for member functions
545 // of template class. The new default parameter's value is ignored.
546 Invalid = true;
547 if (getLangOpts().MicrosoftExt) {
548 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
549 if (MD && MD->getParent()->getDescribedClassTemplate()) {
550 // Merge the old default argument into the new parameter.
551 NewParam->setHasInheritedDefaultArg();
552 if (OldParam->hasUninstantiatedDefaultArg())
554 OldParam->getUninstantiatedDefaultArg());
555 else
556 NewParam->setDefaultArg(OldParam->getInit());
557 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
558 Invalid = false;
559 }
560 }
561
562 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563 // hint here. Alternatively, we could walk the type-source information
564 // for NewParam to find the last source location in the type... but it
565 // isn't worth the effort right now. This is the kind of test case that
566 // is hard to get right:
567 // int f(int);
568 // void g(int (*fp)(int) = f);
569 // void g(int (*fp)(int) = &f);
570 Diag(NewParam->getLocation(), DiagDefaultParamID)
571 << NewParam->getDefaultArgRange();
572
573 // Look for the function declaration where the default argument was
574 // actually written, which may be a declaration prior to Old.
575 for (auto Older = PrevForDefaultArgs;
576 OldParam->hasInheritedDefaultArg(); /**/) {
577 Older = Older->getPreviousDecl();
578 OldParam = Older->getParamDecl(p);
579 }
580
581 Diag(OldParam->getLocation(), diag::note_previous_definition)
582 << OldParam->getDefaultArgRange();
583 } else if (OldParamHasDfl) {
584 // Merge the old default argument into the new parameter unless the new
585 // function is a friend declaration in a template class. In the latter
586 // case the default arguments will be inherited when the friend
587 // declaration will be instantiated.
588 if (New->getFriendObjectKind() == Decl::FOK_None ||
590 // It's important to use getInit() here; getDefaultArg()
591 // strips off any top-level ExprWithCleanups.
592 NewParam->setHasInheritedDefaultArg();
593 if (OldParam->hasUnparsedDefaultArg())
594 NewParam->setUnparsedDefaultArg();
595 else if (OldParam->hasUninstantiatedDefaultArg())
597 OldParam->getUninstantiatedDefaultArg());
598 else
599 NewParam->setDefaultArg(OldParam->getInit());
600 }
601 } else if (NewParamHasDfl) {
602 if (New->getDescribedFunctionTemplate()) {
603 // Paragraph 4, quoted above, only applies to non-template functions.
604 Diag(NewParam->getLocation(),
605 diag::err_param_default_argument_template_redecl)
606 << NewParam->getDefaultArgRange();
607 Diag(PrevForDefaultArgs->getLocation(),
608 diag::note_template_prev_declaration)
609 << false;
610 } else if (New->getTemplateSpecializationKind()
613 // C++ [temp.expr.spec]p21:
614 // Default function arguments shall not be specified in a declaration
615 // or a definition for one of the following explicit specializations:
616 // - the explicit specialization of a function template;
617 // - the explicit specialization of a member function template;
618 // - the explicit specialization of a member function of a class
619 // template where the class template specialization to which the
620 // member function specialization belongs is implicitly
621 // instantiated.
622 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
624 << New->getDeclName()
625 << NewParam->getDefaultArgRange();
626 } else if (New->getDeclContext()->isDependentContext()) {
627 // C++ [dcl.fct.default]p6 (DR217):
628 // Default arguments for a member function of a class template shall
629 // be specified on the initial declaration of the member function
630 // within the class template.
631 //
632 // Reading the tea leaves a bit in DR217 and its reference to DR205
633 // leads me to the conclusion that one cannot add default function
634 // arguments for an out-of-line definition of a member function of a
635 // dependent type.
636 int WhichKind = 2;
638 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
639 if (Record->getDescribedClassTemplate())
640 WhichKind = 0;
641 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
642 WhichKind = 1;
643 else
644 WhichKind = 2;
645 }
646
647 Diag(NewParam->getLocation(),
648 diag::err_param_default_argument_member_template_redecl)
649 << WhichKind
650 << NewParam->getDefaultArgRange();
651 }
652 }
653 }
654
655 // DR1344: If a default argument is added outside a class definition and that
656 // default argument makes the function a special member function, the program
657 // is ill-formed. This can only happen for constructors.
658 if (isa<CXXConstructorDecl>(New) &&
660 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
661 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
662 if (NewSM != OldSM) {
663 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
664 assert(NewParam->hasDefaultArg());
665 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
666 << NewParam->getDefaultArgRange() << NewSM;
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 }
669 }
670
671 const FunctionDecl *Def;
672 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673 // template has a constexpr specifier then all its declarations shall
674 // contain the constexpr specifier.
675 if (New->getConstexprKind() != Old->getConstexprKind()) {
676 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
677 << New << static_cast<int>(New->getConstexprKind())
678 << static_cast<int>(Old->getConstexprKind());
679 Diag(Old->getLocation(), diag::note_previous_declaration);
680 Invalid = true;
681 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
682 Old->isDefined(Def) &&
683 // If a friend function is inlined but does not have 'inline'
684 // specifier, it is a definition. Do not report attribute conflict
685 // in this case, redefinition will be diagnosed later.
686 (New->isInlineSpecified() ||
688 // C++11 [dcl.fcn.spec]p4:
689 // If the definition of a function appears in a translation unit before its
690 // first declaration as inline, the program is ill-formed.
691 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
692 Diag(Def->getLocation(), diag::note_previous_definition);
693 Invalid = true;
694 }
695
696 // C++17 [temp.deduct.guide]p3:
697 // Two deduction guide declarations in the same translation unit
698 // for the same class template shall not have equivalent
699 // parameter-declaration-clauses.
700 if (isa<CXXDeductionGuideDecl>(New) &&
702 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
703 Diag(Old->getLocation(), diag::note_previous_declaration);
704 }
705
706 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707 // argument expression, that declaration shall be a definition and shall be
708 // the only declaration of the function or function template in the
709 // translation unit.
712 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
713 Diag(Old->getLocation(), diag::note_previous_declaration);
714 Invalid = true;
715 }
716
717 // C++11 [temp.friend]p4 (DR329):
718 // When a function is defined in a friend function declaration in a class
719 // template, the function is instantiated when the function is odr-used.
720 // The same restrictions on multiple declarations and definitions that
721 // apply to non-template function declarations and definitions also apply
722 // to these implicit definitions.
723 const FunctionDecl *OldDefinition = nullptr;
725 Old->isDefined(OldDefinition, true))
726 CheckForFunctionRedefinition(New, OldDefinition);
727
728 return Invalid;
729}
730
733 ? diag::warn_cxx23_placeholder_var_definition
734 : diag::ext_placeholder_var_definition);
735}
736
737NamedDecl *
739 MultiTemplateParamsArg TemplateParamLists) {
740 assert(D.isDecompositionDeclarator());
742
743 // The syntax only allows a decomposition declarator as a simple-declaration,
744 // a for-range-declaration, or a condition in Clang, but we parse it in more
745 // cases than that.
747 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
748 << Decomp.getSourceRange();
749 return nullptr;
750 }
751
752 if (!TemplateParamLists.empty()) {
753 // FIXME: There's no rule against this, but there are also no rules that
754 // would actually make it usable, so we reject it for now.
755 Diag(TemplateParamLists.front()->getTemplateLoc(),
756 diag::err_decomp_decl_template);
757 return nullptr;
758 }
759
760 Diag(Decomp.getLSquareLoc(),
762 ? diag::ext_decomp_decl
764 ? diag::ext_decomp_decl_cond
765 : diag::warn_cxx14_compat_decomp_decl)
766 << Decomp.getSourceRange();
767
768 // The semantic context is always just the current context.
769 DeclContext *const DC = CurContext;
770
771 // C++17 [dcl.dcl]/8:
772 // The decl-specifier-seq shall contain only the type-specifier auto
773 // and cv-qualifiers.
774 // C++20 [dcl.dcl]/8:
775 // If decl-specifier-seq contains any decl-specifier other than static,
776 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
777 // C++23 [dcl.pre]/6:
778 // Each decl-specifier in the decl-specifier-seq shall be static,
779 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780 auto &DS = D.getDeclSpec();
781 {
782 // Note: While constrained-auto needs to be checked, we do so separately so
783 // we can emit a better diagnostic.
784 SmallVector<StringRef, 8> BadSpecifiers;
785 SmallVector<SourceLocation, 8> BadSpecifierLocs;
786 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
787 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
788 if (auto SCS = DS.getStorageClassSpec()) {
789 if (SCS == DeclSpec::SCS_static) {
790 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
791 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
792 } else {
793 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
794 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795 }
796 }
797 if (auto TSCS = DS.getThreadStorageClassSpec()) {
798 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
799 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
800 }
801 if (DS.hasConstexprSpecifier()) {
802 BadSpecifiers.push_back(
803 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
804 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
805 }
806 if (DS.isInlineSpecified()) {
807 BadSpecifiers.push_back("inline");
808 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
809 }
810
811 if (!BadSpecifiers.empty()) {
812 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
813 Err << (int)BadSpecifiers.size()
814 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
815 // Don't add FixItHints to remove the specifiers; we do still respect
816 // them when building the underlying variable.
817 for (auto Loc : BadSpecifierLocs)
818 Err << SourceRange(Loc, Loc);
819 } else if (!CPlusPlus20Specifiers.empty()) {
820 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
822 ? diag::warn_cxx17_compat_decomp_decl_spec
823 : diag::ext_decomp_decl_spec);
824 Warn << (int)CPlusPlus20Specifiers.size()
825 << llvm::join(CPlusPlus20Specifiers.begin(),
826 CPlusPlus20Specifiers.end(), " ");
827 for (auto Loc : CPlusPlus20SpecifierLocs)
828 Warn << SourceRange(Loc, Loc);
829 }
830 // We can't recover from it being declared as a typedef.
831 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
832 return nullptr;
833 }
834
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
839 Diag(DS.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding);
841
843 QualType R = TInfo->getType();
844
847 D.setInvalidType();
848
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
851 // specifier here.
852 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854 (D.getNumTypeObjects() == 1 &&
856 Diag(Decomp.getLSquareLoc(),
857 (D.hasGroupingParens() ||
858 (D.getNumTypeObjects() &&
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type)
862 << R;
863
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R->isFunctionType())
868 D.setInvalidType();
869 }
870
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS.isConstrainedAuto()) {
873 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874 assert(TemplRep->Kind == TNK_Concept_template &&
875 "No other template kind should be possible for a constrained auto");
876
877 SourceRange TemplRange{TemplRep->TemplateNameLoc,
878 TemplRep->RAngleLoc.isValid()
879 ? TemplRep->RAngleLoc
880 : TemplRep->TemplateNameLoc};
881 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 }
884
885 // Build the BindingDecls.
887
888 // Build the BindingDecls.
889 for (auto &B : D.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892 IdentifierInfo *VarName = B.Name;
893 assert(VarName && "Cannot have an unnamed binding declaration");
894
898 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
899
900 // It's not permitted to shadow a template parameter name.
901 if (Previous.isSingleResult() &&
902 Previous.getFoundDecl()->isTemplateParameter()) {
904 Previous.getFoundDecl());
905 Previous.clear();
906 }
907
908 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
909
910 // Find the shadowed declaration before filtering for scope.
911 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
913 : nullptr;
914
915 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
916 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
917 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
918 /*AllowInlineNamespace*/false);
919
920 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
921 DC->isFunctionOrMethod() && VarName->isPlaceholder();
922 if (!Previous.empty()) {
923 if (IsPlaceholder) {
924 bool sameDC = (Previous.end() - 1)
925 ->getDeclContext()
926 ->getRedeclContext()
927 ->Equals(DC->getRedeclContext());
928 if (sameDC &&
929 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
930 Previous.clear();
932 }
933 } else {
934 auto *Old = Previous.getRepresentativeDecl();
935 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
936 Diag(Old->getLocation(), diag::note_previous_definition);
937 }
938 } else if (ShadowedDecl && !D.isRedeclaration()) {
939 CheckShadow(BD, ShadowedDecl, Previous);
940 }
941 PushOnScopeChains(BD, S, true);
942 Bindings.push_back(BD);
943 ParsingInitForAutoVars.insert(BD);
944 }
945
946 // There are no prior lookup results for the variable itself, because it
947 // is unnamed.
948 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
949 Decomp.getLSquareLoc());
952
953 // Build the variable that holds the non-decomposed object.
954 bool AddToScope = true;
955 NamedDecl *New =
956 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
957 MultiTemplateParamsArg(), AddToScope, Bindings);
958 if (AddToScope) {
959 S->AddDecl(New);
961 }
962
965
966 return New;
967}
968
971 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
972 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
973 if ((int64_t)Bindings.size() != NumElems) {
974 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
975 << DecompType << (unsigned)Bindings.size()
976 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
977 << toString(NumElems, 10) << (NumElems < Bindings.size());
978 return true;
979 }
980
981 unsigned I = 0;
982 for (auto *B : Bindings) {
983 SourceLocation Loc = B->getLocation();
984 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
985 if (E.isInvalid())
986 return true;
987 E = GetInit(Loc, E.get(), I++);
988 if (E.isInvalid())
989 return true;
990 B->setBinding(ElemType, E.get());
991 }
992
993 return false;
994}
995
998 ValueDecl *Src, QualType DecompType,
999 const llvm::APSInt &NumElems,
1000 QualType ElemType) {
1002 S, Bindings, Src, DecompType, NumElems, ElemType,
1003 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1004 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1005 if (E.isInvalid())
1006 return ExprError();
1007 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1008 });
1009}
1010
1012 ValueDecl *Src, QualType DecompType,
1013 const ConstantArrayType *CAT) {
1014 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1015 llvm::APSInt(CAT->getSize()),
1016 CAT->getElementType());
1017}
1018
1020 ValueDecl *Src, QualType DecompType,
1021 const VectorType *VT) {
1023 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1025 DecompType.getQualifiers()));
1026}
1027
1030 ValueDecl *Src, QualType DecompType,
1031 const ComplexType *CT) {
1033 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1035 DecompType.getQualifiers()),
1036 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1037 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1038 });
1039}
1040
1043 const TemplateParameterList *Params) {
1045 llvm::raw_svector_ostream OS(SS);
1046 bool First = true;
1047 unsigned I = 0;
1048 for (auto &Arg : Args.arguments()) {
1049 if (!First)
1050 OS << ", ";
1051 Arg.getArgument().print(PrintingPolicy, OS,
1053 PrintingPolicy, Params, I));
1054 First = false;
1055 I++;
1056 }
1057 return std::string(OS.str());
1058}
1059
1060static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1061 SourceLocation Loc, StringRef Trait,
1063 unsigned DiagID) {
1064 auto DiagnoseMissing = [&] {
1065 if (DiagID)
1066 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1067 Args, /*Params*/ nullptr);
1068 return true;
1069 };
1070
1071 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1073 if (!Std)
1074 return DiagnoseMissing();
1075
1076 // Look up the trait itself, within namespace std. We can diagnose various
1077 // problems with this lookup even if we've been asked to not diagnose a
1078 // missing specialization, because this can only fail if the user has been
1079 // declaring their own names in namespace std or we don't support the
1080 // standard library implementation in use.
1084 return DiagnoseMissing();
1085 if (Result.isAmbiguous())
1086 return true;
1087
1088 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1089 if (!TraitTD) {
1090 Result.suppressDiagnostics();
1091 NamedDecl *Found = *Result.begin();
1092 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1093 S.Diag(Found->getLocation(), diag::note_declared_at);
1094 return true;
1095 }
1096
1097 // Build the template-id.
1098 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1099 if (TraitTy.isNull())
1100 return true;
1101 if (!S.isCompleteType(Loc, TraitTy)) {
1102 if (DiagID)
1104 Loc, TraitTy, DiagID,
1106 TraitTD->getTemplateParameters()));
1107 return true;
1108 }
1109
1110 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1111 assert(RD && "specialization of class template is not a class?");
1112
1113 // Look up the member of the trait type.
1114 S.LookupQualifiedName(TraitMemberLookup, RD);
1115 return TraitMemberLookup.isAmbiguous();
1116}
1117
1120 uint64_t I) {
1121 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1122 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1123}
1124
1128}
1129
1130namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1131
1132static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1133 llvm::APSInt &Size) {
1136
1139
1140 // Form template argument list for tuple_size<T>.
1141 TemplateArgumentListInfo Args(Loc, Loc);
1143
1144 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145 // it's not tuple-like.
1146 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1147 R.empty())
1148 return IsTupleLike::NotTupleLike;
1149
1150 // If we get this far, we've committed to the tuple interpretation, but
1151 // we can still fail if there actually isn't a usable ::value.
1152
1153 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1154 LookupResult &R;
1156 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1157 : R(R), Args(Args) {}
1158 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1159 SourceLocation Loc) override {
1160 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1162 /*Params*/ nullptr);
1163 }
1164 } Diagnoser(R, Args);
1165
1166 ExprResult E =
1167 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1168 if (E.isInvalid())
1169 return IsTupleLike::Error;
1170
1171 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1172 if (E.isInvalid())
1173 return IsTupleLike::Error;
1174
1175 return IsTupleLike::TupleLike;
1176}
1177
1178/// \return std::tuple_element<I, T>::type.
1180 unsigned I, QualType T) {
1181 // Form template argument list for tuple_element<I, T>.
1182 TemplateArgumentListInfo Args(Loc, Loc);
1183 Args.addArgument(
1186
1187 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1188 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1190 S, R, Loc, "tuple_element", Args,
1191 diag::err_decomp_decl_std_tuple_element_not_specialized))
1192 return QualType();
1193
1194 auto *TD = R.getAsSingle<TypeDecl>();
1195 if (!TD) {
1197 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1199 /*Params*/ nullptr);
1200 if (!R.empty())
1201 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1202 return QualType();
1203 }
1204
1205 return S.Context.getTypeDeclType(TD);
1206}
1207
1208namespace {
1209struct InitializingBinding {
1210 Sema &S;
1211 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1215 Ctx.Entity = BD;
1217 }
1218 ~InitializingBinding() {
1220 }
1221};
1222}
1223
1226 VarDecl *Src, QualType DecompType,
1227 const llvm::APSInt &TupleSize) {
1228 if ((int64_t)Bindings.size() != TupleSize) {
1229 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1230 << DecompType << (unsigned)Bindings.size()
1231 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1232 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1233 return true;
1234 }
1235
1236 if (Bindings.empty())
1237 return false;
1238
1239 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1240
1241 // [dcl.decomp]p3:
1242 // The unqualified-id get is looked up in the scope of E by class member
1243 // access lookup ...
1244 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1245 bool UseMemberGet = false;
1246 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1247 if (auto *RD = DecompType->getAsCXXRecordDecl())
1248 S.LookupQualifiedName(MemberGet, RD);
1249 if (MemberGet.isAmbiguous())
1250 return true;
1251 // ... and if that finds at least one declaration that is a function
1252 // template whose first template parameter is a non-type parameter ...
1253 for (NamedDecl *D : MemberGet) {
1254 if (FunctionTemplateDecl *FTD =
1255 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1256 TemplateParameterList *TPL = FTD->getTemplateParameters();
1257 if (TPL->size() != 0 &&
1258 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1259 // ... the initializer is e.get<i>().
1260 UseMemberGet = true;
1261 break;
1262 }
1263 }
1264 }
1265 }
1266
1267 unsigned I = 0;
1268 for (auto *B : Bindings) {
1269 InitializingBinding InitContext(S, B);
1270 SourceLocation Loc = B->getLocation();
1271
1272 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1273 if (E.isInvalid())
1274 return true;
1275
1276 // e is an lvalue if the type of the entity is an lvalue reference and
1277 // an xvalue otherwise
1278 if (!Src->getType()->isLValueReferenceType())
1279 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1280 E.get(), nullptr, VK_XValue,
1282
1283 TemplateArgumentListInfo Args(Loc, Loc);
1284 Args.addArgument(
1286
1287 if (UseMemberGet) {
1288 // if [lookup of member get] finds at least one declaration, the
1289 // initializer is e.get<i-1>().
1290 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1291 CXXScopeSpec(), SourceLocation(), nullptr,
1292 MemberGet, &Args, nullptr);
1293 if (E.isInvalid())
1294 return true;
1295
1296 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1297 } else {
1298 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1299 // in the associated namespaces.
1302 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args,
1304 /*KnownDependent=*/false);
1305
1306 Expr *Arg = E.get();
1307 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1308 }
1309 if (E.isInvalid())
1310 return true;
1311 Expr *Init = E.get();
1312
1313 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1314 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1315 if (T.isNull())
1316 return true;
1317
1318 // each vi is a variable of type "reference to T" initialized with the
1319 // initializer, where the reference is an lvalue reference if the
1320 // initializer is an lvalue and an rvalue reference otherwise
1321 QualType RefType =
1322 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1323 if (RefType.isNull())
1324 return true;
1325 auto *RefVD = VarDecl::Create(
1326 S.Context, Src->getDeclContext(), Loc, Loc,
1327 B->getDeclName().getAsIdentifierInfo(), RefType,
1329 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1330 RefVD->setTSCSpec(Src->getTSCSpec());
1331 RefVD->setImplicit();
1332 if (Src->isInlineSpecified())
1333 RefVD->setInlineSpecified();
1334 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1335
1338 InitializationSequence Seq(S, Entity, Kind, Init);
1339 E = Seq.Perform(S, Entity, Kind, Init);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1343 if (E.isInvalid())
1344 return true;
1345 RefVD->setInit(E.get());
1347
1349 DeclarationNameInfo(B->getDeclName(), Loc),
1350 RefVD);
1351 if (E.isInvalid())
1352 return true;
1353
1354 B->setBinding(T, E.get());
1355 I++;
1356 }
1357
1358 return false;
1359}
1360
1361/// Find the base class to decompose in a built-in decomposition of a class type.
1362/// This base class search is, unfortunately, not quite like any other that we
1363/// perform anywhere else in C++.
1365 const CXXRecordDecl *RD,
1366 CXXCastPath &BasePath) {
1367 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1368 CXXBasePath &Path) {
1369 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1370 };
1371
1372 const CXXRecordDecl *ClassWithFields = nullptr;
1374 if (RD->hasDirectFields())
1375 // [dcl.decomp]p4:
1376 // Otherwise, all of E's non-static data members shall be public direct
1377 // members of E ...
1378 ClassWithFields = RD;
1379 else {
1380 // ... or of ...
1381 CXXBasePaths Paths;
1382 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1383 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1384 // If no classes have fields, just decompose RD itself. (This will work
1385 // if and only if zero bindings were provided.)
1386 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1387 }
1388
1389 CXXBasePath *BestPath = nullptr;
1390 for (auto &P : Paths) {
1391 if (!BestPath)
1392 BestPath = &P;
1393 else if (!S.Context.hasSameType(P.back().Base->getType(),
1394 BestPath->back().Base->getType())) {
1395 // ... the same ...
1396 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1397 << false << RD << BestPath->back().Base->getType()
1398 << P.back().Base->getType();
1399 return DeclAccessPair();
1400 } else if (P.Access < BestPath->Access) {
1401 BestPath = &P;
1402 }
1403 }
1404
1405 // ... unambiguous ...
1406 QualType BaseType = BestPath->back().Base->getType();
1407 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1408 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1409 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1410 return DeclAccessPair();
1411 }
1412
1413 // ... [accessible, implied by other rules] base class of E.
1414 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1415 *BestPath, diag::err_decomp_decl_inaccessible_base);
1416 AS = BestPath->Access;
1417
1418 ClassWithFields = BaseType->getAsCXXRecordDecl();
1419 S.BuildBasePathArray(Paths, BasePath);
1420 }
1421
1422 // The above search did not check whether the selected class itself has base
1423 // classes with fields, so check that now.
1424 CXXBasePaths Paths;
1425 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1426 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1427 << (ClassWithFields == RD) << RD << ClassWithFields
1428 << Paths.front().back().Base->getType();
1429 return DeclAccessPair();
1430 }
1431
1432 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1433}
1434
1436 ValueDecl *Src, QualType DecompType,
1437 const CXXRecordDecl *OrigRD) {
1438 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1439 diag::err_incomplete_type))
1440 return true;
1441
1442 CXXCastPath BasePath;
1443 DeclAccessPair BasePair =
1444 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1445 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1446 if (!RD)
1447 return true;
1449 DecompType.getQualifiers());
1450
1451 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1452 unsigned NumFields = llvm::count_if(
1453 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1454 assert(Bindings.size() != NumFields);
1455 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1456 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1457 << (NumFields < Bindings.size());
1458 return true;
1459 };
1460
1461 // all of E's non-static data members shall be [...] well-formed
1462 // when named as e.name in the context of the structured binding,
1463 // E shall not have an anonymous union member, ...
1464 unsigned I = 0;
1465 for (auto *FD : RD->fields()) {
1466 if (FD->isUnnamedBitfield())
1467 continue;
1468
1469 // All the non-static data members are required to be nameable, so they
1470 // must all have names.
1471 if (!FD->getDeclName()) {
1472 if (RD->isLambda()) {
1473 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1474 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1475 return true;
1476 }
1477
1478 if (FD->isAnonymousStructOrUnion()) {
1479 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1480 << DecompType << FD->getType()->isUnionType();
1481 S.Diag(FD->getLocation(), diag::note_declared_at);
1482 return true;
1483 }
1484
1485 // FIXME: Are there any other ways we could have an anonymous member?
1486 }
1487
1488 // We have a real field to bind.
1489 if (I >= Bindings.size())
1490 return DiagnoseBadNumberOfBindings();
1491 auto *B = Bindings[I++];
1492 SourceLocation Loc = B->getLocation();
1493
1494 // The field must be accessible in the context of the structured binding.
1495 // We already checked that the base class is accessible.
1496 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1497 // const_cast here.
1499 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1501 BasePair.getAccess(), FD->getAccess())));
1502
1503 // Initialize the binding to Src.FD.
1504 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1505 if (E.isInvalid())
1506 return true;
1507 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1508 VK_LValue, &BasePath);
1509 if (E.isInvalid())
1510 return true;
1511 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1512 CXXScopeSpec(), FD,
1513 DeclAccessPair::make(FD, FD->getAccess()),
1514 DeclarationNameInfo(FD->getDeclName(), Loc));
1515 if (E.isInvalid())
1516 return true;
1517
1518 // If the type of the member is T, the referenced type is cv T, where cv is
1519 // the cv-qualification of the decomposition expression.
1520 //
1521 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522 // 'const' to the type of the field.
1523 Qualifiers Q = DecompType.getQualifiers();
1524 if (FD->isMutable())
1525 Q.removeConst();
1526 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1527 }
1528
1529 if (I != Bindings.size())
1530 return DiagnoseBadNumberOfBindings();
1531
1532 return false;
1533}
1534
1536 QualType DecompType = DD->getType();
1537
1538 // If the type of the decomposition is dependent, then so is the type of
1539 // each binding.
1540 if (DecompType->isDependentType()) {
1541 for (auto *B : DD->bindings())
1542 B->setType(Context.DependentTy);
1543 return;
1544 }
1545
1546 DecompType = DecompType.getNonReferenceType();
1548
1549 // C++1z [dcl.decomp]/2:
1550 // If E is an array type [...]
1551 // As an extension, we also support decomposition of built-in complex and
1552 // vector types.
1553 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1554 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1555 DD->setInvalidDecl();
1556 return;
1557 }
1558 if (auto *VT = DecompType->getAs<VectorType>()) {
1559 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1560 DD->setInvalidDecl();
1561 return;
1562 }
1563 if (auto *CT = DecompType->getAs<ComplexType>()) {
1564 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1565 DD->setInvalidDecl();
1566 return;
1567 }
1568
1569 // C++1z [dcl.decomp]/3:
1570 // if the expression std::tuple_size<E>::value is a well-formed integral
1571 // constant expression, [...]
1572 llvm::APSInt TupleSize(32);
1573 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1574 case IsTupleLike::Error:
1575 DD->setInvalidDecl();
1576 return;
1577
1578 case IsTupleLike::TupleLike:
1579 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1580 DD->setInvalidDecl();
1581 return;
1582
1583 case IsTupleLike::NotTupleLike:
1584 break;
1585 }
1586
1587 // C++1z [dcl.dcl]/8:
1588 // [E shall be of array or non-union class type]
1589 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1590 if (!RD || RD->isUnion()) {
1591 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1592 << DD << !RD << DecompType;
1593 DD->setInvalidDecl();
1594 return;
1595 }
1596
1597 // C++1z [dcl.decomp]/4:
1598 // all of E's non-static data members shall be [...] direct members of
1599 // E or of the same unambiguous public base class of E, ...
1600 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1601 DD->setInvalidDecl();
1602}
1603
1604/// Merge the exception specifications of two variable declarations.
1605///
1606/// This is called when there's a redeclaration of a VarDecl. The function
1607/// checks if the redeclaration might have an exception specification and
1608/// validates compatibility and merges the specs if necessary.
1610 // Shortcut if exceptions are disabled.
1611 if (!getLangOpts().CXXExceptions)
1612 return;
1613
1614 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1615 "Should only be called if types are otherwise the same.");
1616
1617 QualType NewType = New->getType();
1618 QualType OldType = Old->getType();
1619
1620 // We're only interested in pointers and references to functions, as well
1621 // as pointers to member functions.
1622 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1623 NewType = R->getPointeeType();
1624 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1625 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1626 NewType = P->getPointeeType();
1627 OldType = OldType->castAs<PointerType>()->getPointeeType();
1628 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1629 NewType = M->getPointeeType();
1630 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1631 }
1632
1633 if (!NewType->isFunctionProtoType())
1634 return;
1635
1636 // There's lots of special cases for functions. For function pointers, system
1637 // libraries are hopefully not as broken so that we don't need these
1638 // workarounds.
1640 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1641 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1642 New->setInvalidDecl();
1643 }
1644}
1645
1646/// CheckCXXDefaultArguments - Verify that the default arguments for a
1647/// function declaration are well-formed according to C++
1648/// [dcl.fct.default].
1650 unsigned NumParams = FD->getNumParams();
1651 unsigned ParamIdx = 0;
1652
1653 // This checking doesn't make sense for explicit specializations; their
1654 // default arguments are determined by the declaration we're specializing,
1655 // not by FD.
1657 return;
1658 if (auto *FTD = FD->getDescribedFunctionTemplate())
1659 if (FTD->isMemberSpecialization())
1660 return;
1661
1662 // Find first parameter with a default argument
1663 for (; ParamIdx < NumParams; ++ParamIdx) {
1664 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1665 if (Param->hasDefaultArg())
1666 break;
1667 }
1668
1669 // C++20 [dcl.fct.default]p4:
1670 // In a given function declaration, each parameter subsequent to a parameter
1671 // with a default argument shall have a default argument supplied in this or
1672 // a previous declaration, unless the parameter was expanded from a
1673 // parameter pack, or shall be a function parameter pack.
1674 for (; ParamIdx < NumParams; ++ParamIdx) {
1675 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1676 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1679 if (Param->isInvalidDecl())
1680 /* We already complained about this parameter. */;
1681 else if (Param->getIdentifier())
1682 Diag(Param->getLocation(),
1683 diag::err_param_default_argument_missing_name)
1684 << Param->getIdentifier();
1685 else
1686 Diag(Param->getLocation(),
1687 diag::err_param_default_argument_missing);
1688 }
1689 }
1690}
1691
1692/// Check that the given type is a literal type. Issue a diagnostic if not,
1693/// if Kind is Diagnose.
1694/// \return \c true if a problem has been found (and optionally diagnosed).
1695template <typename... Ts>
1697 SourceLocation Loc, QualType T, unsigned DiagID,
1698 Ts &&...DiagArgs) {
1699 if (T->isDependentType())
1700 return false;
1701
1702 switch (Kind) {
1704 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1705 std::forward<Ts>(DiagArgs)...);
1706
1708 return !T->isLiteralType(SemaRef.Context);
1709 }
1710
1711 llvm_unreachable("unknown CheckConstexprKind");
1712}
1713
1714/// Determine whether a destructor cannot be constexpr due to
1716 const CXXDestructorDecl *DD,
1718 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1719 "this check is obsolete for C++23");
1720 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1721 const CXXRecordDecl *RD =
1722 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1723 if (!RD || RD->hasConstexprDestructor())
1724 return true;
1725
1727 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1728 << static_cast<int>(DD->getConstexprKind()) << !FD
1729 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1730 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1731 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1732 }
1733 return false;
1734 };
1735
1736 const CXXRecordDecl *RD = DD->getParent();
1737 for (const CXXBaseSpecifier &B : RD->bases())
1738 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1739 return false;
1740 for (const FieldDecl *FD : RD->fields())
1741 if (!Check(FD->getLocation(), FD->getType(), FD))
1742 return false;
1743 return true;
1744}
1745
1746/// Check whether a function's parameter types are all literal types. If so,
1747/// return true. If not, produce a suitable diagnostic and return false.
1749 const FunctionDecl *FD,
1751 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1752 "this check is obsolete for C++23");
1753 unsigned ArgIndex = 0;
1754 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1755 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1756 e = FT->param_type_end();
1757 i != e; ++i, ++ArgIndex) {
1758 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1759 assert(PD && "null in a parameter list");
1760 SourceLocation ParamLoc = PD->getLocation();
1761 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1762 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1763 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1764 FD->isConsteval()))
1765 return false;
1766 }
1767 return true;
1768}
1769
1770/// Check whether a function's return type is a literal type. If so, return
1771/// true. If not, produce a suitable diagnostic and return false.
1772static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1774 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1775 "this check is obsolete for C++23");
1776 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1777 diag::err_constexpr_non_literal_return,
1778 FD->isConsteval()))
1779 return false;
1780 return true;
1781}
1782
1783/// Get diagnostic %select index for tag kind for
1784/// record diagnostic message.
1785/// WARNING: Indexes apply to particular diagnostics only!
1786///
1787/// \returns diagnostic %select index.
1789 switch (Tag) {
1791 return 0;
1793 return 1;
1794 case TagTypeKind::Class:
1795 return 2;
1796 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1797 }
1798}
1799
1800static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1801 Stmt *Body,
1803
1804// Check whether a function declaration satisfies the requirements of a
1805// constexpr function definition or a constexpr constructor definition. If so,
1806// return true. If not, produce appropriate diagnostics (unless asked not to by
1807// Kind) and return false.
1808//
1809// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1811 CheckConstexprKind Kind) {
1812 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1813 if (MD && MD->isInstance()) {
1814 // C++11 [dcl.constexpr]p4:
1815 // The definition of a constexpr constructor shall satisfy the following
1816 // constraints:
1817 // - the class shall not have any virtual base classes;
1818 //
1819 // FIXME: This only applies to constructors and destructors, not arbitrary
1820 // member functions.
1821 const CXXRecordDecl *RD = MD->getParent();
1822 if (RD->getNumVBases()) {
1824 return false;
1825
1826 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1827 << isa<CXXConstructorDecl>(NewFD)
1829 for (const auto &I : RD->vbases())
1830 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1831 << I.getSourceRange();
1832 return false;
1833 }
1834 }
1835
1836 if (!isa<CXXConstructorDecl>(NewFD)) {
1837 // C++11 [dcl.constexpr]p3:
1838 // The definition of a constexpr function shall satisfy the following
1839 // constraints:
1840 // - it shall not be virtual; (removed in C++20)
1841 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1842 if (Method && Method->isVirtual()) {
1843 if (getLangOpts().CPlusPlus20) {
1844 if (Kind == CheckConstexprKind::Diagnose)
1845 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1846 } else {
1848 return false;
1849
1850 Method = Method->getCanonicalDecl();
1851 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1852
1853 // If it's not obvious why this function is virtual, find an overridden
1854 // function which uses the 'virtual' keyword.
1855 const CXXMethodDecl *WrittenVirtual = Method;
1856 while (!WrittenVirtual->isVirtualAsWritten())
1857 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1858 if (WrittenVirtual != Method)
1859 Diag(WrittenVirtual->getLocation(),
1860 diag::note_overridden_virtual_function);
1861 return false;
1862 }
1863 }
1864
1865 // - its return type shall be a literal type; (removed in C++23)
1866 if (!getLangOpts().CPlusPlus23 &&
1867 !CheckConstexprReturnType(*this, NewFD, Kind))
1868 return false;
1869 }
1870
1871 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1872 // A destructor can be constexpr only if the defaulted destructor could be;
1873 // we don't need to check the members and bases if we already know they all
1874 // have constexpr destructors. (removed in C++23)
1875 if (!getLangOpts().CPlusPlus23 &&
1876 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1878 return false;
1879 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1880 return false;
1881 }
1882 }
1883
1884 // - each of its parameter types shall be a literal type; (removed in C++23)
1885 if (!getLangOpts().CPlusPlus23 &&
1886 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1887 return false;
1888
1889 Stmt *Body = NewFD->getBody();
1890 assert(Body &&
1891 "CheckConstexprFunctionDefinition called on function with no body");
1892 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1893}
1894
1895/// Check the given declaration statement is legal within a constexpr function
1896/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1897///
1898/// \return true if the body is OK (maybe only as an extension), false if we
1899/// have diagnosed a problem.
1900static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1901 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1903 // C++11 [dcl.constexpr]p3 and p4:
1904 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1905 // contain only
1906 for (const auto *DclIt : DS->decls()) {
1907 switch (DclIt->getKind()) {
1908 case Decl::StaticAssert:
1909 case Decl::Using:
1910 case Decl::UsingShadow:
1911 case Decl::UsingDirective:
1912 case Decl::UnresolvedUsingTypename:
1913 case Decl::UnresolvedUsingValue:
1914 case Decl::UsingEnum:
1915 // - static_assert-declarations
1916 // - using-declarations,
1917 // - using-directives,
1918 // - using-enum-declaration
1919 continue;
1920
1921 case Decl::Typedef:
1922 case Decl::TypeAlias: {
1923 // - typedef declarations and alias-declarations that do not define
1924 // classes or enumerations,
1925 const auto *TN = cast<TypedefNameDecl>(DclIt);
1926 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1927 // Don't allow variably-modified types in constexpr functions.
1929 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1930 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1931 << TL.getSourceRange() << TL.getType()
1932 << isa<CXXConstructorDecl>(Dcl);
1933 }
1934 return false;
1935 }
1936 continue;
1937 }
1938
1939 case Decl::Enum:
1940 case Decl::CXXRecord:
1941 // C++1y allows types to be defined, not just declared.
1942 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1944 SemaRef.Diag(DS->getBeginLoc(),
1945 SemaRef.getLangOpts().CPlusPlus14
1946 ? diag::warn_cxx11_compat_constexpr_type_definition
1947 : diag::ext_constexpr_type_definition)
1948 << isa<CXXConstructorDecl>(Dcl);
1949 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1950 return false;
1951 }
1952 }
1953 continue;
1954
1955 case Decl::EnumConstant:
1956 case Decl::IndirectField:
1957 case Decl::ParmVar:
1958 // These can only appear with other declarations which are banned in
1959 // C++11 and permitted in C++1y, so ignore them.
1960 continue;
1961
1962 case Decl::Var:
1963 case Decl::Decomposition: {
1964 // C++1y [dcl.constexpr]p3 allows anything except:
1965 // a definition of a variable of non-literal type or of static or
1966 // thread storage duration or [before C++2a] for which no
1967 // initialization is performed.
1968 const auto *VD = cast<VarDecl>(DclIt);
1969 if (VD->isThisDeclarationADefinition()) {
1970 if (VD->isStaticLocal()) {
1972 SemaRef.Diag(VD->getLocation(),
1973 SemaRef.getLangOpts().CPlusPlus23
1974 ? diag::warn_cxx20_compat_constexpr_var
1975 : diag::ext_constexpr_static_var)
1976 << isa<CXXConstructorDecl>(Dcl)
1977 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1978 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1979 return false;
1980 }
1981 }
1982 if (SemaRef.LangOpts.CPlusPlus23) {
1983 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1984 diag::warn_cxx20_compat_constexpr_var,
1985 isa<CXXConstructorDecl>(Dcl),
1986 /*variable of non-literal type*/ 2);
1987 } else if (CheckLiteralType(
1988 SemaRef, Kind, VD->getLocation(), VD->getType(),
1989 diag::err_constexpr_local_var_non_literal_type,
1990 isa<CXXConstructorDecl>(Dcl))) {
1991 return false;
1992 }
1993 if (!VD->getType()->isDependentType() &&
1994 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1996 SemaRef.Diag(
1997 VD->getLocation(),
1998 SemaRef.getLangOpts().CPlusPlus20
1999 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2000 : diag::ext_constexpr_local_var_no_init)
2001 << isa<CXXConstructorDecl>(Dcl);
2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003 return false;
2004 }
2005 continue;
2006 }
2007 }
2009 SemaRef.Diag(VD->getLocation(),
2010 SemaRef.getLangOpts().CPlusPlus14
2011 ? diag::warn_cxx11_compat_constexpr_local_var
2012 : diag::ext_constexpr_local_var)
2013 << isa<CXXConstructorDecl>(Dcl);
2014 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2015 return false;
2016 }
2017 continue;
2018 }
2019
2020 case Decl::NamespaceAlias:
2021 case Decl::Function:
2022 // These are disallowed in C++11 and permitted in C++1y. Allow them
2023 // everywhere as an extension.
2024 if (!Cxx1yLoc.isValid())
2025 Cxx1yLoc = DS->getBeginLoc();
2026 continue;
2027
2028 default:
2030 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2031 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2032 }
2033 return false;
2034 }
2035 }
2036
2037 return true;
2038}
2039
2040/// Check that the given field is initialized within a constexpr constructor.
2041///
2042/// \param Dcl The constexpr constructor being checked.
2043/// \param Field The field being checked. This may be a member of an anonymous
2044/// struct or union nested within the class being checked.
2045/// \param Inits All declarations, including anonymous struct/union members and
2046/// indirect members, for which any initialization was provided.
2047/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2048/// multiple notes for different members to the same error.
2049/// \param Kind Whether we're diagnosing a constructor as written or determining
2050/// whether the formal requirements are satisfied.
2051/// \return \c false if we're checking for validity and the constructor does
2052/// not satisfy the requirements on a constexpr constructor.
2054 const FunctionDecl *Dcl,
2055 FieldDecl *Field,
2056 llvm::SmallSet<Decl*, 16> &Inits,
2057 bool &Diagnosed,
2059 // In C++20 onwards, there's nothing to check for validity.
2061 SemaRef.getLangOpts().CPlusPlus20)
2062 return true;
2063
2064 if (Field->isInvalidDecl())
2065 return true;
2066
2067 if (Field->isUnnamedBitfield())
2068 return true;
2069
2070 // Anonymous unions with no variant members and empty anonymous structs do not
2071 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2072 // indirect fields don't need initializing.
2073 if (Field->isAnonymousStructOrUnion() &&
2074 (Field->getType()->isUnionType()
2075 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2076 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2077 return true;
2078
2079 if (!Inits.count(Field)) {
2081 if (!Diagnosed) {
2082 SemaRef.Diag(Dcl->getLocation(),
2083 SemaRef.getLangOpts().CPlusPlus20
2084 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2085 : diag::ext_constexpr_ctor_missing_init);
2086 Diagnosed = true;
2087 }
2088 SemaRef.Diag(Field->getLocation(),
2089 diag::note_constexpr_ctor_missing_init);
2090 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2091 return false;
2092 }
2093 } else if (Field->isAnonymousStructOrUnion()) {
2094 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2095 for (auto *I : RD->fields())
2096 // If an anonymous union contains an anonymous struct of which any member
2097 // is initialized, all members must be initialized.
2098 if (!RD->isUnion() || Inits.count(I))
2099 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2100 Kind))
2101 return false;
2102 }
2103 return true;
2104}
2105
2106/// Check the provided statement is allowed in a constexpr function
2107/// definition.
2108static bool
2111 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2112 SourceLocation &Cxx2bLoc,
2114 // - its function-body shall be [...] a compound-statement that contains only
2115 switch (S->getStmtClass()) {
2116 case Stmt::NullStmtClass:
2117 // - null statements,
2118 return true;
2119
2120 case Stmt::DeclStmtClass:
2121 // - static_assert-declarations
2122 // - using-declarations,
2123 // - using-directives,
2124 // - typedef declarations and alias-declarations that do not define
2125 // classes or enumerations,
2126 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2127 return false;
2128 return true;
2129
2130 case Stmt::ReturnStmtClass:
2131 // - and exactly one return statement;
2132 if (isa<CXXConstructorDecl>(Dcl)) {
2133 // C++1y allows return statements in constexpr constructors.
2134 if (!Cxx1yLoc.isValid())
2135 Cxx1yLoc = S->getBeginLoc();
2136 return true;
2137 }
2138
2139 ReturnStmts.push_back(S->getBeginLoc());
2140 return true;
2141
2142 case Stmt::AttributedStmtClass:
2143 // Attributes on a statement don't affect its formal kind and hence don't
2144 // affect its validity in a constexpr function.
2146 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2147 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2148
2149 case Stmt::CompoundStmtClass: {
2150 // C++1y allows compound-statements.
2151 if (!Cxx1yLoc.isValid())
2152 Cxx1yLoc = S->getBeginLoc();
2153
2154 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2155 for (auto *BodyIt : CompStmt->body()) {
2156 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2157 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158 return false;
2159 }
2160 return true;
2161 }
2162
2163 case Stmt::IfStmtClass: {
2164 // C++1y allows if-statements.
2165 if (!Cxx1yLoc.isValid())
2166 Cxx1yLoc = S->getBeginLoc();
2167
2168 IfStmt *If = cast<IfStmt>(S);
2169 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2170 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2171 return false;
2172 if (If->getElse() &&
2173 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2174 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2175 return false;
2176 return true;
2177 }
2178
2179 case Stmt::WhileStmtClass:
2180 case Stmt::DoStmtClass:
2181 case Stmt::ForStmtClass:
2182 case Stmt::CXXForRangeStmtClass:
2183 case Stmt::ContinueStmtClass:
2184 // C++1y allows all of these. We don't allow them as extensions in C++11,
2185 // because they don't make sense without variable mutation.
2186 if (!SemaRef.getLangOpts().CPlusPlus14)
2187 break;
2188 if (!Cxx1yLoc.isValid())
2189 Cxx1yLoc = S->getBeginLoc();
2190 for (Stmt *SubStmt : S->children()) {
2191 if (SubStmt &&
2192 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2193 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2194 return false;
2195 }
2196 return true;
2197
2198 case Stmt::SwitchStmtClass:
2199 case Stmt::CaseStmtClass:
2200 case Stmt::DefaultStmtClass:
2201 case Stmt::BreakStmtClass:
2202 // C++1y allows switch-statements, and since they don't need variable
2203 // mutation, we can reasonably allow them in C++11 as an extension.
2204 if (!Cxx1yLoc.isValid())
2205 Cxx1yLoc = S->getBeginLoc();
2206 for (Stmt *SubStmt : S->children()) {
2207 if (SubStmt &&
2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2209 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2210 return false;
2211 }
2212 return true;
2213
2214 case Stmt::LabelStmtClass:
2215 case Stmt::GotoStmtClass:
2216 if (Cxx2bLoc.isInvalid())
2217 Cxx2bLoc = S->getBeginLoc();
2218 for (Stmt *SubStmt : S->children()) {
2219 if (SubStmt &&
2220 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2221 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222 return false;
2223 }
2224 return true;
2225
2226 case Stmt::GCCAsmStmtClass:
2227 case Stmt::MSAsmStmtClass:
2228 // C++2a allows inline assembly statements.
2229 case Stmt::CXXTryStmtClass:
2230 if (Cxx2aLoc.isInvalid())
2231 Cxx2aLoc = S->getBeginLoc();
2232 for (Stmt *SubStmt : S->children()) {
2233 if (SubStmt &&
2234 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2235 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2236 return false;
2237 }
2238 return true;
2239
2240 case Stmt::CXXCatchStmtClass:
2241 // Do not bother checking the language mode (already covered by the
2242 // try block check).
2244 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2245 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2246 return false;
2247 return true;
2248
2249 default:
2250 if (!isa<Expr>(S))
2251 break;
2252
2253 // C++1y allows expression-statements.
2254 if (!Cxx1yLoc.isValid())
2255 Cxx1yLoc = S->getBeginLoc();
2256 return true;
2257 }
2258
2260 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2261 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2262 }
2263 return false;
2264}
2265
2266/// Check the body for the given constexpr function declaration only contains
2267/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2268///
2269/// \return true if the body is OK, false if we have found or diagnosed a
2270/// problem.
2271static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2272 Stmt *Body,
2275
2276 if (isa<CXXTryStmt>(Body)) {
2277 // C++11 [dcl.constexpr]p3:
2278 // The definition of a constexpr function shall satisfy the following
2279 // constraints: [...]
2280 // - its function-body shall be = delete, = default, or a
2281 // compound-statement
2282 //
2283 // C++11 [dcl.constexpr]p4:
2284 // In the definition of a constexpr constructor, [...]
2285 // - its function-body shall not be a function-try-block;
2286 //
2287 // This restriction is lifted in C++2a, as long as inner statements also
2288 // apply the general constexpr rules.
2289 switch (Kind) {
2291 if (!SemaRef.getLangOpts().CPlusPlus20)
2292 return false;
2293 break;
2294
2296 SemaRef.Diag(Body->getBeginLoc(),
2297 !SemaRef.getLangOpts().CPlusPlus20
2298 ? diag::ext_constexpr_function_try_block_cxx20
2299 : diag::warn_cxx17_compat_constexpr_function_try_block)
2300 << isa<CXXConstructorDecl>(Dcl);
2301 break;
2302 }
2303 }
2304
2305 // - its function-body shall be [...] a compound-statement that contains only
2306 // [... list of cases ...]
2307 //
2308 // Note that walking the children here is enough to properly check for
2309 // CompoundStmt and CXXTryStmt body.
2310 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2311 for (Stmt *SubStmt : Body->children()) {
2312 if (SubStmt &&
2313 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2314 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2315 return false;
2316 }
2317
2319 // If this is only valid as an extension, report that we don't satisfy the
2320 // constraints of the current language.
2321 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2322 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2323 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2324 return false;
2325 } else if (Cxx2bLoc.isValid()) {
2326 SemaRef.Diag(Cxx2bLoc,
2327 SemaRef.getLangOpts().CPlusPlus23
2328 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2329 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2330 << isa<CXXConstructorDecl>(Dcl);
2331 } else if (Cxx2aLoc.isValid()) {
2332 SemaRef.Diag(Cxx2aLoc,
2333 SemaRef.getLangOpts().CPlusPlus20
2334 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2335 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2336 << isa<CXXConstructorDecl>(Dcl);
2337 } else if (Cxx1yLoc.isValid()) {
2338 SemaRef.Diag(Cxx1yLoc,
2339 SemaRef.getLangOpts().CPlusPlus14
2340 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2341 : diag::ext_constexpr_body_invalid_stmt)
2342 << isa<CXXConstructorDecl>(Dcl);
2343 }
2344
2345 if (const CXXConstructorDecl *Constructor
2346 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2347 const CXXRecordDecl *RD = Constructor->getParent();
2348 // DR1359:
2349 // - every non-variant non-static data member and base class sub-object
2350 // shall be initialized;
2351 // DR1460:
2352 // - if the class is a union having variant members, exactly one of them
2353 // shall be initialized;
2354 if (RD->isUnion()) {
2355 if (Constructor->getNumCtorInitializers() == 0 &&
2356 RD->hasVariantMembers()) {
2358 SemaRef.Diag(
2359 Dcl->getLocation(),
2360 SemaRef.getLangOpts().CPlusPlus20
2361 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2362 : diag::ext_constexpr_union_ctor_no_init);
2363 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2364 return false;
2365 }
2366 }
2367 } else if (!Constructor->isDependentContext() &&
2368 !Constructor->isDelegatingConstructor()) {
2369 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2370
2371 // Skip detailed checking if we have enough initializers, and we would
2372 // allow at most one initializer per member.
2373 bool AnyAnonStructUnionMembers = false;
2374 unsigned Fields = 0;
2376 E = RD->field_end(); I != E; ++I, ++Fields) {
2377 if (I->isAnonymousStructOrUnion()) {
2378 AnyAnonStructUnionMembers = true;
2379 break;
2380 }
2381 }
2382 // DR1460:
2383 // - if the class is a union-like class, but is not a union, for each of
2384 // its anonymous union members having variant members, exactly one of
2385 // them shall be initialized;
2386 if (AnyAnonStructUnionMembers ||
2387 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2388 // Check initialization of non-static data members. Base classes are
2389 // always initialized so do not need to be checked. Dependent bases
2390 // might not have initializers in the member initializer list.
2391 llvm::SmallSet<Decl*, 16> Inits;
2392 for (const auto *I: Constructor->inits()) {
2393 if (FieldDecl *FD = I->getMember())
2394 Inits.insert(FD);
2395 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2396 Inits.insert(ID->chain_begin(), ID->chain_end());
2397 }
2398
2399 bool Diagnosed = false;
2400 for (auto *I : RD->fields())
2401 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2402 Kind))
2403 return false;
2404 }
2405 }
2406 } else {
2407 if (ReturnStmts.empty()) {
2408 // C++1y doesn't require constexpr functions to contain a 'return'
2409 // statement. We still do, unless the return type might be void, because
2410 // otherwise if there's no return statement, the function cannot
2411 // be used in a core constant expression.
2412 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2413 (Dcl->getReturnType()->isVoidType() ||
2414 Dcl->getReturnType()->isDependentType());
2415 switch (Kind) {
2417 SemaRef.Diag(Dcl->getLocation(),
2418 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2419 : diag::err_constexpr_body_no_return)
2420 << Dcl->isConsteval();
2421 if (!OK)
2422 return false;
2423 break;
2424
2426 // The formal requirements don't include this rule in C++14, even
2427 // though the "must be able to produce a constant expression" rules
2428 // still imply it in some cases.
2429 if (!SemaRef.getLangOpts().CPlusPlus14)
2430 return false;
2431 break;
2432 }
2433 } else if (ReturnStmts.size() > 1) {
2434 switch (Kind) {
2436 SemaRef.Diag(
2437 ReturnStmts.back(),
2438 SemaRef.getLangOpts().CPlusPlus14
2439 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2440 : diag::ext_constexpr_body_multiple_return);
2441 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2442 SemaRef.Diag(ReturnStmts[I],
2443 diag::note_constexpr_body_previous_return);
2444 break;
2445
2447 if (!SemaRef.getLangOpts().CPlusPlus14)
2448 return false;
2449 break;
2450 }
2451 }
2452 }
2453
2454 // C++11 [dcl.constexpr]p5:
2455 // if no function argument values exist such that the function invocation
2456 // substitution would produce a constant expression, the program is
2457 // ill-formed; no diagnostic required.
2458 // C++11 [dcl.constexpr]p3:
2459 // - every constructor call and implicit conversion used in initializing the
2460 // return value shall be one of those allowed in a constant expression.
2461 // C++11 [dcl.constexpr]p4:
2462 // - every constructor involved in initializing non-static data members and
2463 // base class sub-objects shall be a constexpr constructor.
2464 //
2465 // Note that this rule is distinct from the "requirements for a constexpr
2466 // function", so is not checked in CheckValid mode.
2470 !SemaRef.getLangOpts().CPlusPlus23) {
2471 SemaRef.Diag(Dcl->getLocation(),
2472 diag::ext_constexpr_function_never_constant_expr)
2473 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2474 << Dcl->getNameInfo().getSourceRange();
2475 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2476 SemaRef.Diag(Diags[I].first, Diags[I].second);
2477 // Don't return false here: we allow this for compatibility in
2478 // system headers.
2479 }
2480
2481 return true;
2482}
2483
2485 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2487 return true;
2491 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2492 if (it != UndefinedButUsed.end()) {
2493 Diag(it->second, diag::err_immediate_function_used_before_definition)
2494 << it->first;
2495 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2496 if (FD->isImmediateFunction() && !FD->isConsteval())
2498 return false;
2499 }
2500 }
2501 return true;
2502}
2503
2505 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2506 "expected an immediate function");
2507 assert(FD->hasBody() && "expected the function to have a body");
2508 struct ImmediateEscalatingExpressionsVisitor
2509 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2510
2512 Sema &SemaRef;
2513
2514 const FunctionDecl *ImmediateFn;
2515 bool ImmediateFnIsConstructor;
2516 CXXConstructorDecl *CurrentConstructor = nullptr;
2517 CXXCtorInitializer *CurrentInit = nullptr;
2518
2519 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2520 : SemaRef(SemaRef), ImmediateFn(FD),
2521 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2522
2523 bool shouldVisitImplicitCode() const { return true; }
2524 bool shouldVisitLambdaBody() const { return false; }
2525
2526 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2527 SourceLocation Loc = E->getBeginLoc();
2528 SourceRange Range = E->getSourceRange();
2529 if (CurrentConstructor && CurrentInit) {
2530 Loc = CurrentConstructor->getLocation();
2531 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2532 : SourceRange();
2533 }
2534
2535 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2536
2537 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2538 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2539 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2540 << (InitializedField != nullptr)
2541 << (CurrentInit && !CurrentInit->isWritten())
2542 << InitializedField << Range;
2543 }
2544 bool TraverseCallExpr(CallExpr *E) {
2545 if (const auto *DR =
2546 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2547 DR && DR->isImmediateEscalating()) {
2548 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2549 return false;
2550 }
2551
2552 for (Expr *A : E->arguments())
2553 if (!getDerived().TraverseStmt(A))
2554 return false;
2555
2556 return true;
2557 }
2558
2559 bool VisitDeclRefExpr(DeclRefExpr *E) {
2560 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2561 ReferencedFn && E->isImmediateEscalating()) {
2562 Diag(E, ReferencedFn, /*IsCall=*/false);
2563 return false;
2564 }
2565
2566 return true;
2567 }
2568
2569 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2571 if (E->isImmediateEscalating()) {
2572 Diag(E, D, /*IsCall=*/true);
2573 return false;
2574 }
2575 return true;
2576 }
2577
2578 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2579 llvm::SaveAndRestore RAII(CurrentInit, Init);
2580 return Base::TraverseConstructorInitializer(Init);
2581 }
2582
2583 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2584 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2585 return Base::TraverseCXXConstructorDecl(Ctr);
2586 }
2587
2588 bool TraverseType(QualType T) { return true; }
2589 bool VisitBlockExpr(BlockExpr *T) { return true; }
2590
2591 } Visitor(*this, FD);
2592 Visitor.TraverseDecl(FD);
2593}
2594
2595/// Get the class that is directly named by the current context. This is the
2596/// class for which an unqualified-id in this scope could name a constructor
2597/// or destructor.
2598///
2599/// If the scope specifier denotes a class, this will be that class.
2600/// If the scope specifier is empty, this will be the class whose
2601/// member-specification we are currently within. Otherwise, there
2602/// is no such class.
2604 assert(getLangOpts().CPlusPlus && "No class names in C!");
2605
2606 if (SS && SS->isInvalid())
2607 return nullptr;
2608
2609 if (SS && SS->isNotEmpty()) {
2610 DeclContext *DC = computeDeclContext(*SS, true);
2611 return dyn_cast_or_null<CXXRecordDecl>(DC);
2612 }
2613
2614 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2615}
2616
2617/// isCurrentClassName - Determine whether the identifier II is the
2618/// name of the class type currently being defined. In the case of
2619/// nested classes, this will only return true if II is the name of
2620/// the innermost class.
2622 const CXXScopeSpec *SS) {
2623 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2624 return CurDecl && &II == CurDecl->getIdentifier();
2625}
2626
2627/// Determine whether the identifier II is a typo for the name of
2628/// the class type currently being defined. If so, update it to the identifier
2629/// that should have been used.
2631 assert(getLangOpts().CPlusPlus && "No class names in C!");
2632
2633 if (!getLangOpts().SpellChecking)
2634 return false;
2635
2636 CXXRecordDecl *CurDecl;
2637 if (SS && SS->isSet() && !SS->isInvalid()) {
2638 DeclContext *DC = computeDeclContext(*SS, true);
2639 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2640 } else
2641 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2642
2643 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2644 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2645 < II->getLength()) {
2646 II = CurDecl->getIdentifier();
2647 return true;
2648 }
2649
2650 return false;
2651}
2652
2653/// Determine whether the given class is a base class of the given
2654/// class, including looking at dependent bases.
2656 const CXXRecordDecl *Current) {
2658
2659 Class = Class->getCanonicalDecl();
2660 while (true) {
2661 for (const auto &I : Current->bases()) {
2662 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2663 if (!Base)
2664 continue;
2665
2666 Base = Base->getDefinition();
2667 if (!Base)
2668 continue;
2669
2670 if (Base->getCanonicalDecl() == Class)
2671 return true;
2672
2673 Queue.push_back(Base);
2674 }
2675
2676 if (Queue.empty())
2677 return false;
2678
2679 Current = Queue.pop_back_val();
2680 }
2681
2682 return false;
2683}
2684
2685/// Check the validity of a C++ base class specifier.
2686///
2687/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2688/// and returns NULL otherwise.
2691 SourceRange SpecifierRange,
2692 bool Virtual, AccessSpecifier Access,
2693 TypeSourceInfo *TInfo,
2694 SourceLocation EllipsisLoc) {
2695 // In HLSL, unspecified class access is public rather than private.
2696 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2697 Access == AS_none)
2698 Access = AS_public;
2699
2700 QualType BaseType = TInfo->getType();
2701 if (BaseType->containsErrors()) {
2702 // Already emitted a diagnostic when parsing the error type.
2703 return nullptr;
2704 }
2705 // C++ [class.union]p1:
2706 // A union shall not have base classes.
2707 if (Class->isUnion()) {
2708 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2709 << SpecifierRange;
2710 return nullptr;
2711 }
2712
2713 if (EllipsisLoc.isValid() &&
2715 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2716 << TInfo->getTypeLoc().getSourceRange();
2717 EllipsisLoc = SourceLocation();
2718 }
2719
2720 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2721
2722 if (BaseType->isDependentType()) {
2723 // Make sure that we don't have circular inheritance among our dependent
2724 // bases. For non-dependent bases, the check for completeness below handles
2725 // this.
2726 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2727 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2728 ((BaseDecl = BaseDecl->getDefinition()) &&
2729 findCircularInheritance(Class, BaseDecl))) {
2730 Diag(BaseLoc, diag::err_circular_inheritance)
2731 << BaseType << Context.getTypeDeclType(Class);
2732
2733 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2734 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2735 << BaseType;
2736
2737 return nullptr;
2738 }
2739 }
2740
2741 // Make sure that we don't make an ill-formed AST where the type of the
2742 // Class is non-dependent and its attached base class specifier is an
2743 // dependent type, which violates invariants in many clang code paths (e.g.
2744 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2745 // explicitly mark the Class decl invalid. The diagnostic was already
2746 // emitted.
2747 if (!Class->getTypeForDecl()->isDependentType())
2748 Class->setInvalidDecl();
2749 return new (Context) CXXBaseSpecifier(
2750 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2751 Access, TInfo, EllipsisLoc);
2752 }
2753
2754 // Base specifiers must be record types.
2755 if (!BaseType->isRecordType()) {
2756 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2757 return nullptr;
2758 }
2759
2760 // C++ [class.union]p1:
2761 // A union shall not be used as a base class.
2762 if (BaseType->isUnionType()) {
2763 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2764 return nullptr;
2765 }
2766
2767 // For the MS ABI, propagate DLL attributes to base class templates.
2769 Context.getTargetInfo().getTriple().isPS()) {
2770 if (Attr *ClassAttr = getDLLAttr(Class)) {
2771 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2772 BaseType->getAsCXXRecordDecl())) {
2773 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2774 BaseLoc);
2775 }
2776 }
2777 }
2778
2779 // C++ [class.derived]p2:
2780 // The class-name in a base-specifier shall not be an incompletely
2781 // defined class.
2782 if (RequireCompleteType(BaseLoc, BaseType,
2783 diag::err_incomplete_base_class, SpecifierRange)) {
2784 Class->setInvalidDecl();
2785 return nullptr;
2786 }
2787
2788 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2789 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2790 assert(BaseDecl && "Record type has no declaration");
2791 BaseDecl = BaseDecl->getDefinition();
2792 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2793 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2794 assert(CXXBaseDecl && "Base type is not a C++ type");
2795
2796 // Microsoft docs say:
2797 // "If a base-class has a code_seg attribute, derived classes must have the
2798 // same attribute."
2799 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2800 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2801 if ((DerivedCSA || BaseCSA) &&
2802 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2804 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2805 << CXXBaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as a
2810 // 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 (CXXBaseDecl->hasFlexibleArrayMember()) {
2816 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2817 << CXXBaseDecl->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 = CXXBaseDecl->getAttr<FinalAttr>()) {
2825 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2826 << CXXBaseDecl->getDeclName()
2827 << FA->isSpelledAsSealed();
2828 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2829 << CXXBaseDecl->getDeclName() << FA->getRange();
2830 return nullptr;
2831 }
2832
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835
2836 // Create the base specifier.
2837 return new (Context) CXXBaseSpecifier(
2838 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2839 Access, TInfo, EllipsisLoc);
2840}
2841
2842/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2843/// one entry in the base class list of a class specifier, for
2844/// example:
2845/// class foo : public bar, virtual private baz {
2846/// 'public bar' and 'virtual private baz' are each base-specifiers.
2848 const ParsedAttributesView &Attributes,
2849 bool Virtual, AccessSpecifier Access,
2850 ParsedType basetype, SourceLocation BaseLoc,
2851 SourceLocation EllipsisLoc) {
2852 if (!classdecl)
2853 return true;
2854
2855 AdjustDeclIfTemplate(classdecl);
2856 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2857 if (!Class)
2858 return true;
2859
2860 // We haven't yet attached the base specifiers.
2861 Class->setIsParsingBaseSpecifiers();
2862
2863 // We do not support any C++11 attributes on base-specifiers yet.
2864 // Diagnose any attributes we see.
2865 for (const ParsedAttr &AL : Attributes) {
2866 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2867 continue;
2868 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2869 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2870 << AL << AL.getRange();
2871 else
2872 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2873 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2874 }
2875
2876 TypeSourceInfo *TInfo = nullptr;
2877 GetTypeFromParser(basetype, &TInfo);
2878
2879 if (EllipsisLoc.isInvalid() &&
2880 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2882 return true;
2883
2884 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2885 Virtual, Access, TInfo,
2886 EllipsisLoc))
2887 return BaseSpec;
2888 else
2889 Class->setInvalidDecl();
2890
2891 return true;
2892}
2893
2894/// Use small set to collect indirect bases. As this is only used
2895/// locally, there's no need to abstract the small size parameter.
2897
2898/// Recursively add the bases of Type. Don't add Type itself.
2899static void
2901 const QualType &Type)
2902{
2903 // Even though the incoming type is a base, it might not be
2904 // a class -- it could be a template parm, for instance.
2905 if (auto Rec = Type->getAs<RecordType>()) {
2906 auto Decl = Rec->getAsCXXRecordDecl();
2907
2908 // Iterate over its bases.
2909 for (const auto &BaseSpec : Decl->bases()) {
2910 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2912 if (Set.insert(Base).second)
2913 // If we've not already seen it, recurse.
2915 }
2916 }
2917}
2918
2919/// Performs the actual work of attaching the given base class
2920/// specifiers to a C++ class.
2923 if (Bases.empty())
2924 return false;
2925
2926 // Used to keep track of which base types we have already seen, so
2927 // that we can properly diagnose redundant direct base types. Note
2928 // that the key is always the unqualified canonical type of the base
2929 // class.
2930 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2931
2932 // Used to track indirect bases so we can see if a direct base is
2933 // ambiguous.
2934 IndirectBaseSet IndirectBaseTypes;
2935
2936 // Copy non-redundant base specifiers into permanent storage.
2937 unsigned NumGoodBases = 0;
2938 bool Invalid = false;
2939 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2940 QualType NewBaseType
2941 = Context.getCanonicalType(Bases[idx]->getType());
2942 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2943
2944 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2945 if (KnownBase) {
2946 // C++ [class.mi]p3:
2947 // A class shall not be specified as a direct base class of a
2948 // derived class more than once.
2949 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2950 << KnownBase->getType() << Bases[idx]->getSourceRange();
2951
2952 // Delete the duplicate base class specifier; we're going to
2953 // overwrite its pointer later.
2954 Context.Deallocate(Bases[idx]);
2955
2956 Invalid = true;
2957 } else {
2958 // Okay, add this new base class.
2959 KnownBase = Bases[idx];
2960 Bases[NumGoodBases++] = Bases[idx];
2961
2962 if (NewBaseType->isDependentType())
2963 continue;
2964 // Note this base's direct & indirect bases, if there could be ambiguity.
2965 if (Bases.size() > 1)
2966 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2967
2968 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2970 if (Class->isInterface() &&
2971 (!RD->isInterfaceLike() ||
2972 KnownBase->getAccessSpecifier() != AS_public)) {
2973 // The Microsoft extension __interface does not permit bases that
2974 // are not themselves public interfaces.
2975 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2976 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2977 << RD->getSourceRange();
2978 Invalid = true;
2979 }
2980 if (RD->hasAttr<WeakAttr>())
2981 Class->addAttr(WeakAttr::CreateImplicit(Context));
2982 }
2983 }
2984 }
2985
2986 // Attach the remaining base class specifiers to the derived class.
2987 Class->setBases(Bases.data(), NumGoodBases);
2988
2989 // Check that the only base classes that are duplicate are virtual.
2990 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2991 // Check whether this direct base is inaccessible due to ambiguity.
2992 QualType BaseType = Bases[idx]->getType();
2993
2994 // Skip all dependent types in templates being used as base specifiers.
2995 // Checks below assume that the base specifier is a CXXRecord.
2996 if (BaseType->isDependentType())
2997 continue;
2998
2999 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3001
3002 if (IndirectBaseTypes.count(CanonicalBase)) {
3003 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3004 /*DetectVirtual=*/true);
3005 bool found
3006 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3007 assert(found);
3008 (void)found;
3009
3010 if (Paths.isAmbiguous(CanonicalBase))
3011 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3012 << BaseType << getAmbiguousPathsDisplayString(Paths)
3013 << Bases[idx]->getSourceRange();
3014 else
3015 assert(Bases[idx]->isVirtual());
3016 }
3017
3018 // Delete the base class specifier, since its data has been copied
3019 // into the CXXRecordDecl.
3020 Context.Deallocate(Bases[idx]);
3021 }
3022
3023 return Invalid;
3024}
3025
3026/// ActOnBaseSpecifiers - Attach the given base specifiers to the
3027/// class, after checking whether there are any duplicate base
3028/// classes.
3031 if (!ClassDecl || Bases.empty())
3032 return;
3033
3034 AdjustDeclIfTemplate(ClassDecl);
3035 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3036}
3037
3038/// Determine whether the type \p Derived is a C++ class that is
3039/// derived from the type \p Base.
3041 if (!getLangOpts().CPlusPlus)
3042 return false;
3043
3044 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3045 if (!DerivedRD)
3046 return false;
3047
3048 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3049 if (!BaseRD)
3050 return false;
3051
3052 // If either the base or the derived type is invalid, don't try to
3053 // check whether one is derived from the other.
3054 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3055 return false;
3056
3057 // FIXME: In a modules build, do we need the entire path to be visible for us
3058 // to be able to use the inheritance relationship?
3059 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3060 return false;
3061
3062 return DerivedRD->isDerivedFrom(BaseRD);
3063}
3064
3065/// Determine whether the type \p Derived is a C++ class that is
3066/// derived from the type \p Base.
3068 CXXBasePaths &Paths) {
3069 if (!getLangOpts().CPlusPlus)
3070 return false;
3071
3072 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3073 if (!DerivedRD)
3074 return false;
3075
3076 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3077 if (!BaseRD)
3078 return false;
3079
3080 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3081 return false;
3082
3083 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3084}
3085
3086static void BuildBasePathArray(const CXXBasePath &Path,
3087 CXXCastPath &BasePathArray) {
3088 // We first go backward and check if we have a virtual base.
3089 // FIXME: It would be better if CXXBasePath had the base specifier for
3090 // the nearest virtual base.
3091 unsigned Start = 0;
3092 for (unsigned I = Path.size(); I != 0; --I) {
3093 if (Path[I - 1].Base->isVirtual()) {
3094 Start = I - 1;
3095 break;
3096 }
3097 }
3098
3099 // Now add all bases.
3100 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3101 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3102}
3103
3104
3106 CXXCastPath &BasePathArray) {
3107 assert(BasePathArray.empty() && "Base path array must be empty!");
3108 assert(Paths.isRecordingPaths() && "Must record paths!");
3109 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3110}
3111/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3112/// conversion (where Derived and Base are class types) is
3113/// well-formed, meaning that the conversion is unambiguous (and
3114/// that all of the base classes are accessible). Returns true
3115/// and emits a diagnostic if the code is ill-formed, returns false
3116/// otherwise. Loc is the location where this routine should point to
3117/// if there is an error, and Range is the source range to highlight
3118/// if there is an error.
3119///
3120/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3121/// diagnostic for the respective type of error will be suppressed, but the
3122/// check for ill-formed code will still be performed.
3123bool
3125 unsigned InaccessibleBaseID,
3126 unsigned AmbiguousBaseConvID,
3127 SourceLocation Loc, SourceRange Range,
3128 DeclarationName Name,
3129 CXXCastPath *BasePath,
3130 bool IgnoreAccess) {
3131 // First, determine whether the path from Derived to Base is
3132 // ambiguous. This is slightly more expensive than checking whether
3133 // the Derived to Base conversion exists, because here we need to
3134 // explore multiple paths to determine if there is an ambiguity.
3135 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3136 /*DetectVirtual=*/false);
3137 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3138 if (!DerivationOkay)
3139 return true;
3140
3141 const CXXBasePath *Path = nullptr;
3142 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3143 Path = &Paths.front();
3144
3145 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3146 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3147 // user to access such bases.
3148 if (!Path && getLangOpts().MSVCCompat) {
3149 for (const CXXBasePath &PossiblePath : Paths) {
3150 if (PossiblePath.size() == 1) {
3151 Path = &PossiblePath;
3152 if (AmbiguousBaseConvID)
3153 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3154 << Base << Derived << Range;
3155 break;
3156 }
3157 }
3158 }
3159
3160 if (Path) {
3161 if (!IgnoreAccess) {
3162 // Check that the base class can be accessed.
3163 switch (
3164 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3165 case AR_inaccessible:
3166 return true;
3167 case AR_accessible:
3168 case AR_dependent:
3169 case AR_delayed:
3170 break;
3171 }
3172 }
3173
3174 // Build a base path if necessary.
3175 if (BasePath)
3176 ::BuildBasePathArray(*Path, *BasePath);
3177 return false;
3178 }
3179
3180 if (AmbiguousBaseConvID) {
3181 // We know that the derived-to-base conversion is ambiguous, and
3182 // we're going to produce a diagnostic. Perform the derived-to-base
3183 // search just one more time to compute all of the possible paths so
3184 // that we can print them out. This is more expensive than any of
3185 // the previous derived-to-base checks we've done, but at this point
3186 // performance isn't as much of an issue.
3187 Paths.clear();
3188 Paths.setRecordingPaths(true);
3189 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3190 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3191 (void)StillOkay;
3192
3193 // Build up a textual representation of the ambiguous paths, e.g.,
3194 // D -> B -> A, that will be used to illustrate the ambiguous
3195 // conversions in the diagnostic. We only print one of the paths
3196 // to each base class subobject.
3197 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3198
3199 Diag(Loc, AmbiguousBaseConvID)
3200 << Derived << Base << PathDisplayStr << Range << Name;
3201 }
3202 return true;
3203}
3204
3205bool
3207 SourceLocation Loc, SourceRange Range,
3208 CXXCastPath *BasePath,
3209 bool IgnoreAccess) {
3211 Derived, Base, diag::err_upcast_to_inaccessible_base,
3212 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3213 BasePath, IgnoreAccess);
3214}
3215
3216
3217/// Builds a string representing ambiguous paths from a
3218/// specific derived class to different subobjects of the same base
3219/// class.
3220///
3221/// This function builds a string that can be used in error messages
3222/// to show the different paths that one can take through the
3223/// inheritance hierarchy to go from the derived class to different
3224/// subobjects of a base class. The result looks something like this:
3225/// @code
3226/// struct D -> struct B -> struct A
3227/// struct D -> struct C -> struct A
3228/// @endcode
3230 std::string PathDisplayStr;
3231 std::set<unsigned> DisplayedPaths;
3232 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3233 Path != Paths.end(); ++Path) {
3234 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3235 // We haven't displayed a path to this particular base
3236 // class subobject yet.
3237 PathDisplayStr += "\n ";
3238 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3239 for (CXXBasePath::const_iterator Element = Path->begin();
3240 Element != Path->end(); ++Element)
3241 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3242 }
3243 }
3244
3245 return PathDisplayStr;
3246}
3247
3248//===----------------------------------------------------------------------===//
3249// C++ class member Handling
3250//===----------------------------------------------------------------------===//
3251
3252/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3254 SourceLocation ColonLoc,
3255 const ParsedAttributesView &Attrs) {
3256 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3258 ASLoc, ColonLoc);
3259 CurContext->addHiddenDecl(ASDecl);
3260 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3261}
3262
3263/// CheckOverrideControl - Check C++11 override control semantics.
3265 if (D->isInvalidDecl())
3266 return;
3267
3268 // We only care about "override" and "final" declarations.
3269 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3270 return;
3271
3272 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3273
3274 // We can't check dependent instance methods.
3275 if (MD && MD->isInstance() &&
3276 (MD->getParent()->hasAnyDependentBases() ||
3277 MD->getType()->isDependentType()))
3278 return;
3279
3280 if (MD && !MD->isVirtual()) {
3281 // If we have a non-virtual method, check if it hides a virtual method.
3282 // (In that case, it's most likely the method has the wrong type.)
3283 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3284 FindHiddenVirtualMethods(MD, OverloadedMethods);
3285
3286 if (!OverloadedMethods.empty()) {
3287 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3288 Diag(OA->getLocation(),
3289 diag::override_keyword_hides_virtual_member_function)
3290 << "override" << (OverloadedMethods.size() > 1);
3291 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(FA->getLocation(),
3293 diag::override_keyword_hides_virtual_member_function)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << (OverloadedMethods.size() > 1);
3296 }
3297 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3298 MD->setInvalidDecl();
3299 return;
3300 }
3301 // Fall through into the general case diagnostic.
3302 // FIXME: We might want to attempt typo correction here.
3303 }
3304
3305 if (!MD || !MD->isVirtual()) {
3306 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3307 Diag(OA->getLocation(),
3308 diag::override_keyword_only_allowed_on_virtual_member_functions)
3309 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3310 D->dropAttr<OverrideAttr>();
3311 }
3312 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3313 Diag(FA->getLocation(),
3314 diag::override_keyword_only_allowed_on_virtual_member_functions)
3315 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3316 << FixItHint::CreateRemoval(FA->getLocation());
3317 D->dropAttr<FinalAttr>();
3318 }
3319 return;
3320 }
3321
3322 // C++11 [class.virtual]p5:
3323 // If a function is marked with the virt-specifier override and
3324 // does not override a member function of a base class, the program is
3325 // ill-formed.
3326 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3327 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3328 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3329 << MD->getDeclName();
3330}
3331
3333 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3334 return;
3335 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3336 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3337 return;
3338
3339 SourceLocation Loc = MD->getLocation();
3340 SourceLocation SpellingLoc = Loc;
3341 if (getSourceManager().isMacroArgExpansion(Loc))
3343 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3344 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3345 return;
3346
3347 if (MD->size_overridden_methods() > 0) {
3348 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3349 unsigned DiagID =
3350 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3351 ? DiagInconsistent
3352 : DiagSuggest;
3353 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3354 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3355 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3356 };
3357 if (isa<CXXDestructorDecl>(MD))
3358 EmitDiag(
3359 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3360 diag::warn_suggest_destructor_marked_not_override_overriding);
3361 else
3362 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3363 diag::warn_suggest_function_marked_not_override_overriding);
3364 }
3365}
3366
3367/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3368/// function overrides a virtual member function marked 'final', according to
3369/// C++11 [class.virtual]p4.
3371 const CXXMethodDecl *Old) {
3372 FinalAttr *FA = Old->getAttr<FinalAttr>();
3373 if (!FA)
3374 return false;
3375
3376 Diag(New->getLocation(), diag::err_final_function_overridden)
3377 << New->getDeclName()
3378 << FA->isSpelledAsSealed();
3379 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3380 return true;
3381}
3382
3384 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3385 // FIXME: Destruction of ObjC lifetime types has side-effects.
3386 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3387 return !RD->isCompleteDefinition() ||
3388 !RD->hasTrivialDefaultConstructor() ||
3389 !RD->hasTrivialDestructor();
3390 return false;
3391}
3392
3393// Check if there is a field shadowing.
3394void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3395 DeclarationName FieldName,
3396 const CXXRecordDecl *RD,
3397 bool DeclIsField) {
3398 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3399 return;
3400
3401 // To record a shadowed field in a base
3402 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3403 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3404 CXXBasePath &Path) {
3405 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3406 // Record an ambiguous path directly
3407 if (Bases.find(Base) != Bases.end())
3408 return true;
3409 for (const auto Field : Base->lookup(FieldName)) {
3410 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3411 Field->getAccess() != AS_private) {
3412 assert(Field->getAccess() != AS_none);
3413 assert(Bases.find(Base) == Bases.end());
3414 Bases[Base] = Field;
3415 return true;
3416 }
3417 }
3418 return false;
3419 };
3420
3421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3422 /*DetectVirtual=*/true);
3423 if (!RD->lookupInBases(FieldShadowed, Paths))
3424 return;
3425
3426 for (const auto &P : Paths) {
3427 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3428 auto It = Bases.find(Base);
3429 // Skip duplicated bases
3430 if (It == Bases.end())
3431 continue;
3432 auto BaseField = It->second;
3433 assert(BaseField->getAccess() != AS_private);
3434 if (AS_none !=
3435 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3436 Diag(Loc, diag::warn_shadow_field)
3437 << FieldName << RD << Base << DeclIsField;
3438 Diag(BaseField->getLocation(), diag::note_shadow_field);
3439 Bases.erase(It);
3440 }
3441 }
3442}
3443
3444/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3445/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3446/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3447/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3448/// present (but parsing it has been deferred).
3449NamedDecl *
3451 MultiTemplateParamsArg TemplateParameterLists,
3452 Expr *BW, const VirtSpecifiers &VS,
3453 InClassInitStyle InitStyle) {
3454 const DeclSpec &DS = D.getDeclSpec();
3456 DeclarationName Name = NameInfo.getName();
3457 SourceLocation Loc = NameInfo.getLoc();
3458
3459 // For anonymous bitfields, the location should point to the type.
3460 if (Loc.isInvalid())
3461 Loc = D.getBeginLoc();
3462
3463 Expr *BitWidth = static_cast<Expr*>(BW);
3464
3465 assert(isa<CXXRecordDecl>(CurContext));
3466 assert(!DS.isFriendSpecified());
3467
3468 bool isFunc = D.isDeclarationOfFunction();
3469 const ParsedAttr *MSPropertyAttr =
3471
3472 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3473 // The Microsoft extension __interface only permits public member functions
3474 // and prohibits constructors, destructors, operators, non-public member
3475 // functions, static methods and data members.
3476 unsigned InvalidDecl;
3477 bool ShowDeclName = true;
3478 if (!isFunc &&
3479 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3480 InvalidDecl = 0;
3481 else if (!isFunc)
3482 InvalidDecl = 1;
3483 else if (AS != AS_public)
3484 InvalidDecl = 2;
3486 InvalidDecl = 3;
3487 else switch (Name.getNameKind()) {
3489 InvalidDecl = 4;
3490 ShowDeclName = false;
3491 break;
3492
3494 InvalidDecl = 5;
3495 ShowDeclName = false;
3496 break;
3497
3500 InvalidDecl = 6;
3501 break;
3502
3503 default:
3504 InvalidDecl = 0;
3505 break;
3506 }
3507
3508 if (InvalidDecl) {
3509 if (ShowDeclName)
3510 Diag(Loc, diag::err_invalid_member_in_interface)
3511 << (InvalidDecl-1) << Name;
3512 else
3513 Diag(Loc, diag::err_invalid_member_in_interface)
3514 << (InvalidDecl-1) << "";
3515 return nullptr;
3516 }
3517 }
3518
3519 // C++ 9.2p6: A member shall not be declared to have automatic storage
3520 // duration (auto, register) or with the extern storage-class-specifier.
3521 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3522 // data members and cannot be applied to names declared const or static,
3523 // and cannot be applied to reference members.
3524 switch (DS.getStorageClassSpec()) {
3528 break;
3530 if (isFunc) {
3531 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3532
3533 // FIXME: It would be nicer if the keyword was ignored only for this
3534 // declarator. Otherwise we could get follow-up errors.
3536 }
3537 break;
3538 default:
3540 diag::err_storageclass_invalid_for_member);
3542 break;
3543 }
3544
3545 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3547 !isFunc);
3548
3549 if (DS.hasConstexprSpecifier() && isInstField) {
3551 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3552 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3553 if (InitStyle == ICIS_NoInit) {
3554 B << 0 << 0;
3556 B << FixItHint::CreateRemoval(ConstexprLoc);
3557 else {
3558 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3560 const char *PrevSpec;
3561 unsigned DiagID;
3562 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3563 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3564 (void)Failed;
3565 assert(!Failed && "Making a constexpr member const shouldn't fail");
3566 }
3567 } else {
3568 B << 1;
3569 const char *PrevSpec;
3570 unsigned DiagID;
3572 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3575 "This is the only DeclSpec that should fail to be applied");
3576 B << 1;
3577 } else {
3578 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3579 isInstField = false;
3580 }
3581 }
3582 }
3583
3585 if (isInstField) {
3586 CXXScopeSpec &SS = D.getCXXScopeSpec();
3587
3588 // Data members must have identifiers for names.
3589 if (!Name.isIdentifier()) {
3590 Diag(Loc, diag::err_bad_variable_name)
3591 << Name;
3592 return nullptr;
3593 }
3594
3595 IdentifierInfo *II = Name.getAsIdentifierInfo();
3596
3597 // Member field could not be with "template" keyword.
3598 // So TemplateParameterLists should be empty in this case.
3599 if (TemplateParameterLists.size()) {
3600 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3601 if (TemplateParams->size()) {
3602 // There is no such thing as a member field template.
3603 Diag(D.getIdentifierLoc(), diag::err_template_member)
3604 << II
3605 << SourceRange(TemplateParams->getTemplateLoc(),
3606 TemplateParams->getRAngleLoc());
3607 } else {
3608 // There is an extraneous 'template<>' for this member.
3609 Diag(TemplateParams->getTemplateLoc(),
3610 diag::err_template_member_noparams)
3611 << II
3612 << SourceRange(TemplateParams->getTemplateLoc(),
3613 TemplateParams->getRAngleLoc());
3614 }
3615 return nullptr;
3616 }
3617
3619 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3620 << II
3624 D.SetIdentifier(II, Loc);
3625 }
3626
3627 if (SS.isSet() && !SS.isInvalid()) {
3628 // The user provided a superfluous scope specifier inside a class
3629 // definition:
3630 //
3631 // class X {
3632 // int X::member;
3633 // };
3634 if (DeclContext *DC = computeDeclContext(SS, false)) {
3635 TemplateIdAnnotation *TemplateId =
3637 ? D.getName().TemplateId
3638 : nullptr;
3640 TemplateId,
3641 /*IsMemberSpecialization=*/false);
3642 } else {
3643 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3644 << Name << SS.getRange();
3645 }
3646 SS.clear();
3647 }
3648
3649 if (MSPropertyAttr) {
3650 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3651 BitWidth, InitStyle, AS, *MSPropertyAttr);
3652 if (!Member)
3653 return nullptr;
3654 isInstField = false;
3655 } else {
3656 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3657 BitWidth, InitStyle, AS);
3658 if (!Member)
3659 return nullptr;
3660 }
3661
3662 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3663 } else {
3664 Member = HandleDeclarator(S, D, TemplateParameterLists);
3665 if (!Member)
3666 return nullptr;
3667
3668 // Non-instance-fields can't have a bitfield.
3669 if (BitWidth) {
3670 if (Member->isInvalidDecl()) {
3671 // don't emit another diagnostic.
3672 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3673 // C++ 9.6p3: A bit-field shall not be a static member.
3674 // "static member 'A' cannot be a bit-field"
3675 Diag(Loc, diag::err_static_not_bitfield)
3676 << Name << BitWidth->getSourceRange();
3677 } else if (isa<TypedefDecl>(Member)) {
3678 // "typedef member 'x' cannot be a bit-field"
3679 Diag(Loc, diag::err_typedef_not_bitfield)
3680 << Name << BitWidth->getSourceRange();
3681 } else {
3682 // A function typedef ("typedef int f(); f a;").
3683 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3684 Diag(Loc, diag::err_not_integral_type_bitfield)
3685 << Name << cast<ValueDecl>(Member)->getType()
3686 << BitWidth->getSourceRange();
3687 }
3688
3689 BitWidth = nullptr;
3690 Member->setInvalidDecl();
3691 }
3692
3693 NamedDecl *NonTemplateMember = Member;
3694 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3695 NonTemplateMember = FunTmpl->getTemplatedDecl();
3696 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3697 NonTemplateMember = VarTmpl->getTemplatedDecl();
3698
3699 Member->setAccess(AS);
3700
3701 // If we have declared a member function template or static data member
3702 // template, set the access of the templated declaration as well.
3703 if (NonTemplateMember != Member)
3704 NonTemplateMember->setAccess(AS);
3705
3706 // C++ [temp.deduct.guide]p3:
3707 // A deduction guide [...] for a member class template [shall be
3708 // declared] with the same access [as the template].
3709 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3710 auto *TD = DG->getDeducedTemplate();
3711 // Access specifiers are only meaningful if both the template and the
3712 // deduction guide are from the same scope.
3713 if (AS != TD->getAccess() &&
3714 TD->getDeclContext()->getRedeclContext()->Equals(
3715 DG->getDeclContext()->getRedeclContext())) {
3716 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3717 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3718 << TD->getAccess();
3719 const AccessSpecDecl *LastAccessSpec = nullptr;
3720 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3721 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3722 LastAccessSpec = AccessSpec;
3723 }
3724 assert(LastAccessSpec && "differing access with no access specifier");
3725 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3726 << AS;
3727 }
3728 }
3729 }
3730
3731 if (VS.isOverrideSpecified())
3732 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3733 if (VS.isFinalSpecified())
3734 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3736 ? FinalAttr::Keyword_sealed
3737 : FinalAttr::Keyword_final));
3738
3739 if (VS.getLastLocation().isValid()) {
3740 // Update the end location of a method that has a virt-specifiers.
3741 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3742 MD->setRangeEnd(VS.getLastLocation());
3743 }
3744
3746
3747 assert((Name || isInstField) && "No identifier for non-field ?");
3748
3749 if (isInstField) {
3750 FieldDecl *FD = cast<FieldDecl>(Member);
3751 FieldCollector->Add(FD);
3752
3753 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3754 // Remember all explicit private FieldDecls that have a name, no side
3755 // effects and are not part of a dependent type declaration.
3756
3757 auto DeclHasUnusedAttr = [](const QualType &T) {
3758 if (const TagDecl *TD = T->getAsTagDecl())
3759 return TD->hasAttr<UnusedAttr>();
3760 if (const TypedefType *TDT = T->getAs<TypedefType>())
3761 return TDT->getDecl()->hasAttr<UnusedAttr>();
3762 return false;
3763 };
3764
3765 if (!FD->isImplicit() && FD->getDeclName() &&
3766 FD->getAccess() == AS_private &&
3767 !FD->hasAttr<UnusedAttr>() &&
3768 !FD->getParent()->isDependentContext() &&
3769 !DeclHasUnusedAttr(FD->getType()) &&
3771 UnusedPrivateFields.insert(FD);
3772 }
3773 }
3774
3775 return Member;
3776}
3777
3778namespace {
3779 class UninitializedFieldVisitor
3780 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3781 Sema &S;
3782 // List of Decls to generate a warning on. Also remove Decls that become
3783 // initialized.
3784 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3785 // List of base classes of the record. Classes are removed after their
3786 // initializers.
3787 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3788 // Vector of decls to be removed from the Decl set prior to visiting the
3789 // nodes. These Decls may have been initialized in the prior initializer.
3791 // If non-null, add a note to the warning pointing back to the constructor.
3792 const CXXConstructorDecl *Constructor;
3793 // Variables to hold state when processing an initializer list. When
3794 // InitList is true, special case initialization of FieldDecls matching
3795 // InitListFieldDecl.
3796 bool InitList;
3797 FieldDecl *InitListFieldDecl;
3798 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3799
3800 public:
3802 UninitializedFieldVisitor(Sema &S,
3803 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3804 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3805 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3806 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3807
3808 // Returns true if the use of ME is not an uninitialized use.
3809 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3810 bool CheckReferenceOnly) {
3812 bool ReferenceField = false;
3813 while (ME) {
3814 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3815 if (!FD)
3816 return false;
3817 Fields.push_back(FD);
3818 if (FD->getType()->isReferenceType())
3819 ReferenceField = true;
3820 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3821 }
3822
3823 // Binding a reference to an uninitialized field is not an
3824 // uninitialized use.
3825 if (CheckReferenceOnly && !ReferenceField)
3826 return true;
3827
3828 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3829 // Discard the first field since it is the field decl that is being
3830 // initialized.
3831 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3832 UsedFieldIndex.push_back(FD->getFieldIndex());
3833
3834 for (auto UsedIter = UsedFieldIndex.begin(),
3835 UsedEnd = UsedFieldIndex.end(),
3836 OrigIter = InitFieldIndex.begin(),
3837 OrigEnd = InitFieldIndex.end();
3838 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3839 if (*UsedIter < *OrigIter)
3840 return true;
3841 if (*UsedIter > *OrigIter)
3842 break;
3843 }
3844
3845 return false;
3846 }
3847
3848 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3849 bool AddressOf) {
3850 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3851 return;
3852
3853 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3854 // or union.
3855 MemberExpr *FieldME = ME;
3856
3857 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3858
3859 Expr *Base = ME;
3860 while (MemberExpr *SubME =
3861 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3862
3863 if (isa<VarDecl>(SubME->getMemberDecl()))
3864 return;
3865
3866 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3867 if (!FD->isAnonymousStructOrUnion())
3868 FieldME = SubME;
3869
3870 if (!FieldME->getType().isPODType(S.Context))
3871 AllPODFields = false;
3872
3873 Base = SubME->getBase();
3874 }
3875
3876 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3877 Visit(Base);
3878 return;
3879 }
3880
3881 if (AddressOf && AllPODFields)
3882 return;
3883
3884 ValueDecl* FoundVD = FieldME->getMemberDecl();
3885
3886 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3887 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3888 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3889 }
3890
3891 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3892 QualType T = BaseCast->getType();
3893 if (T->isPointerType() &&
3894 BaseClasses.count(T->getPointeeType())) {
3895 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3896 << T->getPointeeType() << FoundVD;
3897 }
3898 }
3899 }
3900
3901 if (!Decls.count(FoundVD))
3902 return;
3903
3904 const bool IsReference = FoundVD->getType()->isReferenceType();
3905
3906 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3907 // Special checking for initializer lists.
3908 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3909 return;
3910 }
3911 } else {
3912 // Prevent double warnings on use of unbounded references.
3913 if (CheckReferenceOnly && !IsReference)
3914 return;
3915 }
3916
3917 unsigned diag = IsReference
3918 ? diag::warn_reference_field_is_uninit
3919 : diag::warn_field_is_uninit;
3920 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3921 if (Constructor)
3922 S.Diag(Constructor->getLocation(),
3923 diag::note_uninit_in_this_constructor)
3924 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3925
3926 }
3927
3928 void HandleValue(Expr *E, bool AddressOf) {
3929 E = E->IgnoreParens();
3930
3931 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3932 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3933 AddressOf /*AddressOf*/);
3934 return;
3935 }
3936
3937 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3938 Visit(CO->getCond());
3939 HandleValue(CO->getTrueExpr(), AddressOf);
3940 HandleValue(CO->getFalseExpr(), AddressOf);
3941 return;
3942 }
3943
3944 if (BinaryConditionalOperator *BCO =
3945 dyn_cast<BinaryConditionalOperator>(E)) {
3946 Visit(BCO->getCond());
3947 HandleValue(BCO->getFalseExpr(), AddressOf);
3948 return;
3949 }
3950
3951 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3952 HandleValue(OVE->getSourceExpr(), AddressOf);
3953 return;
3954 }
3955
3956 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3957 switch (BO->getOpcode()) {
3958 default:
3959 break;
3960 case(BO_PtrMemD):
3961 case(BO_PtrMemI):
3962 HandleValue(BO->getLHS(), AddressOf);
3963 Visit(BO->getRHS());
3964 return;
3965 case(BO_Comma):
3966 Visit(BO->getLHS());
3967 HandleValue(BO->getRHS(), AddressOf);
3968 return;
3969 }
3970 }
3971
3972 Visit(E);
3973 }
3974
3975 void CheckInitListExpr(InitListExpr *ILE) {
3976 InitFieldIndex.push_back(0);
3977 for (auto *Child : ILE->children()) {
3978 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3979 CheckInitListExpr(SubList);
3980 } else {
3981 Visit(Child);
3982 }
3983 ++InitFieldIndex.back();
3984 }
3985 InitFieldIndex.pop_back();
3986 }
3987
3988 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3989 FieldDecl *Field, const Type *BaseClass) {
3990 // Remove Decls that may have been initialized in the previous
3991 // initializer.
3992 for (ValueDecl* VD : DeclsToRemove)
3993 Decls.erase(VD);
3994 DeclsToRemove.clear();
3995
3996 Constructor = FieldConstructor;
3997 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3998
3999 if (ILE && Field) {
4000 InitList = true;
4001 InitListFieldDecl = Field;
4002 InitFieldIndex.clear();
4003 CheckInitListExpr(ILE);
4004 } else {
4005 InitList = false;
4006 Visit(E);
4007 }
4008
4009 if (Field)
4010 Decls.erase(Field);
4011 if (BaseClass)
4012 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4013 }
4014
4015 void VisitMemberExpr(MemberExpr *ME) {
4016 // All uses of unbounded reference fields will warn.
4017 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4018 }
4019
4020 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4021 if (E->getCastKind() == CK_LValueToRValue) {
4022 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4023 return;
4024 }
4025
4026 Inherited::VisitImplicitCastExpr(E);
4027 }
4028
4029 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4030 if (E->getConstructor()->isCopyConstructor()) {
4031 Expr *ArgExpr = E->getArg(0);
4032 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4033 if (ILE->getNumInits() == 1)
4034 ArgExpr = ILE->getInit(0);
4035 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4036 if (ICE->getCastKind() == CK_NoOp)
4037 ArgExpr = ICE->getSubExpr();
4038 HandleValue(ArgExpr, false /*AddressOf*/);
4039 return;
4040 }
4041 Inherited::VisitCXXConstructExpr(E);
4042 }
4043
4044 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4045 Expr *Callee = E->getCallee();
4046 if (isa<MemberExpr>(Callee)) {
4047 HandleValue(Callee, false /*AddressOf*/);
4048 for (auto *Arg : E->arguments())
4049 Visit(Arg);
4050 return;
4051 }
4052
4053 Inherited::VisitCXXMemberCallExpr(E);
4054 }
4055
4056 void VisitCallExpr(CallExpr *E) {
4057 // Treat std::move as a use.
4058 if (E->isCallToStdMove()) {
4059 HandleValue(E->getArg(0), /*AddressOf=*/false);
4060 return;
4061 }
4062
4063 Inherited::VisitCallExpr(E);
4064 }
4065
4066 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4067 Expr *Callee = E->getCallee();
4068
4069 if (isa<UnresolvedLookupExpr>(Callee))
4070 return Inherited::VisitCXXOperatorCallExpr(E);
4071
4072 Visit(Callee);
4073 for (auto *Arg : E->arguments())
4074 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4075 }
4076
4077 void VisitBinaryOperator(BinaryOperator *E) {
4078 // If a field assignment is detected, remove the field from the
4079 // uninitiailized field set.
4080 if (E->getOpcode() == BO_Assign)
4081 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4082 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4083 if (!FD->getType()->isReferenceType())
4084 DeclsToRemove.push_back(FD);
4085
4086 if (E->isCompoundAssignmentOp()) {
4087 HandleValue(E->getLHS(), false /*AddressOf*/);
4088 Visit(E->getRHS());
4089 return;
4090 }
4091
4092 Inherited::VisitBinaryOperator(E);
4093 }
4094
4095 void VisitUnaryOperator(UnaryOperator *E) {
4096 if (E->isIncrementDecrementOp()) {
4097 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4098 return;
4099 }
4100 if (E->getOpcode() == UO_AddrOf) {
4101 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4102 HandleValue(ME->getBase(), true /*AddressOf*/);
4103 return;
4104 }
4105 }
4106
4107 Inherited::VisitUnaryOperator(E);
4108 }
4109 };
4110
4111 // Diagnose value-uses of fields to initialize themselves, e.g.
4112 // foo(foo)
4113 // where foo is not also a parameter to the constructor.
4114 // Also diagnose across field uninitialized use such as
4115 // x(y), y(x)
4116 // TODO: implement -Wuninitialized and fold this into that framework.
4117 static void DiagnoseUninitializedFields(
4118 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4119
4120 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4121 Constructor->getLocation())) {
4122 return;
4123 }
4124
4125 if (Constructor->isInvalidDecl())
4126 return;
4127
4128 const CXXRecordDecl *RD = Constructor->getParent();
4129
4130 if (RD->isDependentContext())
4131 return;
4132
4133 // Holds fields that are uninitialized.
4134 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4135
4136 // At the beginning, all fields are uninitialized.
4137 for (auto *I : RD->decls()) {
4138 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4139 UninitializedFields.insert(FD);
4140 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4141 UninitializedFields.insert(IFD->getAnonField());
4142 }
4143 }
4144
4145 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4146 for (const auto &I : RD->bases())
4147 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4148
4149 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4150 return;
4151
4152 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4153 UninitializedFields,
4154 UninitializedBaseClasses);
4155
4156 for (const auto *FieldInit : Constructor->inits()) {
4157 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4158 break;
4159
4160 Expr *InitExpr = FieldInit->getInit();
4161 if (!InitExpr)
4162 continue;
4163
4165 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4166 InitExpr = Default->getExpr();
4167 if (!InitExpr)
4168 continue;
4169 // In class initializers will point to the constructor.
4170 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4171 FieldInit->getAnyMember(),
4172 FieldInit->getBaseClass());
4173 } else {
4174 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4175 FieldInit->getAnyMember(),
4176 FieldInit->getBaseClass());
4177 }
4178 }
4179 }
4180} // namespace
4181
4182/// Enter a new C++ default initializer scope. After calling this, the
4183/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4184/// parsing or instantiating the initializer failed.
4186 // Create a synthetic function scope to represent the call to the constructor
4187 // that notionally surrounds a use of this initializer.
4189}
4190
4192 if (!D.isFunctionDeclarator())
4193 return;
4194 auto &FTI = D.getFunctionTypeInfo();
4195 if (!FTI.Params)
4196 return;
4197 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4198 FTI.NumParams)) {
4199 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4200 if (ParamDecl->getDeclName())
4201 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4202 }
4203}
4204
4206 return ActOnRequiresClause(ConstraintExpr);
4207}
4208
4210 if (ConstraintExpr.isInvalid())
4211 return ExprError();
4212
4213 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4214 if (ConstraintExpr.isInvalid())
4215 return ExprError();
4216
4217 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4219 return ExprError();
4220
4221 return ConstraintExpr;
4222}
4223
4225 Expr *InitExpr,
4226 SourceLocation InitLoc) {
4227 InitializedEntity Entity =
4229 InitializationKind Kind =
4232 InitExpr->getBeginLoc(),
4233 InitExpr->getEndLoc())
4234 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4235 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4236 return Seq.Perform(*this, Entity, Kind, InitExpr);
4237}
4238
4239/// This is invoked after parsing an in-class initializer for a
4240/// non-static C++ class member, and after instantiating an in-class initializer
4241/// in a class template. Such actions are deferred until the class is complete.
4243 SourceLocation InitLoc,
4244 Expr *InitExpr) {
4245 // Pop the notional constructor scope we created earlier.
4246 PopFunctionScopeInfo(nullptr, D);
4247
4248 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4249 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4250 "must set init style when field is created");
4251
4252 if (!InitExpr) {
4253 D->setInvalidDecl();
4254 if (FD)
4256 return;
4257 }
4258
4260 FD->setInvalidDecl();
4262 return;
4263 }
4264
4265 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4266 /*RecoverUncorrectedTypos=*/true);
4267 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4268 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4269 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4270 // C++11 [class.base.init]p7:
4271 // The initialization of each base and member constitutes a
4272 // full-expression.
4273 if (!Init.isInvalid())
4274 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4275 if (Init.isInvalid()) {
4276 FD->setInvalidDecl();
4277 return;
4278 }
4279 }
4280
4281 FD->setInClassInitializer(Init.get());
4282}
4283
4284/// Find the direct and/or virtual base specifiers that
4285/// correspond to the given base type, for use in base initialization
4286/// within a constructor.
4287static bool FindBaseInitializer(Sema &SemaRef,
4288 CXXRecordDecl *ClassDecl,
4289 QualType BaseType,
4290 const CXXBaseSpecifier *&DirectBaseSpec,
4291 const CXXBaseSpecifier *&VirtualBaseSpec) {
4292 // First, check for a direct base class.
4293 DirectBaseSpec = nullptr;
4294 for (const auto &Base : ClassDecl->bases()) {
4295 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4296 // We found a direct base of this type. That's what we're
4297 // initializing.
4298 DirectBaseSpec = &Base;
4299 break;
4300 }
4301 }
4302
4303 // Check for a virtual base class.
4304 // FIXME: We might be able to short-circuit this if we know in advance that
4305 // there are no virtual bases.
4306 VirtualBaseSpec = nullptr;
4307 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4308 // We haven't found a base yet; search the class hierarchy for a
4309 // virtual base class.
4310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4311 /*DetectVirtual=*/false);
4312 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4313 SemaRef.Context.getTypeDeclType(ClassDecl),
4314 BaseType, Paths)) {
4315 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4316 Path != Paths.end(); ++Path) {
4317 if (Path->back().Base->isVirtual()) {
4318 VirtualBaseSpec = Path->back().Base;
4319 break;
4320 }
4321 }
4322 }
4323 }
4324
4325 return DirectBaseSpec || VirtualBaseSpec;
4326}
4327
4328/// Handle a C++ member initializer using braced-init-list syntax.
4331 Scope *S,
4332 CXXScopeSpec &SS,
4333 IdentifierInfo *MemberOrBase,
4334 ParsedType TemplateTypeTy,
4335 const DeclSpec &DS,
4336 SourceLocation IdLoc,
4337 Expr *InitList,
4338 SourceLocation EllipsisLoc) {
4339 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4340 DS, IdLoc, InitList,
4341 EllipsisLoc);
4342}
4343
4344/// Handle a C++ member initializer using parentheses syntax.
4347 Scope *S,
4348 CXXScopeSpec &SS,
4349 IdentifierInfo *MemberOrBase,
4350 ParsedType TemplateTypeTy,
4351 const DeclSpec &DS,
4352 SourceLocation IdLoc,
4353 SourceLocation LParenLoc,
4354 ArrayRef<Expr *> Args,
4355 SourceLocation RParenLoc,
4356 SourceLocation EllipsisLoc) {
4357 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4358 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4359 DS, IdLoc, List, EllipsisLoc);
4360}
4361
4362namespace {
4363
4364// Callback to only accept typo corrections that can be a valid C++ member
4365// initializer: either a non-static field member or a base class.
4366class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4367public:
4368 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4369 : ClassDecl(ClassDecl) {}
4370
4371 bool ValidateCandidate(const TypoCorrection &candidate) override {
4372 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4373 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4374 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4375 return isa<TypeDecl>(ND);
4376 }
4377 return false;
4378 }
4379
4380 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4381 return std::make_unique<MemInitializerValidatorCCC>(*this);
4382 }
4383
4384private:
4385 CXXRecordDecl *ClassDecl;
4386};
4387
4388}
4389
4391 RecordDecl *ClassDecl,
4392 const IdentifierInfo *Name) {
4393 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4395 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4396 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4398 });
4399 // We did not find a placeholder variable
4400 if (Found == Result.end())
4401 return false;
4402 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4403 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4404 const NamedDecl *ND = *It;
4405 if (ND->getDeclContext() != ND->getDeclContext())
4406 break;
4407 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4409 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4410 }
4411 return true;
4412}
4413
4414ValueDecl *
4416 const IdentifierInfo *MemberOrBase) {
4417 ValueDecl *ND = nullptr;
4418 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4419 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4420 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4421 if (ND) {
4422 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4423 return nullptr;
4424 break;
4425 }
4426 if (!IsPlaceholder)
4427 return cast<ValueDecl>(D);
4428 ND = cast<ValueDecl>(D);
4429 }
4430 }
4431 return ND;
4432}
4433
4434ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4435 CXXScopeSpec &SS,
4436 ParsedType TemplateTypeTy,
4437 IdentifierInfo *MemberOrBase) {
4438 if (SS.getScopeRep() || TemplateTypeTy)
4439 return nullptr;
4440 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4441}
4442
4443/// Handle a C++ member initializer.
4446 Scope *S,
4447 CXXScopeSpec &SS,
4448 IdentifierInfo *MemberOrBase,
4449 ParsedType TemplateTypeTy,
4450 const DeclSpec &DS,
4451 SourceLocation IdLoc,
4452 Expr *Init,
4453 SourceLocation EllipsisLoc) {
4454 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4455 /*RecoverUncorrectedTypos=*/true);
4456 if (!Res.isUsable())
4457 return true;
4458 Init = Res.get();
4459
4460 if (!ConstructorD)
4461 return true;
4462
4463 AdjustDeclIfTemplate(ConstructorD);
4464
4465 CXXConstructorDecl *Constructor
4466 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4467 if (!Constructor) {
4468 // The user wrote a constructor initializer on a function that is
4469 // not a C++ constructor. Ignore the error for now, because we may
4470 // have more member initializers coming; we'll diagnose it just
4471 // once in ActOnMemInitializers.
4472 return true;
4473 }
4474
4475 CXXRecordDecl *ClassDecl = Constructor->getParent();
4476
4477 // C++ [class.base.init]p2:
4478 // Names in a mem-initializer-id are looked up in the scope of the
4479 // constructor's class and, if not found in that scope, are looked
4480 // up in the scope containing the constructor's definition.
4481 // [Note: if the constructor's class contains a member with the
4482 // same name as a direct or virtual base class of the class, a
4483 // mem-initializer-id naming the member or base class and composed
4484 // of a single identifier refers to the class member. A
4485 // mem-initializer-id for the hidden base class may be specified
4486 // using a qualified name. ]
4487
4488 // Look for a member, first.
4489 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4490 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4491 if (EllipsisLoc.isValid())
4492 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4493 << MemberOrBase
4494 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4495
4496 return BuildMemberInitializer(Member, Init, IdLoc);
4497 }
4498 // It didn't name a member, so see if it names a class.
4499 QualType BaseType;
4500 TypeSourceInfo *TInfo = nullptr;
4501
4502 if (TemplateTypeTy) {
4503 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4504 if (BaseType.isNull())
4505 return true;
4506 } else if (DS.getTypeSpecType() == TST_decltype) {
4507 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4508 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4509 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4510 return true;
4511 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4512 BaseType =
4514 DS.getBeginLoc(), DS.getEllipsisLoc());
4515 } else {
4516 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4517 LookupParsedName(R, S, &SS);
4518
4519 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4520 if (!TyD) {
4521 if (R.isAmbiguous()) return true;
4522
4523 // We don't want access-control diagnostics here.
4525
4526 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4527 bool NotUnknownSpecialization = false;
4528 DeclContext *DC = computeDeclContext(SS, false);
4529 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4530 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4531
4532 if (!NotUnknownSpecialization) {
4533 // When the scope specifier can refer to a member of an unknown
4534 // specialization, we take it as a type name.
4535 BaseType = CheckTypenameType(
4537 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4538 if (BaseType.isNull())
4539 return true;
4540
4541 TInfo = Context.CreateTypeSourceInfo(BaseType);
4544 if (!TL.isNull()) {
4545 TL.setNameLoc(IdLoc);
4548 }
4549
4550 R.clear();
4551 R.setLookupName(MemberOrBase);
4552 }
4553 }
4554
4555 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4556 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4557 auto *TempSpec = cast<TemplateSpecializationType>(
4558 UnqualifiedBase->getInjectedClassNameSpecialization());
4559 TemplateName TN = TempSpec->getTemplateName();
4560 for (auto const &Base : ClassDecl->bases()) {
4561 auto BaseTemplate =
4562 Base.getType()->getAs<TemplateSpecializationType>();
4563 if (BaseTemplate && Context.hasSameTemplateName(
4564 BaseTemplate->getTemplateName(), TN)) {
4565 Diag(IdLoc, diag::ext_unqualified_base_class)
4566 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4567 BaseType = Base.getType();
4568 break;
4569 }
4570 }
4571 }
4572 }
4573
4574 // If no results were found, try to correct typos.
4575 TypoCorrection Corr;
4576 MemInitializerValidatorCCC CCC(ClassDecl);
4577 if (R.empty() && BaseType.isNull() &&
4578 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4579 CCC, CTK_ErrorRecovery, ClassDecl))) {
4581 // We have found a non-static data member with a similar
4582 // name to what was typed; complain and initialize that
4583 // member.
4584 diagnoseTypo(Corr,
4585 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4586 << MemberOrBase << true);
4587 return BuildMemberInitializer(Member, Init, IdLoc);
4588 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4589 const CXXBaseSpecifier *DirectBaseSpec;
4590 const CXXBaseSpecifier *VirtualBaseSpec;
4591 if (FindBaseInitializer(*this, ClassDecl,
4593 DirectBaseSpec, VirtualBaseSpec)) {
4594 // We have found a direct or virtual base class with a
4595 // similar name to what was typed; complain and initialize
4596 // that base class.
4597 diagnoseTypo(Corr,
4598 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4599 << MemberOrBase << false,
4600 PDiag() /*Suppress note, we provide our own.*/);
4601
4602 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4603 : VirtualBaseSpec;
4604 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4605 << BaseSpec->getType() << BaseSpec->getSourceRange();
4606
4607 TyD = Type;
4608 }
4609 }
4610 }
4611
4612 if (!TyD && BaseType.isNull()) {
4613 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4614 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4615 return true;
4616 }
4617 }
4618
4619 if (BaseType.isNull()) {
4622 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4623 TInfo = Context.CreateTypeSourceInfo(BaseType);
4625 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4628 }
4629 }
4630
4631 if (!TInfo)
4632 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4633
4634 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4635}
4636
4639 SourceLocation IdLoc) {
4640 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4641 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4642 assert((DirectMember || IndirectMember) &&
4643 "Member must be a FieldDecl or IndirectFieldDecl");
4644
4646 return true;
4647
4648 if (Member->isInvalidDecl())
4649 return true;
4650
4651 MultiExprArg Args;
4652 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4653 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4654 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4655 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4656 } else {
4657 // Template instantiation doesn't reconstruct ParenListExprs for us.
4658 Args = Init;
4659 }
4660
4661 SourceRange InitRange = Init->getSourceRange();
4662
4663 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4664 // Can't check initialization for a member of dependent type or when
4665 // any of the arguments are type-dependent expressions.
4667 } else {
4668 bool InitList = false;
4669 if (isa<InitListExpr>(Init)) {
4670 InitList = true;
4671 Args = Init;
4672 }
4673
4674 // Initialize the member.
4675 InitializedEntity MemberEntity =
4676 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4677 : InitializedEntity::InitializeMember(IndirectMember,
4678 nullptr);
4679 InitializationKind Kind =
4681 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4682 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4683 InitRange.getEnd());
4684
4685 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4686 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4687 nullptr);
4688 if (!MemberInit.isInvalid()) {
4689 // C++11 [class.base.init]p7:
4690 // The initialization of each base and member constitutes a
4691 // full-expression.
4692 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4693 /*DiscardedValue*/ false);
4694 }
4695
4696 if (MemberInit.isInvalid()) {
4697 // Args were sensible expressions but we couldn't initialize the member
4698 // from them. Preserve them in a RecoveryExpr instead.
4699 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4700 Member->getType())
4701 .get();
4702 if (!Init)
4703 return true;
4704 } else {
4705 Init = MemberInit.get();
4706 }
4707 }
4708
4709 if (DirectMember) {
4710 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4711 InitRange.getBegin(), Init,
4712 InitRange.getEnd());
4713 } else {
4714 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4715 InitRange.getBegin(), Init,
4716 InitRange.getEnd());
4717 }
4718}
4719
4722 CXXRecordDecl *ClassDecl) {
4723 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4724 if (!LangOpts.CPlusPlus11)
4725 return Diag(NameLoc, diag::err_delegating_ctor)
4726 << TInfo->getTypeLoc().getSourceRange();
4727 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4728
4729 bool InitList = true;
4730 MultiExprArg Args = Init;
4731 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4732 InitList = false;
4733 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4734 }
4735
4736 SourceRange InitRange = Init->getSourceRange();
4737 // Initialize the object.
4739 QualType(ClassDecl->getTypeForDecl(), 0));
4740 InitializationKind Kind =
4742 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4743 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4744 InitRange.getEnd());
4745 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4746 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4747 Args, nullptr);
4748 if (!DelegationInit.isInvalid()) {
4749 assert((DelegationInit.get()->containsErrors() ||
4750 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4751 "Delegating constructor with no target?");
4752
4753 // C++11 [class.base.init]p7:
4754 // The initialization of each base and member constitutes a
4755 // full-expression.
4756 DelegationInit = ActOnFinishFullExpr(
4757 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4758 }
4759
4760 if (DelegationInit.isInvalid()) {
4761 DelegationInit =
4762 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4763 QualType(ClassDecl->getTypeForDecl(), 0));
4764 if (DelegationInit.isInvalid())
4765 return true;
4766 } else {
4767 // If we are in a dependent context, template instantiation will
4768 // perform this type-checking again. Just save the arguments that we
4769 // received in a ParenListExpr.
4770 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4771 // of the information that we have about the base
4772 // initializer. However, deconstructing the ASTs is a dicey process,
4773 // and this approach is far more likely to get the corner cases right.
4775 DelegationInit = Init;
4776 }
4777
4778 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4779 DelegationInit.getAs<Expr>(),
4780 InitRange.getEnd());
4781}
4782
4785 Expr *Init, CXXRecordDecl *ClassDecl,
4786 SourceLocation EllipsisLoc) {
4787 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4788
4789 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4790 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4791 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4792
4793 // C++ [class.base.init]p2:
4794 // [...] Unless the mem-initializer-id names a nonstatic data
4795 // member of the constructor's class or a direct or virtual base
4796 // of that class, the mem-initializer is ill-formed. A
4797 // mem-initializer-list can initialize a base class using any
4798 // name that denotes that base class type.
4799
4800 // We can store the initializers in "as-written" form and delay analysis until
4801 // instantiation if the constructor is dependent. But not for dependent
4802 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4803 bool Dependent = CurContext->isDependentContext() &&
4804 (BaseType->isDependentType() || Init->isTypeDependent());
4805
4806 SourceRange InitRange = Init->getSourceRange();
4807 if (EllipsisLoc.isValid()) {
4808 // This is a pack expansion.
4809 if (!BaseType->containsUnexpandedParameterPack()) {
4810 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4811 << SourceRange(BaseLoc, InitRange.getEnd());
4812
4813 EllipsisLoc = SourceLocation();
4814 }
4815 } else {
4816 // Check for any unexpanded parameter packs.
4817 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4818 return true;
4819
4821 return true;
4822 }
4823
4824 // Check for direct and virtual base classes.
4825 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4826 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4827 if (!Dependent) {
4829 BaseType))
4830 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4831
4832 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4833 VirtualBaseSpec);
4834
4835 // C++ [base.class.init]p2:
4836 // Unless the mem-initializer-id names a nonstatic data member of the
4837 // constructor's class or a direct or virtual base of that class, the
4838 // mem-initializer is ill-formed.
4839 if (!DirectBaseSpec && !VirtualBaseSpec) {
4840 // If the class has any dependent bases, then it's possible that
4841 // one of those types will resolve to the same type as
4842 // BaseType. Therefore, just treat this as a dependent base
4843 // class initialization. FIXME: Should we try to check the
4844 // initialization anyway? It seems odd.
4845 if (ClassDecl->hasAnyDependentBases())
4846 Dependent = true;
4847 else
4848 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4849 << BaseType << Context.getTypeDeclType(ClassDecl)
4850 << BaseTInfo->getTypeLoc().getSourceRange();
4851 }
4852 }
4853
4854 if (Dependent) {
4856
4857 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4858 /*IsVirtual=*/false,
4859 InitRange.getBegin(), Init,
4860 InitRange.getEnd(), EllipsisLoc);
4861 }
4862
4863 // C++ [base.class.init]p2:
4864 // If a mem-initializer-id is ambiguous because it designates both
4865 // a direct non-virtual base class and an inherited virtual base
4866 // class, the mem-initializer is ill-formed.
4867 if (DirectBaseSpec && VirtualBaseSpec)
4868 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4869 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4870
4871 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4872 if (!BaseSpec)
4873 BaseSpec = VirtualBaseSpec;
4874
4875 // Initialize the base.
4876 bool InitList = true;
4877 MultiExprArg Args = Init;
4878 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4879 InitList = false;
4880 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4881 }
4882
4883 InitializedEntity BaseEntity =
4884 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4885 InitializationKind Kind =
4886 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4887 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4888 InitRange.getEnd());
4889 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4890 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4891 if (!BaseInit.isInvalid()) {
4892 // C++11 [class.base.init]p7:
4893 // The initialization of each base and member constitutes a
4894 // full-expression.
4895 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4896 /*DiscardedValue*/ false);
4897 }
4898
4899 if (BaseInit.isInvalid()) {
4900 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4901 Args, BaseType);
4902 if (BaseInit.isInvalid())
4903 return true;
4904 } else {
4905 // If we are in a dependent context, template instantiation will
4906 // perform this type-checking again. Just save the arguments that we
4907 // received in a ParenListExpr.
4908 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4909 // of the information that we have about the base
4910 // initializer. However, deconstructing the ASTs is a dicey process,
4911 // and this approach is far more likely to get the corner cases right.
4913 BaseInit = Init;
4914 }
4915
4916 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4917 BaseSpec->isVirtual(),
4918 InitRange.getBegin(),
4919 BaseInit.getAs<Expr>(),
4920 InitRange.getEnd(), EllipsisLoc);
4921}
4922
4923// Create a static_cast<T&&>(expr).
4924static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4925 QualType TargetType =
4926 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4928 SourceLocation ExprLoc = E->getBeginLoc();
4929 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4930 TargetType, ExprLoc);
4931
4932 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4933 SourceRange(ExprLoc, ExprLoc),
4934 E->getSourceRange()).get();
4935}
4936
4937/// ImplicitInitializerKind - How an implicit base or member initializer should
4938/// initialize its base or member.
4945
4946static bool
4948 ImplicitInitializerKind ImplicitInitKind,
4949 CXXBaseSpecifier *BaseSpec,
4950 bool IsInheritedVirtualBase,
4951 CXXCtorInitializer *&CXXBaseInit) {
4952 InitializedEntity InitEntity
4953 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4954 IsInheritedVirtualBase);
4955
4956 ExprResult BaseInit;
4957
4958 switch (ImplicitInitKind) {
4959 case IIK_Inherit:
4960 case IIK_Default: {
4961 InitializationKind InitKind
4962 = InitializationKind::CreateDefault(Constructor->getLocation());
4963 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4964 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4965 break;
4966 }
4967
4968 case IIK_Move:
4969 case IIK_Copy: {
4970 bool Moving = ImplicitInitKind == IIK_Move;
4971 ParmVarDecl *Param = Constructor->getParamDecl(0);
4972 QualType ParamType = Param->getType().getNonReferenceType();
4973
4974 Expr *CopyCtorArg =
4976 SourceLocation(), Param, false,
4977 Constructor->getLocation(), ParamType,
4978 VK_LValue, nullptr);
4979
4980 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4981
4982 // Cast to the base class to avoid ambiguities.
4983 QualType ArgTy =
4984 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4985 ParamType.getQualifiers());
4986
4987 if (Moving) {
4988 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4989 }
4990
4991 CXXCastPath BasePath;
4992 BasePath.push_back(BaseSpec);
4993 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4994 CK_UncheckedDerivedToBase,
4995 Moving ? VK_XValue : VK_LValue,
4996 &BasePath).get();
4997
4998 InitializationKind InitKind
4999 = InitializationKind::CreateDirect(Constructor->getLocation(),
5001 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5002 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5003 break;
5004 }
5005 }
5006
5007 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5008 if (BaseInit.isInvalid())
5009 return true;
5010
5011 CXXBaseInit =
5012 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5013 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5014 SourceLocation()),
5015 BaseSpec->isVirtual(),
5017 BaseInit.getAs<Expr>(),
5019 SourceLocation());
5020
5021 return false;
5022}
5023
5024static bool RefersToRValueRef(Expr *MemRef) {
5025 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5026 return Referenced->getType()->isRValueReferenceType();
5027}
5028
5029static bool
5031 ImplicitInitializerKind ImplicitInitKind,
5032 FieldDecl *Field, IndirectFieldDecl *Indirect,
5033 CXXCtorInitializer *&CXXMemberInit) {
5034 if (Field->isInvalidDecl())
5035 return true;
5036
5037 SourceLocation Loc = Constructor->getLocation();
5038
5039 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5040 bool Moving = ImplicitInitKind == IIK_Move;
5041 ParmVarDecl *Param = Constructor->getParamDecl(0);
5042 QualType ParamType = Param->getType().getNonReferenceType();
5043
5044 // Suppress copying zero-width bitfields.
5045 if (Field->isZeroLengthBitField(SemaRef.Context))
5046 return false;
5047
5048 Expr *MemberExprBase =
5050 SourceLocation(), Param, false,
5051 Loc, ParamType, VK_LValue, nullptr);
5052
5053 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5054
5055 if (Moving) {
5056 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5057 }
5058
5059 // Build a reference to this field within the parameter.
5060 CXXScopeSpec SS;
5061 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5063 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5064 : cast<ValueDecl>(Field), AS_public);
5065 MemberLookup.resolveKind();
5066 ExprResult CtorArg
5067 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5068 ParamType, Loc,
5069 /*IsArrow=*/false,
5070 SS,
5071 /*TemplateKWLoc=*/SourceLocation(),
5072 /*FirstQualifierInScope=*/nullptr,
5073 MemberLookup,
5074 /*TemplateArgs=*/nullptr,
5075 /*S*/nullptr);
5076 if (CtorArg.isInvalid())
5077 return true;
5078
5079 // C++11 [class.copy]p15:
5080 // - if a member m has rvalue reference type T&&, it is direct-initialized
5081 // with static_cast<T&&>(x.m);
5082 if (RefersToRValueRef(CtorArg.get())) {
5083 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5084 }
5085
5086 InitializedEntity Entity =
5087 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5088 /*Implicit*/ true)
5089 : InitializedEntity::InitializeMember(Field, nullptr,
5090 /*Implicit*/ true);
5091
5092 // Direct-initialize to use the copy constructor.
5093 InitializationKind InitKind =
5095
5096 Expr *CtorArgE = CtorArg.getAs<Expr>();
5097 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5098 ExprResult MemberInit =
5099 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5100 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5101 if (MemberInit.isInvalid())
5102 return true;
5103
5104 if (Indirect)
5105 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5106 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5107 else
5108 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5109 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5110 return false;
5111 }
5112
5113 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5114 "Unhandled implicit init kind!");
5115
5116 QualType FieldBaseElementType =
5117 SemaRef.Context.getBaseElementType(Field->getType());
5118
5119 if (FieldBaseElementType->isRecordType()) {
5120 InitializedEntity InitEntity =
5121 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5122 /*Implicit*/ true)
5123 : InitializedEntity::InitializeMember(Field, nullptr,
5124 /*Implicit*/ true);
5125 InitializationKind InitKind =
5127
5128 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5129 ExprResult MemberInit =
5130 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5131
5132 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5133 if (MemberInit.isInvalid())
5134 return true;
5135
5136 if (Indirect)
5137 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5138 Indirect, Loc,
5139 Loc,
5140 MemberInit.get(),
5141 Loc);
5142 else
5143 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5144 Field, Loc, Loc,
5145 MemberInit.get(),
5146 Loc);
5147 return false;
5148 }
5149
5150 if (!Field->getParent()->isUnion()) {
5151 if (FieldBaseElementType->isReferenceType()) {
5152 SemaRef.Diag(Constructor->getLocation(),
5153 diag::err_uninitialized_member_in_ctor)
5154 << (int)Constructor->isImplicit()
5155 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5156 << 0 << Field->getDeclName();
5157 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5158 return true;
5159 }
5160
5161 if (FieldBaseElementType.isConstQualified()) {
5162 SemaRef.Diag(Constructor->getLocation(),
5163 diag::err_uninitialized_member_in_ctor)
5164 << (int)Constructor->isImplicit()
5165 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5166 << 1 << Field->getDeclName();
5167 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5168 return true;
5169 }
5170 }
5171
5172 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5173 // ARC and Weak:
5174 // Default-initialize Objective-C pointers to NULL.
5175 CXXMemberInit
5176 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5177 Loc, Loc,
5178 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5179 Loc);
5180 return false;
5181 }
5182
5183 // Nothing to initialize.
5184 CXXMemberInit = nullptr;
5185 return false;
5186}
5187
5188namespace {
5189struct BaseAndFieldInfo {
5190 Sema &S;
5191 CXXConstructorDecl *Ctor;
5192 bool AnyErrorsInInits;
5194 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5196 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5197
5198 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5199 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5200 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5201 if (Ctor->getInheritedConstructor())
5202 IIK = IIK_Inherit;
5203 else if (Generated && Ctor->isCopyConstructor())
5204 IIK = IIK_Copy;
5205 else if (Generated && Ctor->isMoveConstructor())
5206 IIK = IIK_Move;
5207 else
5208 IIK = IIK_Default;
5209 }
5210
5211 bool isImplicitCopyOrMove() const {
5212 switch (IIK) {
5213 case IIK_Copy:
5214 case IIK_Move:
5215 return true;
5216
5217 case IIK_Default:
5218 case IIK_Inherit:
5219 return false;
5220 }
5221
5222 llvm_unreachable("Invalid ImplicitInitializerKind!");
5223 }
5224
5225 bool addFieldInitializer(CXXCtorInitializer *Init) {
5226 AllToInit.push_back(Init);
5227
5228 // Check whether this initializer makes the field "used".
5229 if (Init->getInit()->HasSideEffects(S.Context))
5230 S.UnusedPrivateFields.remove(Init->getAnyMember());
5231
5232 return false;
5233 }
5234
5235 bool isInactiveUnionMember(FieldDecl *Field) {
5236 RecordDecl *Record = Field->getParent();
5237 if (!Record->isUnion())
5238 return false;
5239
5240 if (FieldDecl *Active =
5241 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5242 return Active != Field->getCanonicalDecl();
5243
5244 // In an implicit copy or move constructor, ignore any in-class initializer.
5245 if (isImplicitCopyOrMove())
5246 return true;
5247
5248 // If there's no explicit initialization, the field is active only if it
5249 // has an in-class initializer...
5250 if (Field->hasInClassInitializer())
5251 return false;
5252 // ... or it's an anonymous struct or union whose class has an in-class
5253 // initializer.
5254 if (!Field->isAnonymousStructOrUnion())
5255 return true;
5256 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5257 return !FieldRD->hasInClassInitializer();
5258 }
5259
5260 /// Determine whether the given field is, or is within, a union member
5261 /// that is inactive (because there was an initializer given for a different
5262 /// member of the union, or because the union was not initialized at all).
5263 bool isWithinInactiveUnionMember(FieldDecl *Field,
5264 IndirectFieldDecl *Indirect) {
5265 if (!Indirect)
5266 return isInactiveUnionMember(Field);
5267
5268 for (auto *C : Indirect->chain()) {
5269 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5270 if (Field && isInactiveUnionMember(Field))
5271 return true;
5272 }
5273 return false;
5274 }
5275};
5276}
5277
5278/// Determine whether the given type is an incomplete or zero-lenfgth
5279/// array type.
5281 if (T->isIncompleteArrayType())
5282 return true;
5283
5284 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5285 if (!ArrayT->getSize())
5286 return true;
5287
5288 T = ArrayT->getElementType();
5289 }
5290
5291 return false;
5292}
5293
5294static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5295 FieldDecl *Field,
5296 IndirectFieldDecl *Indirect = nullptr) {
5297 if (Field->isInvalidDecl())
5298 return false;
5299
5300 // Overwhelmingly common case: we have a direct initializer for this field.
5302 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5303 return Info.addFieldInitializer(Init);
5304
5305 // C++11 [class.base.init]p8:
5306 // if the entity is a non-static data member that has a
5307 // brace-or-equal-initializer and either
5308 // -- the constructor's class is a union and no other variant member of that
5309 // union is designated by a mem-initializer-id or
5310 // -- the constructor's class is not a union, and, if the entity is a member
5311 // of an anonymous union, no other member of that union is designated by
5312 // a mem-initializer-id,
5313 // the entity is initialized as specified in [dcl.init].
5314 //
5315 // We also apply the same rules to handle anonymous structs within anonymous
5316 // unions.
5317 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5318 return false;
5319
5320 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5321 ExprResult DIE =
5322 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5323 if (DIE.isInvalid())
5324 return true;
5325
5326 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5327 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5328
5330 if (Indirect)
5331 Init = new (SemaRef.Context)
5332 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5333 SourceLocation(), DIE.get(), SourceLocation());
5334 else
5335 Init = new (SemaRef.Context)
5336 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5337 SourceLocation(), DIE.get(), SourceLocation());
5338 return Info.addFieldInitializer(Init);
5339 }
5340
5341 // Don't initialize incomplete or zero-length arrays.
5342 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5343 return false;
5344
5345 // Don't try to build an implicit initializer if there were semantic
5346 // errors in any of the initializers (and therefore we might be
5347 // missing some that the user actually wrote).
5348 if (Info.AnyErrorsInInits)
5349 return false;
5350
5351 CXXCtorInitializer *Init = nullptr;
5352 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5353 Indirect, Init))
5354 return true;
5355
5356 if (!Init)
5357 return false;
5358
5359 return Info.addFieldInitializer(Init);
5360}
5361
5362bool
5365 assert(Initializer->isDelegatingInitializer());
5366 Constructor->setNumCtorInitializers(1);
5367 CXXCtorInitializer **initializer =
5368 new (Context) CXXCtorInitializer*[1];
5369 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5370 Constructor->setCtorInitializers(initializer);
5371
5372 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5373 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5374 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5375 }
5376
5377 DelegatingCtorDecls.push_back(Constructor);
5378
5379 DiagnoseUninitializedFields(*this, Constructor);
5380
5381 return false;
5382}
5383
5384bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5385 ArrayRef<CXXCtorInitializer *> Initializers) {
5386 if (Constructor->isDependentContext()) {
5387 // Just store the initializers as written, they will be checked during
5388 // instantiation.
5389 if (!Initializers.empty()) {
5390 Constructor->setNumCtorInitializers(Initializers.size());
5391 CXXCtorInitializer **baseOrMemberInitializers =
5392 new (Context) CXXCtorInitializer*[Initializers.size()];
5393 memcpy(baseOrMemberInitializers, Initializers.data(),
5394 Initializers.size() * sizeof(CXXCtorInitializer*));
5395 Constructor->setCtorInitializers(baseOrMemberInitializers);
5396 }
5397
5398 // Let template instantiation know whether we had errors.
5399 if (AnyErrors)
5400 Constructor->setInvalidDecl();
5401
5402 return false;
5403 }
5404
5405 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5406
5407 // We need to build the initializer AST according to order of construction
5408 // and not what user specified in the Initializers list.
5409 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5410 if (!ClassDecl)
5411 return true;
5412
5413 bool HadError = false;
5414
5415 for (unsigned i = 0; i < Initializers.size(); i++) {
5416 CXXCtorInitializer *Member = Initializers[i];
5417
5418 if (Member->isBaseInitializer())
5419 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5420 else {
5421 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5422
5423 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5424 for (auto *C : F->chain()) {
5425 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5426 if (FD && FD->getParent()->isUnion())
5427 Info.ActiveUnionMember.insert(std::make_pair(
5429 }
5430 } else if (FieldDecl *FD = Member->getMember()) {
5431 if (FD->getParent()->isUnion())
5432 Info.ActiveUnionMember.insert(std::make_pair(
5434 }
5435 }
5436 }
5437
5438 // Keep track of the direct virtual bases.
5440 for (auto &I : ClassDecl->bases()) {
5441 if (I.isVirtual())
5442 DirectVBases.insert(&I);
5443 }
5444
5445 // Push virtual bases before others.
5446 for (auto &VBase : ClassDecl->vbases()) {
5448 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5449 // [class.base.init]p7, per DR257:
5450 // A mem-initializer where the mem-initializer-id names a virtual base
5451 // class is ignored during execution of a constructor of any class that
5452 // is not the most derived class.
5453 if (ClassDecl->isAbstract()) {
5454 // FIXME: Provide a fixit to remove the base specifier. This requires
5455 // tracking the location of the associated comma for a base specifier.
5456 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5457 << VBase.getType() << ClassDecl;
5458 DiagnoseAbstractType(ClassDecl);
5459 }
5460
5461 Info.AllToInit.push_back(Value);
5462 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5463 // [class.base.init]p8, per DR257:
5464 // If a given [...] base class is not named by a mem-initializer-id
5465 // [...] and the entity is not a virtual base class of an abstract
5466 // class, then [...] the entity is default-initialized.
5467 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5468 CXXCtorInitializer *CXXBaseInit;
5469 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5470 &VBase, IsInheritedVirtualBase,
5471 CXXBaseInit)) {
5472 HadError = true;
5473 continue;
5474 }
5475
5476 Info.AllToInit.push_back(CXXBaseInit);
5477 }
5478 }
5479
5480 // Non-virtual bases.
5481 for (auto &Base : ClassDecl->bases()) {
5482 // Virtuals are in the virtual base list and already constructed.
5483 if (Base.isVirtual())
5484 continue;
5485
5487 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5488 Info.AllToInit.push_back(Value);
5489 } else if (!AnyErrors) {
5490 CXXCtorInitializer *CXXBaseInit;
5491 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5492 &Base, /*IsInheritedVirtualBase=*/false,
5493 CXXBaseInit)) {
5494 HadError = true;
5495 continue;
5496 }
5497
5498 Info.AllToInit.push_back(CXXBaseInit);
5499 }
5500 }
5501
5502 // Fields.
5503 for (auto *Mem : ClassDecl->decls()) {
5504 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5505 // C++ [class.bit]p2:
5506 // A declaration for a bit-field that omits the identifier declares an
5507 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5508 // initialized.
5509 if (F->isUnnamedBitfield())
5510 continue;
5511
5512 // If we're not generating the implicit copy/move constructor, then we'll
5513 // handle anonymous struct/union fields based on their individual
5514 // indirect fields.
5515 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5516 continue;
5517
5518 if (CollectFieldInitializer(*this, Info, F))
5519 HadError = true;
5520 continue;
5521 }
5522
5523 // Beyond this point, we only consider default initialization.
5524 if (Info.isImplicitCopyOrMove())
5525 continue;
5526
5527 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5528 if (F->getType()->isIncompleteArrayType()) {
5529 assert(ClassDecl->hasFlexibleArrayMember() &&
5530 "Incomplete array type is not valid");
5531 continue;
5532 }
5533
5534 // Initialize each field of an anonymous struct individually.
5535 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5536 HadError = true;
5537
5538 continue;
5539 }
5540 }
5541
5542 unsigned NumInitializers = Info.AllToInit.size();
5543 if (NumInitializers > 0) {
5544 Constructor->setNumCtorInitializers(NumInitializers);
5545 CXXCtorInitializer **baseOrMemberInitializers =
5546 new (Context) CXXCtorInitializer*[NumInitializers];
5547 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5548 NumInitializers * sizeof(CXXCtorInitializer*));
5549 Constructor->setCtorInitializers(baseOrMemberInitializers);
5550
5551 // Constructors implicitly reference the base and member
5552 // destructors.
5553 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5554 Constructor->getParent());
5555 }
5556
5557 return HadError;
5558}
5559
5561 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5562 const RecordDecl *RD = RT->getDecl();
5563 if (RD->isAnonymousStructOrUnion()) {
5564 for (auto *Field : RD->fields())
5565 PopulateKeysForFields(Field, IdealInits);
5566 return;
5567 }
5568 }
5569 IdealInits.push_back(Field->getCanonicalDecl());
5570}
5571
5572static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5573 return Context.getCanonicalType(BaseType).getTypePtr();
5574}
5575
5578 if (!Member->isAnyMemberInitializer())
5579 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5580
5581 return Member->getAnyMember()->getCanonicalDecl();
5582}
5583
5586 const CXXCtorInitializer *Current) {
5587 if (Previous->isAnyMemberInitializer())
5588 Diag << 0 << Previous->getAnyMember();
5589 else
5590 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5591
5592 if (Current->isAnyMemberInitializer())
5593 Diag << 0 << Current->getAnyMember();
5594 else
5595 Diag << 1 << Current->getTypeSourceInfo()->getType();
5596}
5597
5599 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5601 if (Constructor->getDeclContext()->isDependentContext())
5602 return;
5603
5604 // Don't check initializers order unless the warning is enabled at the
5605 // location of at least one initializer.
5606 bool ShouldCheckOrder = false;
5607 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5608 CXXCtorInitializer *Init = Inits[InitIndex];
5609 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5610 Init->getSourceLocation())) {
5611 ShouldCheckOrder = true;
5612 break;
5613 }
5614 }
5615 if (!ShouldCheckOrder)
5616 return;
5617
5618 // Build the list of bases and members in the order that they'll
5619 // actually be initialized. The explicit initializers should be in
5620 // this same order but may be missing things.
5621 SmallVector<const void*, 32> IdealInitKeys;
5622
5623 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5624
5625 // 1. Virtual bases.
5626 for (const auto &VBase : ClassDecl->vbases())
5627 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5628
5629 // 2. Non-virtual bases.
5630 for (const auto &Base : ClassDecl->bases()) {
5631 if (Base.isVirtual())
5632 continue;
5633 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5634 }
5635
5636 // 3. Direct fields.
5637 for (auto *Field : ClassDecl->fields()) {
5638 if (Field->isUnnamedBitfield())
5639 continue;
5640
5641 PopulateKeysForFields(Field, IdealInitKeys);
5642 }
5643
5644 unsigned NumIdealInits = IdealInitKeys.size();
5645 unsigned IdealIndex = 0;
5646
5647 // Track initializers that are in an incorrect order for either a warning or
5648 // note if multiple ones occur.
5649 SmallVector<unsigned> WarnIndexes;
5650 // Correlates the index of an initializer in the init-list to the index of
5651 // the field/base in the class.
5652 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5653
5654 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5655 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5656
5657 // Scan forward to try to find this initializer in the idealized
5658 // initializers list.
5659 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5660 if (InitKey == IdealInitKeys[IdealIndex])
5661 break;
5662
5663 // If we didn't find this initializer, it must be because we
5664 // scanned past it on a previous iteration. That can only
5665 // happen if we're out of order; emit a warning.
5666 if (IdealIndex == NumIdealInits && InitIndex) {
5667 WarnIndexes.push_back(InitIndex);
5668
5669 // Move back to the initializer's location in the ideal list.
5670 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5671 if (InitKey == IdealInitKeys[IdealIndex])
5672 break;
5673
5674 assert(IdealIndex < NumIdealInits &&
5675 "initializer not found in initializer list");
5676 }
5677 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5678 }
5679
5680 if (WarnIndexes.empty())
5681 return;
5682
5683 // Sort based on the ideal order, first in the pair.
5684 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5685
5686 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5687 // emit the diagnostic before we can try adding notes.
5688 {
5690 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5691 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5692 : diag::warn_some_initializers_out_of_order);
5693
5694 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5695 if (CorrelatedInitOrder[I].second == I)
5696 continue;
5697 // Ideally we would be using InsertFromRange here, but clang doesn't
5698 // appear to handle InsertFromRange correctly when the source range is
5699 // modified by another fix-it.
5701 Inits[I]->getSourceRange(),
5704 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5705 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5706 }
5707
5708 // If there is only 1 item out of order, the warning expects the name and
5709 // type of each being added to it.
5710 if (WarnIndexes.size() == 1) {
5711 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5712 Inits[WarnIndexes.front()]);
5713 return;
5714 }
5715 }
5716 // More than 1 item to warn, create notes letting the user know which ones
5717 // are bad.
5718 for (unsigned WarnIndex : WarnIndexes) {
5719 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5720 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5721 diag::note_initializer_out_of_order);
5722 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5723 D << PrevInit->getSourceRange();
5724 }
5725}
5726
5727namespace {
5728bool CheckRedundantInit(Sema &S,
5730 CXXCtorInitializer *&PrevInit) {
5731 if (!PrevInit) {
5732 PrevInit = Init;
5733 return false;
5734 }
5735
5736 if (FieldDecl *Field = Init->getAnyMember())
5737 S.Diag(Init->getSourceLocation(),
5738 diag::err_multiple_mem_initialization)
5739 << Field->getDeclName()
5740 << Init->getSourceRange();
5741 else {
5742 const Type *BaseClass = Init->getBaseClass();
5743 assert(BaseClass && "neither field nor base");
5744 S.Diag(Init->getSourceLocation(),
5745 diag::err_multiple_base_initialization)
5746 << QualType(BaseClass, 0)
5747 << Init->getSourceRange();
5748 }
5749 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5750 << 0 << PrevInit->getSourceRange();
5751
5752 return true;
5753}
5754
5755typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5756typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5757
5758bool CheckRedundantUnionInit(Sema &S,
5760 RedundantUnionMap &Unions) {
5761 FieldDecl *Field = Init->getAnyMember();
5762 RecordDecl *Parent = Field->getParent();
5763 NamedDecl *Child = Field;
5764
5765 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5766 if (Parent->isUnion()) {
5767 UnionEntry &En = Unions[Parent];
5768 if (En.first && En.first != Child) {
5769 S.Diag(Init->getSourceLocation(),
5770 diag::err_multiple_mem_union_initialization)
5771 << Field->getDeclName()
5772 << Init->getSourceRange();
5773 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5774 << 0 << En.second->getSourceRange();
5775 return true;
5776 }
5777 if (!En.first) {
5778 En.first = Child;
5779 En.second = Init;
5780 }
5781 if (!Parent->isAnonymousStructOrUnion())
5782 return false;
5783 }
5784
5785 Child = Parent;
5786 Parent = cast<RecordDecl>(Parent->getDeclContext());
5787 }
5788
5789 return false;
5790}
5791} // namespace
5792
5793/// ActOnMemInitializers - Handle the member initializers for a constructor.
5794void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5795 SourceLocation ColonLoc,
5797 bool AnyErrors) {
5798 if (!ConstructorDecl)
5799 return;
5800
5801 AdjustDeclIfTemplate(ConstructorDecl);
5802
5803 CXXConstructorDecl *Constructor
5804 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5805
5806 if (!Constructor) {
5807 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5808 return;
5809 }
5810
5811 // Mapping for the duplicate initializers check.
5812 // For member initializers, this is keyed with a FieldDecl*.
5813 // For base initializers, this is keyed with a Type*.
5814 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5815
5816 // Mapping for the inconsistent anonymous-union initializers check.
5817 RedundantUnionMap MemberUnions;
5818
5819 bool HadError = false;
5820 for (unsigned i = 0; i < MemInits.size(); i++) {
5821 CXXCtorInitializer *Init = MemInits[i];
5822
5823 // Set the source order index.
5824 Init->setSourceOrder(i);
5825
5826 if (Init->isAnyMemberInitializer()) {
5827 const void *Key = GetKeyForMember(Context, Init);
5828 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5829 CheckRedundantUnionInit(*this, Init, MemberUnions))
5830 HadError = true;
5831 } else if (Init->isBaseInitializer()) {
5832 const void *Key = GetKeyForMember(Context, Init);
5833 if (CheckRedundantInit(*this, Init, Members[Key]))
5834 HadError = true;
5835 } else {
5836 assert(Init->isDelegatingInitializer());
5837 // This must be the only initializer
5838 if (MemInits.size() != 1) {
5839 Diag(Init->getSourceLocation(),
5840 diag::err_delegating_initializer_alone)
5841 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5842 // We will treat this as being the only initializer.
5843 }
5844 SetDelegatingInitializer(Constructor, MemInits[i]);
5845 // Return immediately as the initializer is set.
5846 return;
5847 }
5848 }
5849
5850 if (HadError)
5851 return;
5852
5853 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5854
5855 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5856
5857 DiagnoseUninitializedFields(*this, Constructor);
5858}
5859
5860void
5862 CXXRecordDecl *ClassDecl) {
5863 // Ignore dependent contexts. Also ignore unions, since their members never
5864 // have destructors implicitly called.
5865 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5866 return;
5867
5868 // FIXME: all the access-control diagnostics are positioned on the
5869 // field/base declaration. That's probably good; that said, the
5870 // user might reasonably want to know why the destructor is being
5871 // emitted, and we currently don't say.
5872
5873 // Non-static data members.
5874 for (auto *Field : ClassDecl->fields()) {
5875 if (Field->isInvalidDecl())
5876 continue;
5877
5878 // Don't destroy incomplete or zero-length arrays.
5879 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5880 continue;
5881
5882 QualType FieldType = Context.getBaseElementType(Field->getType());
5883
5884 const RecordType* RT = FieldType->getAs<RecordType>();
5885 if (!RT)
5886 continue;
5887
5888 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5889 if (FieldClassDecl->isInvalidDecl())
5890 continue;
5891 if (FieldClassDecl->hasIrrelevantDestructor())
5892 continue;
5893 // The destructor for an implicit anonymous union member is never invoked.
5894 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5895 continue;
5896
5897 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5898 // Dtor might still be missing, e.g because it's invalid.
5899 if (!Dtor)
5900 continue;
5901 CheckDestructorAccess(Field->getLocation(), Dtor,
5902 PDiag(diag::err_access_dtor_field)
5903 << Field->getDeclName()
5904 << FieldType);
5905
5906 MarkFunctionReferenced(Location, Dtor);
5907 DiagnoseUseOfDecl(Dtor, Location);
5908 }
5909
5910 // We only potentially invoke the destructors of potentially constructed
5911 // subobjects.
5912 bool VisitVirtualBases = !ClassDecl->isAbstract();
5913
5914 // If the destructor exists and has already been marked used in the MS ABI,
5915 // then virtual base destructors have already been checked and marked used.
5916 // Skip checking them again to avoid duplicate diagnostics.
5918 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5919 if (Dtor && Dtor->isUsed())
5920 VisitVirtualBases = false;
5921 }
5922
5924
5925 // Bases.
5926 for (const auto &Base : ClassDecl->bases()) {
5927 const RecordType *RT = Base.getType()->getAs<RecordType>();
5928 if (!RT)
5929 continue;
5930
5931 // Remember direct virtual bases.
5932 if (Base.isVirtual()) {
5933 if (!VisitVirtualBases)
5934 continue;
5935 DirectVirtualBases.insert(RT);
5936 }
5937
5938 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5939 // If our base class is invalid, we probably can't get its dtor anyway.
5940 if (BaseClassDecl->isInvalidDecl())
5941 continue;
5942 if (BaseClassDecl->hasIrrelevantDestructor())
5943 continue;
5944
5945 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5946 // Dtor might still be missing, e.g because it's invalid.
5947 if (!Dtor)
5948 continue;
5949
5950 // FIXME: caret should be on the start of the class name
5951 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5952 PDiag(diag::err_access_dtor_base)
5953 << Base.getType() << Base.getSourceRange(),
5954 Context.getTypeDeclType(ClassDecl));
5955
5956 MarkFunctionReferenced(Location, Dtor);
5957 DiagnoseUseOfDecl(Dtor, Location);
5958 }
5959
5960 if (VisitVirtualBases)
5961 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5962 &DirectVirtualBases);
5963}
5964
5966 SourceLocation Location, CXXRecordDecl *ClassDecl,
5967 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5968 // Virtual bases.
5969 for (const auto &VBase : ClassDecl->vbases()) {
5970 // Bases are always records in a well-formed non-dependent class.
5971 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5972
5973 // Ignore already visited direct virtual bases.
5974 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5975 continue;
5976
5977 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5978 // If our base class is invalid, we probably can't get its dtor anyway.
5979 if (BaseClassDecl->isInvalidDecl())
5980 continue;
5981 if (BaseClassDecl->hasIrrelevantDestructor())
5982 continue;
5983
5984 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5985 // Dtor might still be missing, e.g because it's invalid.
5986 if (!Dtor)
5987 continue;
5989 ClassDecl->getLocation(), Dtor,
5990 PDiag(diag::err_access_dtor_vbase)
5991 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5992 Context.getTypeDeclType(ClassDecl)) ==
5993 AR_accessible) {
5995 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5996 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5997 SourceRange(), DeclarationName(), nullptr);
5998 }
5999
6000 MarkFunctionReferenced(Location, Dtor);
6001 DiagnoseUseOfDecl(Dtor, Location);
6002 }
6003}
6004
6006 if (!CDtorDecl)
6007 return;
6008
6009 if (CXXConstructorDecl *Constructor
6010 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6011 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6012 !ClassDecl || ClassDecl->isInvalidDecl()) {
6013 return;
6014 }
6015 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6016 DiagnoseUninitializedFields(*this, Constructor);
6017 }
6018}
6019
6021 if (!getLangOpts().CPlusPlus)
6022 return false;
6023
6024 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6025 if (!RD)
6026 return false;
6027
6028 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6029 // class template specialization here, but doing so breaks a lot of code.
6030
6031 // We can't answer whether something is abstract until it has a
6032 // definition. If it's currently being defined, we'll walk back
6033 // over all the declarations when we have a full definition.
6034 const CXXRecordDecl *Def = RD->getDefinition();
6035 if (!Def || Def->isBeingDefined())
6036 return false;
6037
6038 return RD->isAbstract();
6039}
6040
6042 TypeDiagnoser &Diagnoser) {
6043 if (!isAbstractType(Loc, T))
6044 return false;
6045
6047 Diagnoser.diagnose(*this, Loc, T);
6049 return true;
6050}
6051
6053 // Check if we've already emitted the list of pure virtual functions
6054 // for this class.
6056 return;
6057
6058 // If the diagnostic is suppressed, don't emit the notes. We're only
6059 // going to emit them once, so try to attach them to a diagnostic we're
6060 // actually going to show.
6062 return;
6063
6064 CXXFinalOverriderMap FinalOverriders;
6065 RD->getFinalOverriders(FinalOverriders);
6066
6067 // Keep a set of seen pure methods so we won't diagnose the same method
6068 // more than once.
6070
6071 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6072 MEnd = FinalOverriders.end();
6073 M != MEnd;
6074 ++M) {
6075 for (OverridingMethods::iterator SO = M->second.begin(),
6076 SOEnd = M->second.end();
6077 SO != SOEnd; ++SO) {
6078 // C++ [class.abstract]p4:
6079 // A class is abstract if it contains or inherits at least one
6080 // pure virtual function for which the final overrider is pure
6081 // virtual.
6082
6083 //
6084 if (SO->second.size() != 1)
6085 continue;
6086
6087 if (!SO->second.front().Method->isPureVirtual())
6088 continue;
6089
6090 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6091 continue;
6092
6093 Diag(SO->second.front().Method->getLocation(),
6094 diag::note_pure_virtual_function)
6095 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6096 }
6097 }
6098
6101 PureVirtualClassDiagSet->insert(RD);
6102}
6103
6104namespace {
6105struct AbstractUsageInfo {
6106 Sema &S;
6108 CanQualType AbstractType;
6109 bool Invalid;
6110
6111 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6112 : S(S), Record(Record),
6113 AbstractType(S.Context.getCanonicalType(
6114 S.Context.getTypeDeclType(Record))),
6115 Invalid(false) {}
6116
6117 void DiagnoseAbstractType() {
6118 if (Invalid) return;
6120 Invalid = true;
6121 }
6122
6123 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6124};
6125
6126struct CheckAbstractUsage {
6127 AbstractUsageInfo &Info;
6128 const NamedDecl *Ctx;
6129
6130 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6131 : Info(Info), Ctx(Ctx) {}
6132
6133 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6134 switch (TL.getTypeLocClass()) {
6135#define ABSTRACT_TYPELOC(CLASS, PARENT)
6136#define TYPELOC(CLASS, PARENT) \
6137 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6138#include "clang/AST/TypeLocNodes.def"
6139 }
6140 }
6141
6142 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6144 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6145 if (!TL.getParam(I))
6146 continue;
6147
6149 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6150 }
6151 }
6152
6153 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6155 }
6156
6158 // Visit the type parameters from a permissive context.
6159 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6160 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6162 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6163 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6164 // TODO: other template argument types?
6165 }
6166 }
6167
6168 // Visit pointee types from a permissive context.
6169#define CheckPolymorphic(Type) \
6170 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6171 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6172 }
6178
6179 /// Handle all the types we haven't given a more specific
6180 /// implementation for above.
6181 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6182 // Every other kind of type that we haven't called out already
6183 // that has an inner type is either (1) sugar or (2) contains that
6184 // inner type in some way as a subobject.
6185 if (TypeLoc Next = TL.getNextTypeLoc())
6186 return Visit(Next, Sel);
6187
6188 // If there's no inner type and we're in a permissive context,
6189 // don't diagnose.
6190 if (Sel == Sema::AbstractNone) return;
6191
6192 // Check whether the type matches the abstract type.
6193 QualType T = TL.getType();
6194 if (T->isArrayType()) {
6196 T = Info.S.Context.getBaseElementType(T);
6197 }
6199 if (CT != Info.AbstractType) return;
6200
6201 // It matched; do some magic.
6202 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6203 if (Sel == Sema::AbstractArrayType) {
6204 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6205 << T << TL.getSourceRange();
6206 } else {
6207 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6208 << Sel << T << TL.getSourceRange();
6209 }
6210 Info.DiagnoseAbstractType();
6211 }
6212};
6213
6214void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6216 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6217}
6218
6219}
6220
6221/// Check for invalid uses of an abstract type in a function declaration.
6222static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6223 FunctionDecl *FD) {
6224 // Only definitions are required to refer to complete and
6225 // non-abstract types.
6227 return;
6228
6229 // For safety's sake, just ignore it if we don't have type source
6230 // information. This should never happen for non-implicit methods,
6231 // but...
6232 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6233 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6234}
6235
6236/// Check for invalid uses of an abstract type in a variable0 declaration.
6237static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6238 VarDecl *VD) {
6239 // No need to do the check on definitions, which require that
6240 // the type is complete.
6242 return;
6243
6244 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6246}
6247
6248/// Check for invalid uses of an abstract type within a class definition.
6249static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6250 CXXRecordDecl *RD) {
6251 for (auto *D : RD->decls()) {
6252 if (D->isImplicit()) continue;
6253
6254 // Step through friends to the befriended declaration.
6255 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6256 D = FD->getFriendDecl();
6257 if (!D) continue;
6258 }
6259
6260 // Functions and function templates.
6261 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6262 CheckAbstractClassUsage(Info, FD);
6263 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6264 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6265
6266 // Fields and static variables.
6267 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6268 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6269 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6270 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6271 CheckAbstractClassUsage(Info, VD);
6272 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6273 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6274
6275 // Nested classes and class templates.
6276 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6277 CheckAbstractClassUsage(Info, RD);
6278 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6279 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6280 }
6281 }
6282}
6283
6285 Attr *ClassAttr = getDLLAttr(Class);
6286 if (!ClassAttr)
6287 return;
6288
6289 assert(ClassAttr->getKind() == attr::DLLExport);
6290
6291 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6292
6294 // Don't go any further if this is just an explicit instantiation
6295 // declaration.
6296 return;
6297
6298 // Add a context note to explain how we got to any diagnostics produced below.
6299 struct MarkingClassDllexported {
6300 Sema &S;
6301 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6302 SourceLocation AttrLoc)
6303 : S(S) {
6306 Ctx.PointOfInstantiation = AttrLoc;
6307 Ctx.Entity = Class;
6309 }
6310 ~MarkingClassDllexported() {
6312 }
6313 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6314
6315 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6316 S.MarkVTableUsed(Class->getLocation(), Class, true);
6317
6318 for (Decl *Member : Class->decls()) {
6319 // Skip members that were not marked exported.
6320 if (!Member->hasAttr<DLLExportAttr>())
6321 continue;
6322
6323 // Defined static variables that are members of an exported base
6324 // class must be marked export too.
6325 auto *VD = dyn_cast<VarDecl>(Member);
6326 if (VD && VD->getStorageClass() == SC_Static &&
6328 S.MarkVariableReferenced(VD->getLocation(), VD);
6329
6330 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6331 if (!MD)
6332 continue;
6333
6334 if (MD->isUserProvided()) {
6335 // Instantiate non-default class member functions ...
6336
6337 // .. except for certain kinds of template specializations.
6338 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6339 continue;
6340
6341 // If this is an MS ABI dllexport default constructor, instantiate any
6342 // default arguments.
6344 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6345 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6347 }
6348 }
6349
6350 S.MarkFunctionReferenced(Class->getLocation(), MD);
6351
6352 // The function will be passed to the consumer when its definition is
6353 // encountered.
6354 } else if (MD->isExplicitlyDefaulted()) {
6355 // Synthesize and instantiate explicitly defaulted methods.
6356 S.MarkFunctionReferenced(Class->getLocation(), MD);
6357
6359 // Except for explicit instantiation defs, we will not see the
6360 // definition again later, so pass it to the consumer now.
6362 }
6363 } else if (!MD->isTrivial() ||
6364 MD->isCopyAssignmentOperator() ||
6365 MD->isMoveAssignmentOperator()) {
6366 // Synthesize and instantiate non-trivial implicit methods, and the copy
6367 // and move assignment operators. The latter are exported even if they
6368 // are trivial, because the address of an operator can be taken and
6369 // should compare equal across libraries.
6370 S.MarkFunctionReferenced(Class->getLocation(), MD);
6371
6372 // There is no later point when we will see the definition of this
6373 // function, so pass it to the consumer now.
6375 }
6376 }
6377}
6378
6381 // Only the MS ABI has default constructor closures, so we don't need to do
6382 // this semantic checking anywhere else.
6384 return;
6385
6386 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6387 for (Decl *Member : Class->decls()) {
6388 // Look for exported default constructors.
6389 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6390 if (!CD || !CD->isDefaultConstructor())
6391 continue;
6392 auto *Attr = CD->getAttr<DLLExportAttr>();
6393 if (!Attr)
6394 continue;
6395
6396 // If the class is non-dependent, mark the default arguments as ODR-used so
6397 // that we can properly codegen the constructor closure.
6398 if (!Class->isDependentContext()) {
6399 for (ParmVarDecl *PD : CD->parameters()) {
6400 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6402 }
6403 }
6404
6405 if (LastExportedDefaultCtor) {
6406 S.Diag(LastExportedDefaultCtor->getLocation(),
6407 diag::err_attribute_dll_ambiguous_default_ctor)
6408 << Class;
6409 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6410 << CD->getDeclName();
6411 return;
6412 }
6413 LastExportedDefaultCtor = CD;
6414 }
6415}
6416
6419 bool ErrorReported = false;
6420 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6421 ClassTemplateDecl *TD) {
6422 if (ErrorReported)
6423 return;
6424 S.Diag(TD->getLocation(),
6425 diag::err_cuda_device_builtin_surftex_cls_template)
6426 << /*surface*/ 0 << TD;
6427 ErrorReported = true;
6428 };
6429
6430 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6431 if (!TD) {
6432 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6433 if (!SD) {
6434 S.Diag(Class->getLocation(),
6435 diag::err_cuda_device_builtin_surftex_ref_decl)
6436 << /*surface*/ 0 << Class;
6437 S.Diag(Class->getLocation(),
6438 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6439 << Class;
6440 return;
6441 }
6442 TD = SD->getSpecializedTemplate();
6443 }
6444
6446 unsigned N = Params->size();
6447
6448 if (N != 2) {
6449 reportIllegalClassTemplate(S, TD);
6450 S.Diag(TD->getLocation(),
6451 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6452 << TD << 2;
6453 }
6454 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6455 reportIllegalClassTemplate(S, TD);
6456 S.Diag(TD->getLocation(),
6457 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6458 << TD << /*1st*/ 0 << /*type*/ 0;
6459 }
6460 if (N > 1) {
6461 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6462 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6463 reportIllegalClassTemplate(S, TD);
6464 S.Diag(TD->getLocation(),
6465 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6466 << TD << /*2nd*/ 1 << /*integer*/ 1;
6467 }
6468 }
6469}
6470
6473 bool ErrorReported = false;
6474 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6475 ClassTemplateDecl *TD) {
6476 if (ErrorReported)
6477 return;
6478 S.Diag(TD->getLocation(),
6479 diag::err_cuda_device_builtin_surftex_cls_template)
6480 << /*texture*/ 1 << TD;
6481 ErrorReported = true;
6482 };
6483
6484 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6485 if (!TD) {
6486 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6487 if (!SD) {
6488 S.Diag(Class->getLocation(),
6489 diag::err_cuda_device_builtin_surftex_ref_decl)
6490 << /*texture*/ 1 << Class;
6491 S.Diag(Class->getLocation(),
6492 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6493 << Class;
6494 return;
6495 }
6496 TD = SD->getSpecializedTemplate();
6497 }
6498
6500 unsigned N = Params->size();
6501
6502 if (N != 3) {
6503 reportIllegalClassTemplate(S, TD);
6504 S.Diag(TD->getLocation(),
6505 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6506 << TD << 3;
6507 }
6508 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6509 reportIllegalClassTemplate(S, TD);
6510 S.Diag(TD->getLocation(),
6511 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6512 << TD << /*1st*/ 0 << /*type*/ 0;
6513 }
6514 if (N > 1) {
6515 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6516 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6517 reportIllegalClassTemplate(S, TD);
6518 S.Diag(TD->getLocation(),
6519 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6520 << TD << /*2nd*/ 1 << /*integer*/ 1;
6521 }
6522 }
6523 if (N > 2) {
6524 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6525 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6526 reportIllegalClassTemplate(S, TD);
6527 S.Diag(TD->getLocation(),
6528 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6529 << TD << /*3rd*/ 2 << /*integer*/ 1;
6530 }
6531 }
6532}
6533
6535 // Mark any compiler-generated routines with the implicit code_seg attribute.
6536 for (auto *Method : Class->methods()) {
6537 if (Method->isUserProvided())
6538 continue;
6539 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6540 Method->addAttr(A);
6541 }
6542}
6543
6544/// Check class-level dllimport/dllexport attribute.
6546 Attr *ClassAttr = getDLLAttr(Class);
6547
6548 // MSVC inherits DLL attributes to partial class template specializations.
6549 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6550 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6551 if (Attr *TemplateAttr =
6552 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6553 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6554 A->setInherited(true);
6555 ClassAttr = A;
6556 }
6557 }
6558 }
6559
6560 if (!ClassAttr)
6561 return;
6562
6563 // MSVC allows imported or exported template classes that have UniqueExternal
6564 // linkage. This occurs when the template class has been instantiated with
6565 // a template parameter which itself has internal linkage.
6566 // We drop the attribute to avoid exporting or importing any members.
6568 Context.getTargetInfo().getTriple().isPS()) &&
6569 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6570 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6571 return;
6572 }
6573
6574 if (!Class->isExternallyVisible()) {
6575 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6576 << Class << ClassAttr;
6577 return;
6578 }
6579
6581 !ClassAttr->isInherited()) {
6582 // Diagnose dll attributes on members of class with dll attribute.
6583 for (Decl *Member : Class->decls()) {
6584 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6585 continue;
6586 InheritableAttr *MemberAttr = getDLLAttr(Member);
6587 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6588 continue;
6589
6590 Diag(MemberAttr->getLocation(),
6591 diag::err_attribute_dll_member_of_dll_class)
6592 << MemberAttr << ClassAttr;
6593 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6594 Member->setInvalidDecl();
6595 }
6596 }
6597
6598 if (Class->getDescribedClassTemplate())
6599 // Don't inherit dll attribute until the template is instantiated.
6600 return;
6601
6602 // The class is either imported or exported.
6603 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6604
6605 // Check if this was a dllimport attribute propagated from a derived class to
6606 // a base class template specialization. We don't apply these attributes to
6607 // static data members.
6608 const bool PropagatedImport =
6609 !ClassExported &&
6610 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6611
6612 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6613
6614 // Ignore explicit dllexport on explicit class template instantiation
6615 // declarations, except in MinGW mode.
6616 if (ClassExported && !ClassAttr->isInherited() &&
6618 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6619 Class->dropAttr<DLLExportAttr>();
6620 return;
6621 }
6622
6623 // Force declaration of implicit members so they can inherit the attribute.
6625
6626 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6627 // seem to be true in practice?
6628
6629 for (Decl *Member : Class->decls()) {
6630 VarDecl *VD = dyn_cast<VarDecl>(Member);
6631 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6632
6633 // Only methods and static fields inherit the attributes.
6634 if (!VD && !MD)
6635 continue;
6636
6637 if (MD) {
6638 // Don't process deleted methods.
6639 if (MD->isDeleted())
6640 continue;
6641
6642 if (MD->isInlined()) {
6643 // MinGW does not import or export inline methods. But do it for
6644 // template instantiations.
6648 continue;
6649
6650 // MSVC versions before 2015 don't export the move assignment operators
6651 // and move constructor, so don't attempt to import/export them if
6652 // we have a definition.
6653 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6654 if ((MD->isMoveAssignmentOperator() ||
6655 (Ctor && Ctor->isMoveConstructor())) &&
6656 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6657 continue;
6658
6659 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6660 // operator is exported anyway.
6661 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6662 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6663 continue;
6664 }
6665 }
6666
6667 // Don't apply dllimport attributes to static data members of class template
6668 // instantiations when the attribute is propagated from a derived class.
6669 if (VD && PropagatedImport)
6670 continue;
6671
6672 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6673 continue;
6674
6675 if (!getDLLAttr(Member)) {
6676 InheritableAttr *NewAttr = nullptr;
6677
6678 // Do not export/import inline function when -fno-dllexport-inlines is
6679 // passed. But add attribute for later local static var check.
6680 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6683 if (ClassExported) {
6684 NewAttr = ::new (getASTContext())
6685 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6686 } else {
6687 NewAttr = ::new (getASTContext())
6688 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6689 }
6690 } else {
6691 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6692 }
6693
6694 NewAttr->setInherited(true);
6695 Member->addAttr(NewAttr);
6696
6697 if (MD) {
6698 // Propagate DLLAttr to friend re-declarations of MD that have already
6699 // been constructed.
6700 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6701 FD = FD->getPreviousDecl()) {
6703 continue;
6704 assert(!getDLLAttr(FD) &&
6705 "friend re-decl should not already have a DLLAttr");
6706 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6707 NewAttr->setInherited(true);
6708 FD->addAttr(NewAttr);
6709 }
6710 }
6711 }
6712 }
6713
6714 if (ClassExported)
6715 DelayedDllExportClasses.push_back(Class);
6716}
6717
6718/// Perform propagation of DLL attributes from a derived class to a
6719/// templated base class for MS compatibility.
6721 CXXRecordDecl *Class, Attr *ClassAttr,
6722 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6723 if (getDLLAttr(
6724 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6725 // If the base class template has a DLL attribute, don't try to change it.
6726 return;
6727 }
6728
6729 auto TSK = BaseTemplateSpec->getSpecializationKind();
6730 if (!getDLLAttr(BaseTemplateSpec) &&
6732 TSK == TSK_ImplicitInstantiation)) {
6733 // The template hasn't been instantiated yet (or it has, but only as an
6734 // explicit instantiation declaration or implicit instantiation, which means
6735 // we haven't codegenned any members yet), so propagate the attribute.
6736 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6737 NewAttr->setInherited(true);
6738 BaseTemplateSpec->addAttr(NewAttr);
6739
6740 // If this was an import, mark that we propagated it from a derived class to
6741 // a base class template specialization.
6742 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6743 ImportAttr->setPropagatedToBaseTemplate();
6744
6745 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6746 // needs to be run again to work see the new attribute. Otherwise this will
6747 // get run whenever the template is instantiated.
6748 if (TSK != TSK_Undeclared)
6749 checkClassLevelDLLAttribute(BaseTemplateSpec);
6750
6751 return;
6752 }
6753
6754 if (getDLLAttr(BaseTemplateSpec)) {
6755 // The template has already been specialized or instantiated with an
6756 // attribute, explicitly or through propagation. We should not try to change
6757 // it.
6758 return;
6759 }
6760
6761 // The template was previously instantiated or explicitly specialized without
6762 // a dll attribute, It's too late for us to add an attribute, so warn that
6763 // this is unsupported.
6764 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6765 << BaseTemplateSpec->isExplicitSpecialization();
6766 Diag(ClassAttr->getLocation(), diag::note_attribute);
6767 if (BaseTemplateSpec->isExplicitSpecialization()) {
6768 Diag(BaseTemplateSpec->getLocation(),
6769 diag::note_template_class_explicit_specialization_was_here)
6770 << BaseTemplateSpec;
6771 } else {
6772 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6773 diag::note_template_class_instantiation_was_here)
6774 << BaseTemplateSpec;
6775 }
6776}
6777
6778/// Determine the kind of defaulting that would be done for a given function.
6779///
6780/// If the function is both a default constructor and a copy / move constructor
6781/// (due to having a default argument for the first parameter), this picks
6782/// CXXDefaultConstructor.
6783///
6784/// FIXME: Check that case is properly handled by all callers.
6787 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6788 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6789 if (Ctor->isDefaultConstructor())
6791
6792 if (Ctor->isCopyConstructor())
6794
6795 if (Ctor->isMoveConstructor())
6797 }
6798
6799 if (MD->isCopyAssignmentOperator())
6801
6802 if (MD->isMoveAssignmentOperator())
6804
6805 if (isa<CXXDestructorDecl>(FD))
6806 return Sema::CXXDestructor;
6807 }
6808
6809 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6810 case OO_EqualEqual:
6812
6813 case OO_ExclaimEqual:
6815
6816 case OO_Spaceship:
6817 // No point allowing this if <=> doesn't exist in the current language mode.
6818 if (!getLangOpts().CPlusPlus20)
6819 break;
6821
6822 case OO_Less:
6823 case OO_LessEqual:
6824 case OO_Greater:
6825 case OO_GreaterEqual:
6826 // No point allowing this if <=> doesn't exist in the current language mode.
6827 if (!getLangOpts().CPlusPlus20)
6828 break;
6830
6831 default:
6832 break;
6833 }
6834
6835 // Not defaultable.
6836 return DefaultedFunctionKind();
6837}
6838
6840 SourceLocation DefaultLoc) {
6842 if (DFK.isComparison())
6843 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6844
6845 switch (DFK.asSpecialMember()) {
6848 cast<CXXConstructorDecl>(FD));
6849 break;
6851 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6852 break;
6854 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6855 break;
6857 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6858 break;
6860 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6861 break;
6863 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6864 break;
6865 case Sema::CXXInvalid:
6866 llvm_unreachable("Invalid special member.");
6867 }
6868}
6869
6870/// Determine whether a type is permitted to be passed or returned in
6871/// registers, per C++ [class.temporary]p3.
6874 if (D->isDependentType() || D->isInvalidDecl())
6875 return false;
6876
6877 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6878 // The PS4 platform ABI follows the behavior of Clang 3.2.
6880 return !D->hasNonTrivialDestructorForCall() &&
6882
6883 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6884 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6885 bool DtorIsTrivialForCall = false;
6886
6887 // If a class has at least one eligible, trivial copy constructor, it
6888 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6889 //
6890 // Note: This permits classes with non-trivial copy or move ctors to be
6891 // passed in registers, so long as they *also* have a trivial copy ctor,
6892 // which is non-conforming.
6896 CopyCtorIsTrivial = true;
6898 CopyCtorIsTrivialForCall = true;
6899 }
6900 } else {
6901 for (const CXXConstructorDecl *CD : D->ctors()) {
6902 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6903 !CD->isIneligibleOrNotSelected()) {
6904 if (CD->isTrivial())
6905 CopyCtorIsTrivial = true;
6906 if (CD->isTrivialForCall())
6907 CopyCtorIsTrivialForCall = true;
6908 }
6909 }
6910 }
6911
6912 if (D->needsImplicitDestructor()) {
6913 if (!D->defaultedDestructorIsDeleted() &&
6915 DtorIsTrivialForCall = true;
6916 } else if (const auto *DD = D->getDestructor()) {
6917 if (!DD->isDeleted() && DD->isTrivialForCall())
6918 DtorIsTrivialForCall = true;
6919 }
6920
6921 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6922 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6923 return true;
6924
6925 // If a class has a destructor, we'd really like to pass it indirectly
6926 // because it allows us to elide copies. Unfortunately, MSVC makes that
6927 // impossible for small types, which it will pass in a single register or
6928 // stack slot. Most objects with dtors are large-ish, so handle that early.
6929 // We can't call out all large objects as being indirect because there are
6930 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6931 // how we pass large POD types.
6932
6933 // Note: This permits small classes with nontrivial destructors to be
6934 // passed in registers, which is non-conforming.
6935 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6936 uint64_t TypeSize = isAArch64 ? 128 : 64;
6937
6938 if (CopyCtorIsTrivial &&
6939 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6940 return true;
6941 return false;
6942 }
6943
6944 // Per C++ [class.temporary]p3, the relevant condition is:
6945 // each copy constructor, move constructor, and destructor of X is
6946 // either trivial or deleted, and X has at least one non-deleted copy
6947 // or move constructor
6948 bool HasNonDeletedCopyOrMove = false;
6949
6953 return false;
6954 HasNonDeletedCopyOrMove = true;
6955 }
6956
6957 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6960 return false;
6961 HasNonDeletedCopyOrMove = true;
6962 }
6963
6966 return false;
6967
6968 for (const CXXMethodDecl *MD : D->methods()) {
6969 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6970 continue;
6971
6972 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6973 if (CD && CD->isCopyOrMoveConstructor())
6974 HasNonDeletedCopyOrMove = true;
6975 else if (!isa<CXXDestructorDecl>(MD))
6976 continue;
6977
6978 if (!MD->isTrivialForCall())
6979 return false;
6980 }
6981
6982 return HasNonDeletedCopyOrMove;
6983}
6984
6985/// Report an error regarding overriding, along with any relevant
6986/// overridden methods.
6987///
6988/// \param DiagID the primary error to report.
6989/// \param MD the overriding method.
6990static bool
6991ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6992 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6993 bool IssuedDiagnostic = false;
6994 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6995 if (Report(O)) {
6996 if (!IssuedDiagnostic) {
6997 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6998 IssuedDiagnostic = true;
6999 }
7000 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7001 }
7002 }
7003 return IssuedDiagnostic;
7004}
7005
7006/// Perform semantic checks on a class definition that has been
7007/// completing, introducing implicitly-declared members, checking for
7008/// abstract types, etc.
7009///
7010/// \param S The scope in which the class was parsed. Null if we didn't just
7011/// parse a class definition.
7012/// \param Record The completed class.
7014 if (!Record)
7015 return;
7016
7017 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7018 AbstractUsageInfo Info(*this, Record);
7020 }
7021
7022 // If this is not an aggregate type and has no user-declared constructor,
7023 // complain about any non-static data members of reference or const scalar
7024 // type, since they will never get initializers.
7025 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7026 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7027 !Record->isLambda()) {
7028 bool Complained = false;
7029 for (const auto *F : Record->fields()) {
7030 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
7031 continue;
7032
7033 if (F->getType()->isReferenceType() ||
7034 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7035 if (!Complained) {
7036 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7037 << llvm::to_underlying(Record->getTagKind()) << Record;
7038 Complained = true;
7039 }
7040
7041 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7042 << F->getType()->isReferenceType()
7043 << F->getDeclName();
7044 }
7045 }
7046 }
7047
7048 if (Record->getIdentifier()) {
7049 // C++ [class.mem]p13:
7050 // If T is the name of a class, then each of the following shall have a
7051 // name different from T:
7052 // - every member of every anonymous union that is a member of class T.
7053 //
7054 // C++ [class.mem]p14:
7055 // In addition, if class T has a user-declared constructor (12.1), every
7056 // non-static data member of class T shall have a name different from T.
7057 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7058 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7059 ++I) {
7060 NamedDecl *D = (*I)->getUnderlyingDecl();
7061 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7062 Record->hasUserDeclaredConstructor()) ||
7063 isa<IndirectFieldDecl>(D)) {
7064 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7065 << D->getDeclName();
7066 break;
7067 }
7068 }
7069 }
7070
7071 // Warn if the class has virtual methods but non-virtual public destructor.
7072 if (Record->isPolymorphic() && !Record->isDependentType()) {
7073 CXXDestructorDecl *dtor = Record->getDestructor();
7074 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7075 !Record->hasAttr<FinalAttr>())
7076 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7077 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7078 }
7079
7080 if (Record->isAbstract()) {
7081 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7082 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7083 << FA->isSpelledAsSealed();
7085 }
7086 }
7087
7088 // Warn if the class has a final destructor but is not itself marked final.
7089 if (!Record->hasAttr<FinalAttr>()) {
7090 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7091 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7092 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7093 << FA->isSpelledAsSealed()
7095 getLocForEndOfToken(Record->getLocation()),
7096 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7097 Diag(Record->getLocation(),
7098 diag::note_final_dtor_non_final_class_silence)
7099 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7100 }
7101 }
7102 }
7103
7104 // See if trivial_abi has to be dropped.
7105 if (Record->hasAttr<TrivialABIAttr>())
7107
7108 // Set HasTrivialSpecialMemberForCall if the record has attribute
7109 // "trivial_abi".
7110 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7111
7112 if (HasTrivialABI)
7113 Record->setHasTrivialSpecialMemberForCall();
7114
7115 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7116 // We check these last because they can depend on the properties of the
7117 // primary comparison functions (==, <=>).
7118 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7119
7120 // Perform checks that can't be done until we know all the properties of a
7121 // member function (whether it's defaulted, deleted, virtual, overriding,
7122 // ...).
7123 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7124 // A static function cannot override anything.
7125 if (MD->getStorageClass() == SC_Static) {
7126 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7127 [](const CXXMethodDecl *) { return true; }))
7128 return;
7129 }
7130
7131 // A deleted function cannot override a non-deleted function and vice
7132 // versa.
7133 if (ReportOverrides(*this,
7134 MD->isDeleted() ? diag::err_deleted_override
7135 : diag::err_non_deleted_override,
7136 MD, [&](const CXXMethodDecl *V) {
7137 return MD->isDeleted() != V->isDeleted();
7138 })) {
7139 if (MD->isDefaulted() && MD->isDeleted())
7140 // Explain why this defaulted function was deleted.
7142 return;
7143 }
7144
7145 // A consteval function cannot override a non-consteval function and vice
7146 // versa.
7147 if (ReportOverrides(*this,
7148 MD->isConsteval() ? diag::err_consteval_override
7149 : diag::err_non_consteval_override,
7150 MD, [&](const CXXMethodDecl *V) {
7151 return MD->isConsteval() != V->isConsteval();
7152 })) {
7153 if (MD->isDefaulted() && MD->isDeleted())
7154 // Explain why this defaulted function was deleted.
7156 return;
7157 }
7158 };
7159
7160 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7161 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7162 return false;
7163
7167 DefaultedSecondaryComparisons.push_back(FD);
7168 return true;
7169 }
7170
7172 return false;
7173 };
7174
7175 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7176 // Check whether the explicitly-defaulted members are valid.
7177 bool Incomplete = CheckForDefaultedFunction(M);
7178
7179 // Skip the rest of the checks for a member of a dependent class.
7180 if (Record->isDependentType())
7181 return;
7182
7183 // For an explicitly defaulted or deleted special member, we defer
7184 // determining triviality until the class is complete. That time is now!
7186 if (!M->isImplicit() && !M->isUserProvided()) {
7187 if (CSM != CXXInvalid) {
7188 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7189 // Inform the class that we've finished declaring this member.
7190 Record->finishedDefaultedOrDeletedMember(M);
7191 M->setTrivialForCall(
7192 HasTrivialABI ||
7194 Record->setTrivialForCallFlags(M);
7195 }
7196 }
7197
7198 // Set triviality for the purpose of calls if this is a user-provided
7199 // copy/move constructor or destructor.
7200 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7201 CSM == CXXDestructor) && M->isUserProvided()) {
7202 M->setTrivialForCall(HasTrivialABI);
7203 Record->setTrivialForCallFlags(M);
7204 }
7205
7206 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7207 M->hasAttr<DLLExportAttr>()) {
7208 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7209 M->isTrivial() &&
7210 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7211 CSM == CXXDestructor))
7212 M->dropAttr<DLLExportAttr>();
7213
7214 if (M->hasAttr<DLLExportAttr>()) {
7215 // Define after any fields with in-class initializers have been parsed.
7217 }
7218 }
7219
7220 // Define defaulted constexpr virtual functions that override a base class
7221 // function right away.
7222 // FIXME: We can defer doing this until the vtable is marked as used.
7223 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7224 M->isConstexpr() && M->size_overridden_methods())
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 if (M->hasAttr<OverrideAttr>())
7251 HasMethodWithOverrideControl = true;
7252 else if (M->size_overridden_methods() > 0)
7253 HasOverridingMethodWithoutOverrideControl = true;
7254 }
7255
7256 if (!isa<CXXDestructorDecl>(M))
7257 CompleteMemberFunction(M);
7258 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7259 CheckForDefaultedFunction(
7260 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7261 }
7262 }
7263
7264 if (HasOverridingMethodWithoutOverrideControl) {
7265 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7266 for (auto *M : Record->methods())
7267 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7268 }
7269
7270 // Check the defaulted secondary comparisons after any other member functions.
7271 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7273
7274 // If this is a member function, we deferred checking it until now.
7275 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7276 CheckCompletedMemberFunction(MD);
7277 }
7278
7279 // ms_struct is a request to use the same ABI rules as MSVC. Check
7280 // whether this class uses any C++ features that are implemented
7281 // completely differently in MSVC, and if so, emit a diagnostic.
7282 // That diagnostic defaults to an error, but we allow projects to
7283 // map it down to a warning (or ignore it). It's a fairly common
7284 // practice among users of the ms_struct pragma to mass-annotate
7285 // headers, sweeping up a bunch of types that the project doesn't
7286 // really rely on MSVC-compatible layout for. We must therefore
7287 // support "ms_struct except for C++ stuff" as a secondary ABI.
7288 // Don't emit this diagnostic if the feature was enabled as a
7289 // language option (as opposed to via a pragma or attribute), as
7290 // the option -mms-bitfields otherwise essentially makes it impossible
7291 // to build C++ code, unless this diagnostic is turned off.
7292 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7293 (Record->isPolymorphic() || Record->getNumBases())) {
7294 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7295 }
7296
7299
7300 bool ClangABICompat4 =
7301 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7303 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7304 bool CanPass = canPassInRegisters(*this, Record, CCK);
7305
7306 // Do not change ArgPassingRestrictions if it has already been set to
7307 // RecordArgPassingKind::CanNeverPassInRegs.
7308 if (Record->getArgPassingRestrictions() !=
7310 Record->setArgPassingRestrictions(
7313
7314 // If canPassInRegisters returns true despite the record having a non-trivial
7315 // destructor, the record is destructed in the callee. This happens only when
7316 // the record or one of its subobjects has a field annotated with trivial_abi
7317 // or a field qualified with ObjC __strong/__weak.
7319 Record->setParamDestroyedInCallee(true);
7320 else if (Record->hasNonTrivialDestructor())
7321 Record->setParamDestroyedInCallee(CanPass);
7322
7323 if (getLangOpts().ForceEmitVTables) {
7324 // If we want to emit all the vtables, we need to mark it as used. This
7325 // is especially required for cases like vtable assumption loads.
7326 MarkVTableUsed(Record->getInnerLocStart(), Record);
7327 }
7328
7329 if (getLangOpts().CUDA) {
7330 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7332 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7334 }
7335}
7336
7337/// Look up the special member function that would be called by a special
7338/// member function for a subobject of class type.
7339///
7340/// \param Class The class type of the subobject.
7341/// \param CSM The kind of special member function.
7342/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7343/// \param ConstRHS True if this is a copy operation with a const object
7344/// on its RHS, that is, if the argument to the outer special member
7345/// function is 'const' and this is not a field marked 'mutable'.
7348 unsigned FieldQuals, bool ConstRHS) {
7349 unsigned LHSQuals = 0;
7351 LHSQuals = FieldQuals;
7352
7353 unsigned RHSQuals = FieldQuals;
7355 RHSQuals = 0;
7356 else if (ConstRHS)
7357 RHSQuals |= Qualifiers::Const;
7358
7359 return S.LookupSpecialMember(Class, CSM,
7360 RHSQuals & Qualifiers::Const,
7361 RHSQuals & Qualifiers::Volatile,
7362 false,
7363 LHSQuals & Qualifiers::Const,
7364 LHSQuals & Qualifiers::Volatile);
7365}
7366
7368 Sema &S;
7369 SourceLocation UseLoc;
7370
7371 /// A mapping from the base classes through which the constructor was
7372 /// inherited to the using shadow declaration in that base class (or a null
7373 /// pointer if the constructor was declared in that base class).
7374 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7375 InheritedFromBases;
7376
7377public:
7380 : S(S), UseLoc(UseLoc) {
7381 bool DiagnosedMultipleConstructedBases = false;
7382 CXXRecordDecl *ConstructedBase = nullptr;
7383 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7384
7385 // Find the set of such base class subobjects and check that there's a
7386 // unique constructed subobject.
7387 for (auto *D : Shadow->redecls()) {
7388 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7389 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7390 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7391
7392 InheritedFromBases.insert(
7393 std::make_pair(DNominatedBase->getCanonicalDecl(),
7394 DShadow->getNominatedBaseClassShadowDecl()));
7395 if (DShadow->constructsVirtualBase())
7396 InheritedFromBases.insert(
7397 std::make_pair(DConstructedBase->getCanonicalDecl(),
7398 DShadow->getConstructedBaseClassShadowDecl()));
7399 else
7400 assert(DNominatedBase == DConstructedBase);
7401
7402 // [class.inhctor.init]p2:
7403 // If the constructor was inherited from multiple base class subobjects
7404 // of type B, the program is ill-formed.
7405 if (!ConstructedBase) {
7406 ConstructedBase = DConstructedBase;
7407 ConstructedBaseIntroducer = D->getIntroducer();
7408 } else if (ConstructedBase != DConstructedBase &&
7409 !Shadow->isInvalidDecl()) {
7410 if (!DiagnosedMultipleConstructedBases) {
7411 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7412 << Shadow->getTargetDecl();
7413 S.Diag(ConstructedBaseIntroducer->getLocation(),
7414 diag::note_ambiguous_inherited_constructor_using)
7415 << ConstructedBase;
7416 DiagnosedMultipleConstructedBases = true;
7417 }
7418 S.Diag(D->getIntroducer()->getLocation(),
7419 diag::note_ambiguous_inherited_constructor_using)
7420 << DConstructedBase;
7421 }
7422 }
7423
7424 if (DiagnosedMultipleConstructedBases)
7425 Shadow->setInvalidDecl();
7426 }
7427
7428 /// Find the constructor to use for inherited construction of a base class,
7429 /// and whether that base class constructor inherits the constructor from a
7430 /// virtual base class (in which case it won't actually invoke it).
7431 std::pair<CXXConstructorDecl *, bool>
7433 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7434 if (It == InheritedFromBases.end())
7435 return std::make_pair(nullptr, false);
7436
7437 // This is an intermediary class.
7438 if (It->second)
7439 return std::make_pair(
7440 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7441 It->second->constructsVirtualBase());
7442
7443 // This is the base class from which the constructor was inherited.
7444 return std::make_pair(Ctor, false);
7445 }
7446};
7447
7448/// Is the special member function which would be selected to perform the
7449/// specified operation on the specified class type a constexpr constructor?
7450static bool
7452 Sema::CXXSpecialMember CSM, unsigned Quals,
7453 bool ConstRHS,
7454 CXXConstructorDecl *InheritedCtor = nullptr,
7455 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7456 // Suppress duplicate constraint checking here, in case a constraint check
7457 // caused us to decide to do this. Any truely recursive checks will get
7458 // caught during these checks anyway.
7460
7461 // If we're inheriting a constructor, see if we need to call it for this base
7462 // class.
7463 if (InheritedCtor) {
7464 assert(CSM == Sema::CXXDefaultConstructor);
7465 auto BaseCtor =
7466 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7467 if (BaseCtor)
7468 return BaseCtor->isConstexpr();
7469 }
7470
7471 if (CSM == Sema::CXXDefaultConstructor)
7472 return ClassDecl->hasConstexprDefaultConstructor();
7473 if (CSM == Sema::CXXDestructor)
7474 return ClassDecl->hasConstexprDestructor();
7475
7477 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7478 if (!SMOR.getMethod())
7479 // A constructor we wouldn't select can't be "involved in initializing"
7480 // anything.
7481 return true;
7482 return SMOR.getMethod()->isConstexpr();
7483}
7484
7485/// Determine whether the specified special member function would be constexpr
7486/// if it were implicitly defined.
7488 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7489 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7490 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7491 if (!S.getLangOpts().CPlusPlus11)
7492 return false;
7493
7494 // C++11 [dcl.constexpr]p4:
7495 // In the definition of a constexpr constructor [...]
7496 bool Ctor = true;
7497 switch (CSM) {
7499 if (Inherited)
7500 break;
7501 // Since default constructor lookup is essentially trivial (and cannot
7502 // involve, for instance, template instantiation), we compute whether a
7503 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7504 //
7505 // This is important for performance; we need to know whether the default
7506 // constructor is constexpr to determine whether the type is a literal type.
7507 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7508
7511 // For copy or move constructors, we need to perform overload resolution.
7512 break;
7513
7516 if (!S.getLangOpts().CPlusPlus14)
7517 return false;
7518 // In C++1y, we need to perform overload resolution.
7519 Ctor = false;
7520 break;
7521
7523 return ClassDecl->defaultedDestructorIsConstexpr();
7524
7525 case Sema::CXXInvalid:
7526 return false;
7527 }
7528
7529 // -- if the class is a non-empty union, or for each non-empty anonymous
7530 // union member of a non-union class, exactly one non-static data member
7531 // shall be initialized; [DR1359]
7532 //
7533 // If we squint, this is guaranteed, since exactly one non-static data member
7534 // will be initialized (if the constructor isn't deleted), we just don't know
7535 // which one.
7536 if (Ctor && ClassDecl->isUnion())
7537 return CSM == Sema::CXXDefaultConstructor
7538 ? ClassDecl->hasInClassInitializer() ||
7539 !ClassDecl->hasVariantMembers()
7540 : true;
7541
7542 // -- the class shall not have any virtual base classes;
7543 if (Ctor && ClassDecl->getNumVBases())
7544 return false;
7545
7546 // C++1y [class.copy]p26:
7547 // -- [the class] is a literal type, and
7548 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7549 return false;
7550
7551 // -- every constructor involved in initializing [...] base class
7552 // sub-objects shall be a constexpr constructor;
7553 // -- the assignment operator selected to copy/move each direct base
7554 // class is a constexpr function, and
7555 if (!S.getLangOpts().CPlusPlus23) {
7556 for (const auto &B : ClassDecl->bases()) {
7557 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7558 if (!BaseType)
7559 continue;
7560 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7561 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7562 InheritedCtor, Inherited))
7563 return false;
7564 }
7565 }
7566
7567 // -- every constructor involved in initializing non-static data members
7568 // [...] shall be a constexpr constructor;
7569 // -- every non-static data member and base class sub-object shall be
7570 // initialized
7571 // -- for each non-static data member of X that is of class type (or array
7572 // thereof), the assignment operator selected to copy/move that member is
7573 // a constexpr function
7574 if (!S.getLangOpts().CPlusPlus23) {
7575 for (const auto *F : ClassDecl->fields()) {
7576 if (F->isInvalidDecl())
7577 continue;
7578 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7579 continue;
7580 QualType BaseType = S.Context.getBaseElementType(F->getType());
7581 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7582 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7583 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7584 BaseType.getCVRQualifiers(),
7585 ConstArg && !F->isMutable()))
7586 return false;
7587 } else if (CSM == Sema::CXXDefaultConstructor) {
7588 return false;
7589 }
7590 }
7591 }
7592
7593 // All OK, it's constexpr!
7594 return true;
7595}
7596
7597namespace {
7598/// RAII object to register a defaulted function as having its exception
7599/// specification computed.
7600struct ComputingExceptionSpec {
7601 Sema &S;
7602
7603 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7604 : S(S) {
7607 Ctx.PointOfInstantiation = Loc;
7608 Ctx.Entity = FD;
7610 }
7611 ~ComputingExceptionSpec() {
7613 }
7614};
7615}
7616
7621
7624 FunctionDecl *FD,
7626
7629 auto DFK = S.getDefaultedFunctionKind(FD);
7630 if (DFK.isSpecialMember())
7632 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7633 if (DFK.isComparison())
7635 DFK.asComparison());
7636
7637 auto *CD = cast<CXXConstructorDecl>(FD);
7638 assert(CD->getInheritedConstructor() &&
7639 "only defaulted functions and inherited constructors have implicit "
7640 "exception specs");
7642 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7644 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7645}
7646
7648 CXXMethodDecl *MD) {
7650
7651 // Build an exception specification pointing back at this member.
7653 EPI.ExceptionSpec.SourceDecl = MD;
7654
7655 // Set the calling convention to the default for C++ instance methods.
7657 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7658 /*IsCXXMethod=*/true));
7659 return EPI;
7660}
7661
7663 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7665 return;
7666
7667 // Evaluate the exception specification.
7668 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7669 auto ESI = IES.getExceptionSpec();
7670
7671 // Update the type of the special member to use it.
7672 UpdateExceptionSpec(FD, ESI);
7673}
7674
7676 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7677
7679 if (!DefKind) {
7680 assert(FD->getDeclContext()->isDependentContext());
7681 return;
7682 }
7683
7684 if (DefKind.isComparison())
7685 UnusedPrivateFields.clear();
7686
7687 if (DefKind.isSpecialMember()
7688 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7689 DefKind.asSpecialMember(),
7690 FD->getDefaultLoc())
7692 FD->setInvalidDecl();
7693}
7694
7696 CXXSpecialMember CSM,
7697 SourceLocation DefaultLoc) {
7698 CXXRecordDecl *RD = MD->getParent();
7699
7700 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7701 "not an explicitly-defaulted special member");
7702
7703 // Defer all checking for special members of a dependent type.
7704 if (RD->isDependentType())
7705 return false;
7706
7707 // Whether this was the first-declared instance of the constructor.
7708 // This affects whether we implicitly add an exception spec and constexpr.
7709 bool First = MD == MD->getCanonicalDecl();
7710
7711 bool HadError = false;
7712
7713 // C++11 [dcl.fct.def.default]p1:
7714 // A function that is explicitly defaulted shall
7715 // -- be a special member function [...] (checked elsewhere),
7716 // -- have the same type (except for ref-qualifiers, and except that a
7717 // copy operation can take a non-const reference) as an implicit
7718 // declaration, and
7719 // -- not have default arguments.
7720 // C++2a changes the second bullet to instead delete the function if it's
7721 // defaulted on its first declaration, unless it's "an assignment operator,
7722 // and its return type differs or its parameter type is not a reference".
7723 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7724 bool ShouldDeleteForTypeMismatch = false;
7725 unsigned ExpectedParams = 1;
7726 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7727 ExpectedParams = 0;
7728 if (MD->getNumExplicitParams() != ExpectedParams) {
7729 // This checks for default arguments: a copy or move constructor with a
7730 // default argument is classified as a default constructor, and assignment
7731 // operations and destructors can't have default arguments.
7732 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7733 << CSM << MD->getSourceRange();
7734 HadError = true;
7735 } else if (MD->isVariadic()) {
7736 if (DeleteOnTypeMismatch)
7737 ShouldDeleteForTypeMismatch = true;
7738 else {
7739 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7740 << CSM << MD->getSourceRange();
7741 HadError = true;
7742 }
7743 }
7744
7746
7747 bool CanHaveConstParam = false;
7748 if (CSM == CXXCopyConstructor)
7749 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7750 else if (CSM == CXXCopyAssignment)
7751 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7752
7753 QualType ReturnType = Context.VoidTy;
7754 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7755 // Check for return type matching.
7756 ReturnType = Type->getReturnType();
7758
7759 QualType DeclType = Context.getTypeDeclType(RD);
7761 DeclType, nullptr);
7762 DeclType = Context.getAddrSpaceQualType(
7763 DeclType, ThisType.getQualifiers().getAddressSpace());
7764 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7765
7766 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7767 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7768 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7769 HadError = true;
7770 }
7771
7772 // A defaulted special member cannot have cv-qualifiers.
7773 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7774 if (DeleteOnTypeMismatch)
7775 ShouldDeleteForTypeMismatch = true;
7776 else {
7777 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7778 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7779 HadError = true;
7780 }
7781 }
7782 // [C++23][dcl.fct.def.default]/p2.2
7783 // if F2 has an implicit object parameter of type “reference to C”,
7784 // F1 may be an explicit object member function whose explicit object
7785 // parameter is of (possibly different) type “reference to C”,
7786 // in which case the type of F1 would differ from the type of F2
7787 // in that the type of F1 has an additional parameter;
7788 if (!Context.hasSameType(
7790 Context.getRecordType(RD))) {
7791 if (DeleteOnTypeMismatch)
7792 ShouldDeleteForTypeMismatch = true;
7793 else {
7794 Diag(MD->getLocation(),
7795 diag::err_defaulted_special_member_explicit_object_mismatch)
7796 << (CSM == CXXMoveAssignment) << RD << MD->getSourceRange();
7797 HadError = true;
7798 }
7799 }
7800 }
7801
7802 // Check for parameter type matching.
7803 QualType ArgType =
7804 ExpectedParams
7805 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7806 : QualType();
7807 bool HasConstParam = false;
7808 if (ExpectedParams && ArgType->isReferenceType()) {
7809 // Argument must be reference to possibly-const T.
7810 QualType ReferentType = ArgType->getPointeeType();
7811 HasConstParam = ReferentType.isConstQualified();
7812
7813 if (ReferentType.isVolatileQualified()) {
7814 if (DeleteOnTypeMismatch)
7815 ShouldDeleteForTypeMismatch = true;
7816 else {
7817 Diag(MD->getLocation(),
7818 diag::err_defaulted_special_member_volatile_param) << CSM;
7819 HadError = true;
7820 }
7821 }
7822
7823 if (HasConstParam && !CanHaveConstParam) {
7824 if (DeleteOnTypeMismatch)
7825 ShouldDeleteForTypeMismatch = true;
7826 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7827 Diag(MD->getLocation(),
7828 diag::err_defaulted_special_member_copy_const_param)
7829 << (CSM == CXXCopyAssignment);
7830 // FIXME: Explain why this special member can't be const.
7831 HadError = true;
7832 } else {
7833 Diag(MD->getLocation(),
7834 diag::err_defaulted_special_member_move_const_param)
7835 << (CSM == CXXMoveAssignment);
7836 HadError = true;
7837 }
7838 }
7839 } else if (ExpectedParams) {
7840 // A copy assignment operator can take its argument by value, but a
7841 // defaulted one cannot.
7842 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7843 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7844 HadError = true;
7845 }
7846
7847 // C++11 [dcl.fct.def.default]p2:
7848 // An explicitly-defaulted function may be declared constexpr only if it
7849 // would have been implicitly declared as constexpr,
7850 // Do not apply this rule to members of class templates, since core issue 1358
7851 // makes such functions always instantiate to constexpr functions. For
7852 // functions which cannot be constexpr (for non-constructors in C++11 and for
7853 // destructors in C++14 and C++17), this is checked elsewhere.
7854 //
7855 // FIXME: This should not apply if the member is deleted.
7856 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7857 HasConstParam);
7858
7859 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7860 // If the instantiated template specialization of a constexpr function
7861 // template or member function of a class template would fail to satisfy
7862 // the requirements for a constexpr function or constexpr constructor, that
7863 // specialization is still a constexpr function or constexpr constructor,
7864 // even though a call to such a function cannot appear in a constant
7865 // expression.
7866 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7867 Constexpr = true;
7868
7869 if ((getLangOpts().CPlusPlus20 ||
7870 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7871 : isa<CXXConstructorDecl>(MD))) &&
7872 MD->isConstexpr() && !Constexpr &&
7874 if (!MD->isConsteval() && RD->getNumVBases()) {
7875 Diag(MD->getBeginLoc(),
7876 diag::err_incorrect_defaulted_constexpr_with_vb)
7877 << CSM;
7878 for (const auto &I : RD->vbases())
7879 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7880 } else {
7881 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7882 << CSM << MD->isConsteval();
7883 }
7884 HadError = true;
7885 // FIXME: Explain why the special member can't be constexpr.
7886 }
7887
7888 if (First) {
7889 // C++2a [dcl.fct.def.default]p3:
7890 // If a function is explicitly defaulted on its first declaration, it is
7891 // implicitly considered to be constexpr if the implicit declaration
7892 // would be.
7897
7898 if (!Type->hasExceptionSpec()) {
7899 // C++2a [except.spec]p3:
7900 // If a declaration of a function does not have a noexcept-specifier
7901 // [and] is defaulted on its first declaration, [...] the exception
7902 // specification is as specified below
7903 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7905 EPI.ExceptionSpec.SourceDecl = MD;
7906 MD->setType(
7907 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7908 }
7909 }
7910
7911 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7912 if (First) {
7913 SetDeclDeleted(MD, MD->getLocation());
7914 if (!inTemplateInstantiation() && !HadError) {
7915 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7916 if (ShouldDeleteForTypeMismatch) {
7917 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7918 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7919 /*Diagnose*/ true) &&
7920 DefaultLoc.isValid()) {
7921 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7922 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7923 }
7924 }
7925 if (ShouldDeleteForTypeMismatch && !HadError) {
7926 Diag(MD->getLocation(),
7927 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7928 }
7929 } else {
7930 // C++11 [dcl.fct.def.default]p4:
7931 // [For a] user-provided explicitly-defaulted function [...] if such a
7932 // function is implicitly defined as deleted, the program is ill-formed.
7933 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7934 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7935 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7936 HadError = true;
7937 }
7938 }
7939
7940 return HadError;
7941}
7942
7943namespace {
7944/// Helper class for building and checking a defaulted comparison.
7945///
7946/// Defaulted functions are built in two phases:
7947///
7948/// * First, the set of operations that the function will perform are
7949/// identified, and some of them are checked. If any of the checked
7950/// operations is invalid in certain ways, the comparison function is
7951/// defined as deleted and no body is built.
7952/// * Then, if the function is not defined as deleted, the body is built.
7953///
7954/// This is accomplished by performing two visitation steps over the eventual
7955/// body of the function.
7956template<typename Derived, typename ResultList, typename Result,
7957 typename Subobject>
7958class DefaultedComparisonVisitor {
7959public:
7960 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7961
7962 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7963 DefaultedComparisonKind DCK)
7964 : S(S), RD(RD), FD(FD), DCK(DCK) {
7965 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7966 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7967 // UnresolvedSet to avoid this copy.
7968 Fns.assign(Info->getUnqualifiedLookups().begin(),
7969 Info->getUnqualifiedLookups().end());
7970 }
7971 }
7972
7973 ResultList visit() {
7974 // The type of an lvalue naming a parameter of this function.
7975 QualType ParamLvalType =
7977
7978 ResultList Results;
7979
7980 switch (DCK) {
7981 case DefaultedComparisonKind::None:
7982 llvm_unreachable("not a defaulted comparison");
7983
7984 case DefaultedComparisonKind::Equal:
7985 case DefaultedComparisonKind::ThreeWay:
7986 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7987 return Results;
7988
7989 case DefaultedComparisonKind::NotEqual:
7990 case DefaultedComparisonKind::Relational:
7991 Results.add(getDerived().visitExpandedSubobject(
7992 ParamLvalType, getDerived().getCompleteObject()));
7993 return Results;
7994 }
7995 llvm_unreachable("");
7996 }
7997
7998protected:
7999 Derived &getDerived() { return static_cast<Derived&>(*this); }
8000
8001 /// Visit the expanded list of subobjects of the given type, as specified in
8002 /// C++2a [class.compare.default].
8003 ///
8004 /// \return \c true if the ResultList object said we're done, \c false if not.
8005 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8006 Qualifiers Quals) {
8007 // C++2a [class.compare.default]p4:
8008 // The direct base class subobjects of C
8009 for (CXXBaseSpecifier &Base : Record->bases())
8010 if (Results.add(getDerived().visitSubobject(
8011 S.Context.getQualifiedType(Base.getType(), Quals),
8012 getDerived().getBase(&Base))))
8013 return true;
8014
8015 // followed by the non-static data members of C
8016 for (FieldDecl *Field : Record->fields()) {
8017 // C++23 [class.bit]p2:
8018 // Unnamed bit-fields are not members ...
8019 if (Field->isUnnamedBitfield())
8020 continue;
8021 // Recursively expand anonymous structs.
8022 if (Field->isAnonymousStructOrUnion()) {
8023 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8024 Quals))
8025 return true;
8026 continue;
8027 }
8028
8029 // Figure out the type of an lvalue denoting this field.
8030 Qualifiers FieldQuals = Quals;
8031 if (Field->isMutable())
8032 FieldQuals.removeConst();
8033 QualType FieldType =
8034 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8035
8036 if (Results.add(getDerived().visitSubobject(
8037 FieldType, getDerived().getField(Field))))
8038 return true;
8039 }
8040
8041 // form a list of subobjects.
8042 return false;
8043 }
8044
8045 Result visitSubobject(QualType Type, Subobject Subobj) {
8046 // In that list, any subobject of array type is recursively expanded
8047 const ArrayType *AT = S.Context.getAsArrayType(Type);
8048 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8049 return getDerived().visitSubobjectArray(CAT->getElementType(),
8050 CAT->getSize(), Subobj);
8051 return getDerived().visitExpandedSubobject(Type, Subobj);
8052 }
8053
8054 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8055 Subobject Subobj) {
8056 return getDerived().visitSubobject(Type, Subobj);
8057 }
8058
8059protected:
8060 Sema &S;
8061 CXXRecordDecl *RD;
8062 FunctionDecl *FD;
8063 DefaultedComparisonKind DCK;
8065};
8066
8067/// Information about a defaulted comparison, as determined by
8068/// DefaultedComparisonAnalyzer.
8069struct DefaultedComparisonInfo {
8070 bool Deleted = false;
8071 bool Constexpr = true;
8072 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8073
8074 static DefaultedComparisonInfo deleted() {
8075 DefaultedComparisonInfo Deleted;
8076 Deleted.Deleted = true;
8077 return Deleted;
8078 }
8079
8080 bool add(const DefaultedComparisonInfo &R) {
8081 Deleted |= R.Deleted;
8082 Constexpr &= R.Constexpr;
8083 Category = commonComparisonType(Category, R.Category);
8084 return Deleted;
8085 }
8086};
8087
8088/// An element in the expanded list of subobjects of a defaulted comparison, as
8089/// specified in C++2a [class.compare.default]p4.
8090struct DefaultedComparisonSubobject {
8091 enum { CompleteObject, Member, Base } Kind;
8092 NamedDecl *Decl;
8093 SourceLocation Loc;
8094};
8095
8096/// A visitor over the notional body of a defaulted comparison that determines
8097/// whether that body would be deleted or constexpr.
8098class DefaultedComparisonAnalyzer
8099 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8100 DefaultedComparisonInfo,
8101 DefaultedComparisonInfo,
8102 DefaultedComparisonSubobject> {
8103public:
8104 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8105
8106private:
8107 DiagnosticKind Diagnose;
8108
8109public:
8110 using Base = DefaultedComparisonVisitor;
8111 using Result = DefaultedComparisonInfo;
8112 using Subobject = DefaultedComparisonSubobject;
8113
8114 friend Base;
8115
8116 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8117 DefaultedComparisonKind DCK,
8118 DiagnosticKind Diagnose = NoDiagnostics)
8119 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8120
8121 Result visit() {
8122 if ((DCK == DefaultedComparisonKind::Equal ||
8123 DCK == DefaultedComparisonKind::ThreeWay) &&
8124 RD->hasVariantMembers()) {
8125 // C++2a [class.compare.default]p2 [P2002R0]:
8126 // A defaulted comparison operator function for class C is defined as
8127 // deleted if [...] C has variant members.
8128 if (Diagnose == ExplainDeleted) {
8129 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8130 << FD << RD->isUnion() << RD;
8131 }
8132 return Result::deleted();
8133 }
8134
8135 return Base::visit();
8136 }
8137
8138private:
8139 Subobject getCompleteObject() {
8140 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8141 }
8142
8143 Subobject getBase(CXXBaseSpecifier *Base) {
8144 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8145 Base->getBaseTypeLoc()};
8146 }
8147
8148 Subobject getField(FieldDecl *Field) {
8149 return Subobject{Subobject::Member, Field, Field->getLocation()};
8150 }
8151
8152 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8153 // C++2a [class.compare.default]p2 [P2002R0]:
8154 // A defaulted <=> or == operator function for class C is defined as
8155 // deleted if any non-static data member of C is of reference type
8156 if (Type->isReferenceType()) {
8157 if (Diagnose == ExplainDeleted) {
8158 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8159 << FD << RD;
8160 }
8161 return Result::deleted();
8162 }
8163
8164 // [...] Let xi be an lvalue denoting the ith element [...]
8166 Expr *Args[] = {&Xi, &Xi};
8167
8168 // All operators start by trying to apply that same operator recursively.
8170 assert(OO != OO_None && "not an overloaded operator!");
8171 return visitBinaryOperator(OO, Args, Subobj);
8172 }
8173
8174 Result
8175 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8176 Subobject Subobj,
8177 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8178 // Note that there is no need to consider rewritten candidates here if
8179 // we've already found there is no viable 'operator<=>' candidate (and are
8180 // considering synthesizing a '<=>' from '==' and '<').
8181 OverloadCandidateSet CandidateSet(
8184 OO, FD->getLocation(),
8185 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8186
8187 /// C++2a [class.compare.default]p1 [P2002R0]:
8188 /// [...] the defaulted function itself is never a candidate for overload
8189 /// resolution [...]
8190 CandidateSet.exclude(FD);
8191
8192 if (Args[0]->getType()->isOverloadableType())
8193 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8194 else
8195 // FIXME: We determine whether this is a valid expression by checking to
8196 // see if there's a viable builtin operator candidate for it. That isn't
8197 // really what the rules ask us to do, but should give the right results.
8198 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8199
8200 Result R;
8201
8203 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8204 case OR_Success: {
8205 // C++2a [class.compare.secondary]p2 [P2002R0]:
8206 // The operator function [...] is defined as deleted if [...] the
8207 // candidate selected by overload resolution is not a rewritten
8208 // candidate.
8209 if ((DCK == DefaultedComparisonKind::NotEqual ||
8210 DCK == DefaultedComparisonKind::Relational) &&
8211 !Best->RewriteKind) {
8212 if (Diagnose == ExplainDeleted) {
8213 if (Best->Function) {
8214 S.Diag(Best->Function->getLocation(),
8215 diag::note_defaulted_comparison_not_rewritten_callee)
8216 << FD;
8217 } else {
8218 assert(Best->Conversions.size() == 2 &&
8219 Best->Conversions[0].isUserDefined() &&
8220 "non-user-defined conversion from class to built-in "
8221 "comparison");
8222 S.Diag(Best->Conversions[0]
8223 .UserDefined.FoundConversionFunction.getDecl()
8224 ->getLocation(),
8225 diag::note_defaulted_comparison_not_rewritten_conversion)
8226 << FD;
8227 }
8228 }
8229 return Result::deleted();
8230 }
8231
8232 // Throughout C++2a [class.compare]: if overload resolution does not
8233 // result in a usable function, the candidate function is defined as
8234 // deleted. This requires that we selected an accessible function.
8235 //
8236 // Note that this only considers the access of the function when named
8237 // within the type of the subobject, and not the access path for any
8238 // derived-to-base conversion.
8239 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8240 if (ArgClass && Best->FoundDecl.getDecl() &&
8241 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8242 QualType ObjectType = Subobj.Kind == Subobject::Member
8243 ? Args[0]->getType()
8244 : S.Context.getRecordType(RD);
8246 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8247 Diagnose == ExplainDeleted
8248 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8249 << FD << Subobj.Kind << Subobj.Decl
8250 : S.PDiag()))
8251 return Result::deleted();
8252 }
8253
8254 bool NeedsDeducing =
8255 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8256
8257 if (FunctionDecl *BestFD = Best->Function) {
8258 // C++2a [class.compare.default]p3 [P2002R0]:
8259 // A defaulted comparison function is constexpr-compatible if
8260 // [...] no overlod resolution performed [...] results in a
8261 // non-constexpr function.
8262 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8263 // If it's not constexpr, explain why not.
8264 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8265 if (Subobj.Kind != Subobject::CompleteObject)
8266 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8267 << Subobj.Kind << Subobj.Decl;
8268 S.Diag(BestFD->getLocation(),
8269 diag::note_defaulted_comparison_not_constexpr_here);
8270 // Bail out after explaining; we don't want any more notes.
8271 return Result::deleted();
8272 }
8273 R.Constexpr &= BestFD->isConstexpr();
8274
8275 if (NeedsDeducing) {
8276 // If any callee has an undeduced return type, deduce it now.
8277 // FIXME: It's not clear how a failure here should be handled. For
8278 // now, we produce an eager diagnostic, because that is forward
8279 // compatible with most (all?) other reasonable options.
8280 if (BestFD->getReturnType()->isUndeducedType() &&
8281 S.DeduceReturnType(BestFD, FD->getLocation(),
8282 /*Diagnose=*/false)) {
8283 // Don't produce a duplicate error when asked to explain why the
8284 // comparison is deleted: we diagnosed that when initially checking
8285 // the defaulted operator.
8286 if (Diagnose == NoDiagnostics) {
8287 S.Diag(
8288 FD->getLocation(),
8289 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8290 << Subobj.Kind << Subobj.Decl;
8291 S.Diag(
8292 Subobj.Loc,
8293 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8294 << Subobj.Kind << Subobj.Decl;
8295 S.Diag(BestFD->getLocation(),
8296 diag::note_defaulted_comparison_cannot_deduce_callee)
8297 << Subobj.Kind << Subobj.Decl;
8298 }
8299 return Result::deleted();
8300 }
8302 BestFD->getCallResultType());
8303 if (!Info) {
8304 if (Diagnose == ExplainDeleted) {
8305 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8306 << Subobj.Kind << Subobj.Decl
8307 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8308 S.Diag(BestFD->getLocation(),
8309 diag::note_defaulted_comparison_cannot_deduce_callee)
8310 << Subobj.Kind << Subobj.Decl;
8311 }
8312 return Result::deleted();
8313 }
8314 R.Category = Info->Kind;
8315 }
8316 } else {
8317 QualType T = Best->BuiltinParamTypes[0];
8318 assert(T == Best->BuiltinParamTypes[1] &&
8319 "builtin comparison for different types?");
8320 assert(Best->BuiltinParamTypes[2].isNull() &&
8321 "invalid builtin comparison");
8322
8323 if (NeedsDeducing) {
8324 std::optional<ComparisonCategoryType> Cat =
8326 assert(Cat && "no category for builtin comparison?");
8327 R.Category = *Cat;
8328 }
8329 }
8330
8331 // Note that we might be rewriting to a different operator. That call is
8332 // not considered until we come to actually build the comparison function.
8333 break;
8334 }
8335
8336 case OR_Ambiguous:
8337 if (Diagnose == ExplainDeleted) {
8338 unsigned Kind = 0;
8339 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8340 Kind = OO == OO_EqualEqual ? 1 : 2;
8341 CandidateSet.NoteCandidates(
8343 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8344 << FD << Kind << Subobj.Kind << Subobj.Decl),
8345 S, OCD_AmbiguousCandidates, Args);
8346 }
8347 R = Result::deleted();
8348 break;
8349
8350 case OR_Deleted:
8351 if (Diagnose == ExplainDeleted) {
8352 if ((DCK == DefaultedComparisonKind::NotEqual ||
8353 DCK == DefaultedComparisonKind::Relational) &&
8354 !Best->RewriteKind) {
8355 S.Diag(Best->Function->getLocation(),
8356 diag::note_defaulted_comparison_not_rewritten_callee)
8357 << FD;
8358 } else {
8359 S.Diag(Subobj.Loc,
8360 diag::note_defaulted_comparison_calls_deleted)
8361 << FD << Subobj.Kind << Subobj.Decl;
8362 S.NoteDeletedFunction(Best->Function);
8363 }
8364 }
8365 R = Result::deleted();
8366 break;
8367
8369 // If there's no usable candidate, we're done unless we can rewrite a
8370 // '<=>' in terms of '==' and '<'.
8371 if (OO == OO_Spaceship &&
8373 // For any kind of comparison category return type, we need a usable
8374 // '==' and a usable '<'.
8375 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8376 &CandidateSet)))
8377 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8378 break;
8379 }
8380
8381 if (Diagnose == ExplainDeleted) {
8382 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8383 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8384 << Subobj.Kind << Subobj.Decl;
8385
8386 // For a three-way comparison, list both the candidates for the
8387 // original operator and the candidates for the synthesized operator.
8388 if (SpaceshipCandidates) {
8389 SpaceshipCandidates->NoteCandidates(
8390 S, Args,
8391 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8392 Args, FD->getLocation()));
8393 S.Diag(Subobj.Loc,
8394 diag::note_defaulted_comparison_no_viable_function_synthesized)
8395 << (OO == OO_EqualEqual ? 0 : 1);
8396 }
8397
8398 CandidateSet.NoteCandidates(
8399 S, Args,
8400 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8401 FD->getLocation()));
8402 }
8403 R = Result::deleted();
8404 break;
8405 }
8406
8407 return R;
8408 }
8409};
8410
8411/// A list of statements.
8412struct StmtListResult {
8413 bool IsInvalid = false;
8415
8416 bool add(const StmtResult &S) {
8417 IsInvalid |= S.isInvalid();
8418 if (IsInvalid)
8419 return true;
8420 Stmts.push_back(S.get());
8421 return false;
8422 }
8423};
8424
8425/// A visitor over the notional body of a defaulted comparison that synthesizes
8426/// the actual body.
8427class DefaultedComparisonSynthesizer
8428 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8429 StmtListResult, StmtResult,
8430 std::pair<ExprResult, ExprResult>> {
8431 SourceLocation Loc;
8432 unsigned ArrayDepth = 0;
8433
8434public:
8435 using Base = DefaultedComparisonVisitor;
8436 using ExprPair = std::pair<ExprResult, ExprResult>;
8437
8438 friend Base;
8439
8440 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8441 DefaultedComparisonKind DCK,
8442 SourceLocation BodyLoc)
8443 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8444
8445 /// Build a suitable function body for this defaulted comparison operator.
8446 StmtResult build() {
8447 Sema::CompoundScopeRAII CompoundScope(S);
8448
8449 StmtListResult Stmts = visit();
8450 if (Stmts.IsInvalid)
8451 return StmtError();
8452
8453 ExprResult RetVal;
8454 switch (DCK) {
8455 case DefaultedComparisonKind::None:
8456 llvm_unreachable("not a defaulted comparison");
8457
8458 case DefaultedComparisonKind::Equal: {
8459 // C++2a [class.eq]p3:
8460 // [...] compar[e] the corresponding elements [...] until the first
8461 // index i where xi == yi yields [...] false. If no such index exists,
8462 // V is true. Otherwise, V is false.
8463 //
8464 // Join the comparisons with '&&'s and return the result. Use a right
8465 // fold (traversing the conditions right-to-left), because that
8466 // short-circuits more naturally.
8467 auto OldStmts = std::move(Stmts.Stmts);
8468 Stmts.Stmts.clear();
8469 ExprResult CmpSoFar;
8470 // Finish a particular comparison chain.
8471 auto FinishCmp = [&] {
8472 if (Expr *Prior = CmpSoFar.get()) {
8473 // Convert the last expression to 'return ...;'
8474 if (RetVal.isUnset() && Stmts.Stmts.empty())
8475 RetVal = CmpSoFar;
8476 // Convert any prior comparison to 'if (!(...)) return false;'
8477 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8478 return true;
8479 CmpSoFar = ExprResult();
8480 }
8481 return false;
8482 };
8483 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8484 Expr *E = dyn_cast<Expr>(EAsStmt);
8485 if (!E) {
8486 // Found an array comparison.
8487 if (FinishCmp() || Stmts.add(EAsStmt))
8488 return StmtError();
8489 continue;
8490 }
8491
8492 if (CmpSoFar.isUnset()) {
8493 CmpSoFar = E;
8494 continue;
8495 }
8496 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8497 if (CmpSoFar.isInvalid())
8498 return StmtError();
8499 }
8500 if (FinishCmp())
8501 return StmtError();
8502 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8503 // If no such index exists, V is true.
8504 if (RetVal.isUnset())
8505 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8506 break;
8507 }
8508
8509 case DefaultedComparisonKind::ThreeWay: {
8510 // Per C++2a [class.spaceship]p3, as a fallback add:
8511 // return static_cast<R>(std::strong_ordering::equal);
8513 ComparisonCategoryType::StrongOrdering, Loc,
8514 Sema::ComparisonCategoryUsage::DefaultedOperator);
8515 if (StrongOrdering.isNull())
8516 return StmtError();
8518 .getValueInfo(ComparisonCategoryResult::Equal)
8519 ->VD;
8520 RetVal = getDecl(EqualVD);
8521 if (RetVal.isInvalid())
8522 return StmtError();
8523 RetVal = buildStaticCastToR(RetVal.get());
8524 break;
8525 }
8526
8527 case DefaultedComparisonKind::NotEqual:
8528 case DefaultedComparisonKind::Relational:
8529 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8530 break;
8531 }
8532
8533 // Build the final return statement.
8534 if (RetVal.isInvalid())
8535 return StmtError();
8536 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8537 if (ReturnStmt.isInvalid())
8538 return StmtError();
8539 Stmts.Stmts.push_back(ReturnStmt.get());
8540
8541 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8542 }
8543
8544private:
8545 ExprResult getDecl(ValueDecl *VD) {
8546 return S.BuildDeclarationNameExpr(
8547 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8548 }
8549
8550 ExprResult getParam(unsigned I) {
8551 ParmVarDecl *PD = FD->getParamDecl(I);
8552 return getDecl(PD);
8553 }
8554
8555 ExprPair getCompleteObject() {
8556 unsigned Param = 0;
8557 ExprResult LHS;
8558 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8559 MD && MD->isImplicitObjectMemberFunction()) {
8560 // LHS is '*this'.
8561 LHS = S.ActOnCXXThis(Loc);
8562 if (!LHS.isInvalid())
8563 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8564 } else {
8565 LHS = getParam(Param++);
8566 }
8567 ExprResult RHS = getParam(Param++);
8568 assert(Param == FD->getNumParams());
8569 return {LHS, RHS};
8570 }
8571
8572 ExprPair getBase(CXXBaseSpecifier *Base) {
8573 ExprPair Obj = getCompleteObject();
8574 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8575 return {ExprError(), ExprError()};
8576 CXXCastPath Path = {Base};
8577 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8578 CK_DerivedToBase, VK_LValue, &Path),
8579 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8580 CK_DerivedToBase, VK_LValue, &Path)};
8581 }
8582
8583 ExprPair getField(FieldDecl *Field) {
8584 ExprPair Obj = getCompleteObject();
8585 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8586 return {ExprError(), ExprError()};
8587
8588 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8589 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8590 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8591 CXXScopeSpec(), Field, Found, NameInfo),
8592 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8593 CXXScopeSpec(), Field, Found, NameInfo)};
8594 }
8595
8596 // FIXME: When expanding a subobject, register a note in the code synthesis
8597 // stack to say which subobject we're comparing.
8598
8599 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8600 if (Cond.isInvalid())
8601 return StmtError();
8602
8603 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8604 if (NotCond.isInvalid())
8605 return StmtError();
8606
8607 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8608 assert(!False.isInvalid() && "should never fail");
8609 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8610 if (ReturnFalse.isInvalid())
8611 return StmtError();
8612
8613 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8614 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8615 Sema::ConditionKind::Boolean),
8616 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8617 }
8618
8619 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8620 ExprPair Subobj) {
8621 QualType SizeType = S.Context.getSizeType();
8622 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8623
8624 // Build 'size_t i$n = 0'.
8625 IdentifierInfo *IterationVarName = nullptr;
8626 {
8627 SmallString<8> Str;
8628 llvm::raw_svector_ostream OS(Str);
8629 OS << "i" << ArrayDepth;
8630 IterationVarName = &S.Context.Idents.get(OS.str());
8631 }
8632 VarDecl *IterationVar = VarDecl::Create(
8633 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8634 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8635 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8636 IterationVar->setInit(
8637 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8638 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8639
8640 auto IterRef = [&] {
8642 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8643 IterationVar);
8644 assert(!Ref.isInvalid() && "can't reference our own variable?");
8645 return Ref.get();
8646 };
8647
8648 // Build 'i$n != Size'.
8650 Loc, BO_NE, IterRef(),
8651 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8652 assert(!Cond.isInvalid() && "should never fail");
8653
8654 // Build '++i$n'.
8655 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8656 assert(!Inc.isInvalid() && "should never fail");
8657
8658 // Build 'a[i$n]' and 'b[i$n]'.
8659 auto Index = [&](ExprResult E) {
8660 if (E.isInvalid())
8661 return ExprError();
8662 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8663 };
8664 Subobj.first = Index(Subobj.first);
8665 Subobj.second = Index(Subobj.second);
8666
8667 // Compare the array elements.
8668 ++ArrayDepth;
8669 StmtResult Substmt = visitSubobject(Type, Subobj);
8670 --ArrayDepth;
8671
8672 if (Substmt.isInvalid())
8673 return StmtError();
8674
8675 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8676 // For outer levels or for an 'operator<=>' we already have a suitable
8677 // statement that returns as necessary.
8678 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8679 assert(DCK == DefaultedComparisonKind::Equal &&
8680 "should have non-expression statement");
8681 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8682 if (Substmt.isInvalid())
8683 return StmtError();
8684 }
8685
8686 // Build 'for (...) ...'
8687 return S.ActOnForStmt(Loc, Loc, Init,
8688 S.ActOnCondition(nullptr, Loc, Cond.get(),
8689 Sema::ConditionKind::Boolean),
8690 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8691 Substmt.get());
8692 }
8693
8694 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8695 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8696 return StmtError();
8697
8700 ExprResult Op;
8701 if (Type->isOverloadableType())
8702 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8703 Obj.second.get(), /*PerformADL=*/true,
8704 /*AllowRewrittenCandidates=*/true, FD);
8705 else
8706 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8707 if (Op.isInvalid())
8708 return StmtError();
8709
8710 switch (DCK) {
8711 case DefaultedComparisonKind::None:
8712 llvm_unreachable("not a defaulted comparison");
8713
8714 case DefaultedComparisonKind::Equal:
8715 // Per C++2a [class.eq]p2, each comparison is individually contextually
8716 // converted to bool.
8718 if (Op.isInvalid())
8719 return StmtError();
8720 return Op.get();
8721
8722 case DefaultedComparisonKind::ThreeWay: {
8723 // Per C++2a [class.spaceship]p3, form:
8724 // if (R cmp = static_cast<R>(op); cmp != 0)
8725 // return cmp;
8726 QualType R = FD->getReturnType();
8727 Op = buildStaticCastToR(Op.get());
8728 if (Op.isInvalid())
8729 return StmtError();
8730
8731 // R cmp = ...;
8732 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8733 VarDecl *VD =
8734 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8736 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8737 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8738
8739 // cmp != 0
8740 ExprResult VDRef = getDecl(VD);
8741 if (VDRef.isInvalid())
8742 return StmtError();
8743 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8744 Expr *Zero =
8745 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8747 if (VDRef.get()->getType()->isOverloadableType())
8748 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8749 true, FD);
8750 else
8751 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8752 if (Comp.isInvalid())
8753 return StmtError();
8755 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8756 if (Cond.isInvalid())
8757 return StmtError();
8758
8759 // return cmp;
8760 VDRef = getDecl(VD);
8761 if (VDRef.isInvalid())
8762 return StmtError();
8763 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8764 if (ReturnStmt.isInvalid())
8765 return StmtError();
8766
8767 // if (...)
8768 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8769 Loc, ReturnStmt.get(),
8770 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8771 }
8772
8773 case DefaultedComparisonKind::NotEqual:
8774 case DefaultedComparisonKind::Relational:
8775 // C++2a [class.compare.secondary]p2:
8776 // Otherwise, the operator function yields x @ y.
8777 return Op.get();
8778 }
8779 llvm_unreachable("");
8780 }
8781
8782 /// Build "static_cast<R>(E)".
8783 ExprResult buildStaticCastToR(Expr *E) {
8784 QualType R = FD->getReturnType();
8785 assert(!R->isUndeducedType() && "type should have been deduced already");
8786
8787 // Don't bother forming a no-op cast in the common case.
8788 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8789 return E;
8790 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8791 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8792 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8793 }
8794};
8795}
8796
8797/// Perform the unqualified lookups that might be needed to form a defaulted
8798/// comparison function for the given operator.
8800 UnresolvedSetImpl &Operators,
8802 auto Lookup = [&](OverloadedOperatorKind OO) {
8803 Self.LookupOverloadedOperatorName(OO, S, Operators);
8804 };
8805
8806 // Every defaulted operator looks up itself.
8807 Lookup(Op);
8808 // ... and the rewritten form of itself, if any.
8810 Lookup(ExtraOp);
8811
8812 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8813 // synthesize a three-way comparison from '<' and '=='. In a dependent
8814 // context, we also need to look up '==' in case we implicitly declare a
8815 // defaulted 'operator=='.
8816 if (Op == OO_Spaceship) {
8817 Lookup(OO_ExclaimEqual);
8818 Lookup(OO_Less);
8819 Lookup(OO_EqualEqual);
8820 }
8821}
8822
8825 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8826
8827 // Perform any unqualified lookups we're going to need to default this
8828 // function.
8829 if (S) {
8830 UnresolvedSet<32> Operators;
8831 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8832 FD->getOverloadedOperator());
8834 Context, Operators.pairs()));
8835 }
8836
8837 // C++2a [class.compare.default]p1:
8838 // A defaulted comparison operator function for some class C shall be a
8839 // non-template function declared in the member-specification of C that is
8840 // -- a non-static const non-volatile member of C having one parameter of
8841 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8842 // -- a friend of C having two parameters of type const C& or two
8843 // parameters of type C.
8844
8845 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8846 bool IsMethod = isa<CXXMethodDecl>(FD);
8847 if (IsMethod) {
8848 auto *MD = cast<CXXMethodDecl>(FD);
8849 assert(!MD->isStatic() && "comparison function cannot be a static member");
8850
8851 if (MD->getRefQualifier() == RQ_RValue) {
8852 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8853
8854 // Remove the ref qualifier to recover.
8855 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8856 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8857 EPI.RefQualifier = RQ_None;
8858 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8859 FPT->getParamTypes(), EPI));
8860 }
8861
8862 // If we're out-of-class, this is the class we're comparing.
8863 if (!RD)
8864 RD = MD->getParent();
8866 if (!T.isConstQualified()) {
8867 SourceLocation Loc, InsertLoc;
8869 Loc = MD->getParamDecl(0)->getBeginLoc();
8870 InsertLoc = getLocForEndOfToken(
8872 } else {
8873 Loc = MD->getLocation();
8874 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8875 InsertLoc = Loc.getRParenLoc();
8876 }
8877 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8878 // corresponding defaulted 'operator<=>' already.
8879 if (!MD->isImplicit()) {
8880 Diag(Loc, diag::err_defaulted_comparison_non_const)
8881 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8882 }
8883
8884 // Add the 'const' to the type to recover.
8885 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8886 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8887 EPI.TypeQuals.addConst();
8888 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8889 FPT->getParamTypes(), EPI));
8890 }
8891
8892 if (MD->isVolatile()) {
8893 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8894
8895 // Remove the 'volatile' from the type to recover.
8896 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8897 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8899 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8900 FPT->getParamTypes(), EPI));
8901 }
8902 }
8903
8904 if ((FD->getNumParams() -
8905 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8906 (IsMethod ? 1 : 2)) {
8907 // Let's not worry about using a variadic template pack here -- who would do
8908 // such a thing?
8909 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8910 << int(IsMethod) << int(DCK);
8911 return true;
8912 }
8913
8914 const ParmVarDecl *KnownParm = nullptr;
8915 for (const ParmVarDecl *Param : FD->parameters()) {
8916 if (Param->isExplicitObjectParameter())
8917 continue;
8918 QualType ParmTy = Param->getType();
8919
8920 if (!KnownParm) {
8921 auto CTy = ParmTy;
8922 // Is it `T const &`?
8923 bool Ok = !IsMethod;
8924 QualType ExpectedTy;
8925 if (RD)
8926 ExpectedTy = Context.getRecordType(RD);
8927 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8928 CTy = Ref->getPointeeType();
8929 if (RD)
8930 ExpectedTy.addConst();
8931 Ok = true;
8932 }
8933
8934 // Is T a class?
8935 if (!Ok) {
8936 } else if (RD) {
8937 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8938 Ok = false;
8939 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8940 RD = cast<CXXRecordDecl>(CRD);
8941 } else {
8942 Ok = false;
8943 }
8944
8945 if (Ok) {
8946 KnownParm = Param;
8947 } else {
8948 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8949 // corresponding defaulted 'operator<=>' already.
8950 if (!FD->isImplicit()) {
8951 if (RD) {
8952 QualType PlainTy = Context.getRecordType(RD);
8953 QualType RefTy =
8955 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8956 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8957 << Param->getSourceRange();
8958 } else {
8959 assert(!IsMethod && "should know expected type for method");
8960 Diag(FD->getLocation(),
8961 diag::err_defaulted_comparison_param_unknown)
8962 << int(DCK) << ParmTy << Param->getSourceRange();
8963 }
8964 }
8965 return true;
8966 }
8967 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8968 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8969 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8970 << ParmTy << Param->getSourceRange();
8971 return true;
8972 }
8973 }
8974
8975 assert(RD && "must have determined class");
8976 if (IsMethod) {
8977 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8978 // In-class, must be a friend decl.
8979 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8980 } else {
8981 // Out of class, require the defaulted comparison to be a friend (of a
8982 // complete type).
8984 diag::err_defaulted_comparison_not_friend, int(DCK),
8985 int(1)))
8986 return true;
8987
8988 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8989 return FD->getCanonicalDecl() ==
8990 F->getFriendDecl()->getCanonicalDecl();
8991 })) {
8992 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8993 << int(DCK) << int(0) << RD;
8994 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8995 return true;
8996 }
8997 }
8998
8999 // C++2a [class.eq]p1, [class.rel]p1:
9000 // A [defaulted comparison other than <=>] shall have a declared return
9001 // type bool.
9005 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9006 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9007 << FD->getReturnTypeSourceRange();
9008 return true;
9009 }
9010 // C++2a [class.spaceship]p2 [P2002R0]:
9011 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9012 // R shall not contain a placeholder type.
9013 if (QualType RT = FD->getDeclaredReturnType();
9015 RT->getContainedDeducedType() &&
9017 RT->getContainedAutoType()->isConstrained())) {
9018 Diag(FD->getLocation(),
9019 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9020 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9021 << FD->getReturnTypeSourceRange();
9022 return true;
9023 }
9024
9025 // For a defaulted function in a dependent class, defer all remaining checks
9026 // until instantiation.
9027 if (RD->isDependentType())
9028 return false;
9029
9030 // Determine whether the function should be defined as deleted.
9031 DefaultedComparisonInfo Info =
9032 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9033
9034 bool First = FD == FD->getCanonicalDecl();
9035
9036 if (!First) {
9037 if (Info.Deleted) {
9038 // C++11 [dcl.fct.def.default]p4:
9039 // [For a] user-provided explicitly-defaulted function [...] if such a
9040 // function is implicitly defined as deleted, the program is ill-formed.
9041 //
9042 // This is really just a consequence of the general rule that you can
9043 // only delete a function on its first declaration.
9044 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9045 << FD->isImplicit() << (int)DCK;
9046 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9047 DefaultedComparisonAnalyzer::ExplainDeleted)
9048 .visit();
9049 return true;
9050 }
9051 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9052 // C++20 [class.compare.default]p1:
9053 // [...] A definition of a comparison operator as defaulted that appears
9054 // in a class shall be the first declaration of that function.
9055 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9056 << (int)DCK;
9058 diag::note_previous_declaration);
9059 return true;
9060 }
9061 }
9062
9063 // If we want to delete the function, then do so; there's nothing else to
9064 // check in that case.
9065 if (Info.Deleted) {
9066 SetDeclDeleted(FD, FD->getLocation());
9067 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9068 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9069 << (int)DCK;
9070 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9071 DefaultedComparisonAnalyzer::ExplainDeleted)
9072 .visit();
9073 if (FD->getDefaultLoc().isValid())
9074 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9075 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9076 }
9077 return false;
9078 }
9079
9080 // C++2a [class.spaceship]p2:
9081 // The return type is deduced as the common comparison type of R0, R1, ...
9085 if (RetLoc.isInvalid())
9086 RetLoc = FD->getBeginLoc();
9087 // FIXME: Should we really care whether we have the complete type and the
9088 // 'enumerator' constants here? A forward declaration seems sufficient.
9090 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9091 if (Cat.isNull())
9092 return true;
9094 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9095 }
9096
9097 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9098 // An explicitly-defaulted function that is not defined as deleted may be
9099 // declared constexpr or consteval only if it is constexpr-compatible.
9100 // C++2a [class.compare.default]p3 [P2002R0]:
9101 // A defaulted comparison function is constexpr-compatible if it satisfies
9102 // the requirements for a constexpr function [...]
9103 // The only relevant requirements are that the parameter and return types are
9104 // literal types. The remaining conditions are checked by the analyzer.
9105 //
9106 // We support P2448R2 in language modes earlier than C++23 as an extension.
9107 // The concept of constexpr-compatible was removed.
9108 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9109 // A function explicitly defaulted on its first declaration is implicitly
9110 // inline, and is implicitly constexpr if it is constexpr-suitable.
9111 // C++23 [dcl.constexpr]p3
9112 // A function is constexpr-suitable if
9113 // - it is not a coroutine, and
9114 // - if the function is a constructor or destructor, its class does not
9115 // have any virtual base classes.
9116 if (FD->isConstexpr()) {
9117 if (!getLangOpts().CPlusPlus23 &&
9120 !Info.Constexpr) {
9121 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9122 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9123 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9124 DefaultedComparisonAnalyzer::ExplainConstexpr)
9125 .visit();
9126 }
9127 }
9128
9129 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9130 // If a constexpr-compatible function is explicitly defaulted on its first
9131 // declaration, it is implicitly considered to be constexpr.
9132 // FIXME: Only applying this to the first declaration seems problematic, as
9133 // simple reorderings can affect the meaning of the program.
9134 if (First && !FD->isConstexpr() && Info.Constexpr)
9136
9137 // C++2a [except.spec]p3:
9138 // If a declaration of a function does not have a noexcept-specifier
9139 // [and] is defaulted on its first declaration, [...] the exception
9140 // specification is as specified below
9141 if (FD->getExceptionSpecType() == EST_None) {
9142 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9143 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9145 EPI.ExceptionSpec.SourceDecl = FD;
9146 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9147 FPT->getParamTypes(), EPI));
9148 }
9149
9150 return false;
9151}
9152
9154 FunctionDecl *Spaceship) {
9157 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9158 Ctx.Entity = Spaceship;
9160
9161 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9162 EqualEqual->setImplicit();
9163
9165}
9166
9169 assert(FD->isDefaulted() && !FD->isDeleted() &&
9171 if (FD->willHaveBody() || FD->isInvalidDecl())
9172 return;
9173
9175
9176 // Add a context note for diagnostics produced after this point.
9177 Scope.addContextNote(UseLoc);
9178
9179 {
9180 // Build and set up the function body.
9181 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9182 // the type of the class being compared.
9183 auto PT = FD->getParamDecl(0)->getType();
9184 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9185 SourceLocation BodyLoc =
9186 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9187 StmtResult Body =
9188 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9189 if (Body.isInvalid()) {
9190 FD->setInvalidDecl();
9191 return;
9192 }
9193 FD->setBody(Body.get());
9194 FD->markUsed(Context);
9195 }
9196
9197 // The exception specification is needed because we are defining the
9198 // function. Note that this will reuse the body we just built.
9200
9202 L->CompletedImplicitDefinition(FD);
9203}
9204
9207 FunctionDecl *FD,
9209 ComputingExceptionSpec CES(S, FD, Loc);
9211
9212 if (FD->isInvalidDecl())
9213 return ExceptSpec;
9214
9215 // The common case is that we just defined the comparison function. In that
9216 // case, just look at whether the body can throw.
9217 if (FD->hasBody()) {
9218 ExceptSpec.CalledStmt(FD->getBody());
9219 } else {
9220 // Otherwise, build a body so we can check it. This should ideally only
9221 // happen when we're not actually marking the function referenced. (This is
9222 // only really important for efficiency: we don't want to build and throw
9223 // away bodies for comparison functions more than we strictly need to.)
9224
9225 // Pretend to synthesize the function body in an unevaluated context.
9226 // Note that we can't actually just go ahead and define the function here:
9227 // we are not permitted to mark its callees as referenced.
9231
9232 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9233 SourceLocation BodyLoc =
9234 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9235 StmtResult Body =
9236 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9237 if (!Body.isInvalid())
9238 ExceptSpec.CalledStmt(Body.get());
9239
9240 // FIXME: Can we hold onto this body and just transform it to potentially
9241 // evaluated when we're asked to define the function rather than rebuilding
9242 // it? Either that, or we should only build the bits of the body that we
9243 // need (the expressions, not the statements).
9244 }
9245
9246 return ExceptSpec;
9247}
9248
9250 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9252
9253 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9255
9256 // Perform any deferred checking of exception specifications for virtual
9257 // destructors.
9258 for (auto &Check : Overriding)
9259 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9260
9261 // Perform any deferred checking of exception specifications for befriended
9262 // special members.
9263 for (auto &Check : Equivalent)
9264 CheckEquivalentExceptionSpec(Check.second, Check.first);
9265}
9266
9267namespace {
9268/// CRTP base class for visiting operations performed by a special member
9269/// function (or inherited constructor).
9270template<typename Derived>
9271struct SpecialMemberVisitor {
9272 Sema &S;
9273 CXXMethodDecl *MD;
9276
9277 // Properties of the special member, computed for convenience.
9278 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9279
9280 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9282 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9283 switch (CSM) {
9287 IsConstructor = true;
9288 break;
9291 IsAssignment = true;
9292 break;
9294 break;
9295 case Sema::CXXInvalid:
9296 llvm_unreachable("invalid special member kind");
9297 }
9298
9299 if (MD->getNumExplicitParams()) {
9300 if (const ReferenceType *RT =
9302 ConstArg = RT->getPointeeType().isConstQualified();
9303 }
9304 }
9305
9306 Derived &getDerived() { return static_cast<Derived&>(*this); }
9307
9308 /// Is this a "move" special member?
9309 bool isMove() const {
9310 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9311 }
9312
9313 /// Look up the corresponding special member in the given class.
9315 unsigned Quals, bool IsMutable) {
9316 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9317 ConstArg && !IsMutable);
9318 }
9319
9320 /// Look up the constructor for the specified base class to see if it's
9321 /// overridden due to this being an inherited constructor.
9322 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9323 if (!ICI)
9324 return {};
9325 assert(CSM == Sema::CXXDefaultConstructor);
9326 auto *BaseCtor =
9327 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9328 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9329 return MD;
9330 return {};
9331 }
9332
9333 /// A base or member subobject.
9334 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9335
9336 /// Get the location to use for a subobject in diagnostics.
9337 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9338 // FIXME: For an indirect virtual base, the direct base leading to
9339 // the indirect virtual base would be a more useful choice.
9340 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9341 return B->getBaseTypeLoc();
9342 else
9343 return Subobj.get<FieldDecl*>()->getLocation();
9344 }
9345
9346 enum BasesToVisit {
9347 /// Visit all non-virtual (direct) bases.
9348 VisitNonVirtualBases,
9349 /// Visit all direct bases, virtual or not.
9350 VisitDirectBases,
9351 /// Visit all non-virtual bases, and all virtual bases if the class
9352 /// is not abstract.
9353 VisitPotentiallyConstructedBases,
9354 /// Visit all direct or virtual bases.
9355 VisitAllBases
9356 };
9357
9358 // Visit the bases and members of the class.
9359 bool visit(BasesToVisit Bases) {
9360 CXXRecordDecl *RD = MD->getParent();
9361
9362 if (Bases == VisitPotentiallyConstructedBases)
9363 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9364
9365 for (auto &B : RD->bases())
9366 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9367 getDerived().visitBase(&B))
9368 return true;
9369
9370 if (Bases == VisitAllBases)
9371 for (auto &B : RD->vbases())
9372 if (getDerived().visitBase(&B))
9373 return true;
9374
9375 for (auto *F : RD->fields())
9376 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9377 getDerived().visitField(F))
9378 return true;
9379
9380 return false;
9381 }
9382};
9383}
9384
9385namespace {
9386struct SpecialMemberDeletionInfo
9387 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9388 bool Diagnose;
9389
9390 SourceLocation Loc;
9391
9392 bool AllFieldsAreConst;
9393
9394 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9396 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9397 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9398 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9399
9400 bool inUnion() const { return MD->getParent()->isUnion(); }
9401
9402 Sema::CXXSpecialMember getEffectiveCSM() {
9403 return ICI ? Sema::CXXInvalid : CSM;
9404 }
9405
9406 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9407
9408 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9409 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9410
9411 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9412 bool shouldDeleteForField(FieldDecl *FD);
9413 bool shouldDeleteForAllConstMembers();
9414
9415 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9416 unsigned Quals);
9417 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9419 bool IsDtorCallInCtor);
9420
9421 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9422};
9423}
9424
9425/// Is the given special member inaccessible when used on the given
9426/// sub-object.
9427bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9428 CXXMethodDecl *target) {
9429 /// If we're operating on a base class, the object type is the
9430 /// type of this special member.
9431 QualType objectTy;
9432 AccessSpecifier access = target->getAccess();
9433 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9434 objectTy = S.Context.getTypeDeclType(MD->getParent());
9435 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9436
9437 // If we're operating on a field, the object type is the type of the field.
9438 } else {
9439 objectTy = S.Context.getTypeDeclType(target->getParent());
9440 }
9441
9443 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9444}
9445
9446/// Check whether we should delete a special member due to the implicit
9447/// definition containing a call to a special member of a subobject.
9448bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9449 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9450 bool IsDtorCallInCtor) {
9451 CXXMethodDecl *Decl = SMOR.getMethod();
9452 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9453
9454 int DiagKind = -1;
9455
9457 DiagKind = !Decl ? 0 : 1;
9459 DiagKind = 2;
9460 else if (!isAccessible(Subobj, Decl))
9461 DiagKind = 3;
9462 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9463 !Decl->isTrivial()) {
9464 // A member of a union must have a trivial corresponding special member.
9465 // As a weird special case, a destructor call from a union's constructor
9466 // must be accessible and non-deleted, but need not be trivial. Such a
9467 // destructor is never actually called, but is semantically checked as
9468 // if it were.
9469 if (CSM == Sema::CXXDefaultConstructor) {
9470 // [class.default.ctor]p2:
9471 // A defaulted default constructor for class X is defined as deleted if
9472 // - X is a union that has a variant member with a non-trivial default
9473 // constructor and no variant member of X has a default member
9474 // initializer
9475 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9476 if (!RD->hasInClassInitializer())
9477 DiagKind = 4;
9478 } else {
9479 DiagKind = 4;
9480 }
9481 }
9482
9483 if (DiagKind == -1)
9484 return false;
9485
9486 if (Diagnose) {
9487 if (Field) {
9488 S.Diag(Field->getLocation(),
9489 diag::note_deleted_special_member_class_subobject)
9490 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9491 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9492 } else {
9493 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9494 S.Diag(Base->getBeginLoc(),
9495 diag::note_deleted_special_member_class_subobject)
9496 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9497 << Base->getType() << DiagKind << IsDtorCallInCtor
9498 << /*IsObjCPtr*/false;
9499 }
9500
9501 if (DiagKind == 1)
9503 // FIXME: Explain inaccessibility if DiagKind == 3.
9504 }
9505
9506 return true;
9507}
9508
9509/// Check whether we should delete a special member function due to having a
9510/// direct or virtual base class or non-static data member of class type M.
9511bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9512 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9513 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9514 bool IsMutable = Field && Field->isMutable();
9515
9516 // C++11 [class.ctor]p5:
9517 // -- any direct or virtual base class, or non-static data member with no
9518 // brace-or-equal-initializer, has class type M (or array thereof) and
9519 // either M has no default constructor or overload resolution as applied
9520 // to M's default constructor results in an ambiguity or in a function
9521 // that is deleted or inaccessible
9522 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9523 // -- a direct or virtual base class B that cannot be copied/moved because
9524 // overload resolution, as applied to B's corresponding special member,
9525 // results in an ambiguity or a function that is deleted or inaccessible
9526 // from the defaulted special member
9527 // C++11 [class.dtor]p5:
9528 // -- any direct or virtual base class [...] has a type with a destructor
9529 // that is deleted or inaccessible
9530 if (!(CSM == Sema::CXXDefaultConstructor &&
9531 Field && Field->hasInClassInitializer()) &&
9532 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9533 false))
9534 return true;
9535
9536 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9537 // -- any direct or virtual base class or non-static data member has a
9538 // type with a destructor that is deleted or inaccessible
9539 if (IsConstructor) {
9542 false, false, false, false, false);
9543 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9544 return true;
9545 }
9546
9547 return false;
9548}
9549
9550bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9551 FieldDecl *FD, QualType FieldType) {
9552 // The defaulted special functions are defined as deleted if this is a variant
9553 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9554 // type under ARC.
9555 if (!FieldType.hasNonTrivialObjCLifetime())
9556 return false;
9557
9558 // Don't make the defaulted default constructor defined as deleted if the
9559 // member has an in-class initializer.
9561 return false;
9562
9563 if (Diagnose) {
9564 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9565 S.Diag(FD->getLocation(),
9566 diag::note_deleted_special_member_class_subobject)
9567 << getEffectiveCSM() << ParentClass << /*IsField*/true
9568 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9569 }
9570
9571 return true;
9572}
9573
9574/// Check whether we should delete a special member function due to the class
9575/// having a particular direct or virtual base class.
9576bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9577 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9578 // If program is correct, BaseClass cannot be null, but if it is, the error
9579 // must be reported elsewhere.
9580 if (!BaseClass)
9581 return false;
9582 // If we have an inheriting constructor, check whether we're calling an
9583 // inherited constructor instead of a default constructor.
9584 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9585 if (auto *BaseCtor = SMOR.getMethod()) {
9586 // Note that we do not check access along this path; other than that,
9587 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9588 // FIXME: Check that the base has a usable destructor! Sink this into
9589 // shouldDeleteForClassSubobject.
9590 if (BaseCtor->isDeleted() && Diagnose) {
9591 S.Diag(Base->getBeginLoc(),
9592 diag::note_deleted_special_member_class_subobject)
9593 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9594 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9595 << /*IsObjCPtr*/false;
9596 S.NoteDeletedFunction(BaseCtor);
9597 }
9598 return BaseCtor->isDeleted();
9599 }
9600 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9601}
9602
9603/// Check whether we should delete a special member function due to the class
9604/// having a particular non-static data member.
9605bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9606 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9607 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9608
9609 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9610 return true;
9611
9612 if (CSM == Sema::CXXDefaultConstructor) {
9613 // For a default constructor, all references must be initialized in-class
9614 // and, if a union, it must have a non-const member.
9615 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9616 if (Diagnose)
9617 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9618 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9619 return true;
9620 }
9621 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9622 // data member of const-qualified type (or array thereof) with no
9623 // brace-or-equal-initializer is not const-default-constructible.
9624 if (!inUnion() && FieldType.isConstQualified() &&
9625 !FD->hasInClassInitializer() &&
9626 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9627 if (Diagnose)
9628 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9629 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9630 return true;
9631 }
9632
9633 if (inUnion() && !FieldType.isConstQualified())
9634 AllFieldsAreConst = false;
9635 } else if (CSM == Sema::CXXCopyConstructor) {
9636 // For a copy constructor, data members must not be of rvalue reference
9637 // type.
9638 if (FieldType->isRValueReferenceType()) {
9639 if (Diagnose)
9640 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9641 << MD->getParent() << FD << FieldType;
9642 return true;
9643 }
9644 } else if (IsAssignment) {
9645 // For an assignment operator, data members must not be of reference type.
9646 if (FieldType->isReferenceType()) {
9647 if (Diagnose)
9648 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9649 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9650 return true;
9651 }
9652 if (!FieldRecord && FieldType.isConstQualified()) {
9653 // C++11 [class.copy]p23:
9654 // -- a non-static data member of const non-class type (or array thereof)
9655 if (Diagnose)
9656 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9657 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9658 return true;
9659 }
9660 }
9661
9662 if (FieldRecord) {
9663 // Some additional restrictions exist on the variant members.
9664 if (!inUnion() && FieldRecord->isUnion() &&
9665 FieldRecord->isAnonymousStructOrUnion()) {
9666 bool AllVariantFieldsAreConst = true;
9667
9668 // FIXME: Handle anonymous unions declared within anonymous unions.
9669 for (auto *UI : FieldRecord->fields()) {
9670 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9671
9672 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9673 return true;
9674
9675 if (!UnionFieldType.isConstQualified())
9676 AllVariantFieldsAreConst = false;
9677
9678 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9679 if (UnionFieldRecord &&
9680 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9681 UnionFieldType.getCVRQualifiers()))
9682 return true;
9683 }
9684
9685 // At least one member in each anonymous union must be non-const
9686 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9687 !FieldRecord->field_empty()) {
9688 if (Diagnose)
9689 S.Diag(FieldRecord->getLocation(),
9690 diag::note_deleted_default_ctor_all_const)
9691 << !!ICI << MD->getParent() << /*anonymous union*/1;
9692 return true;
9693 }
9694
9695 // Don't check the implicit member of the anonymous union type.
9696 // This is technically non-conformant but supported, and we have a
9697 // diagnostic for this elsewhere.
9698 return false;
9699 }
9700
9701 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9702 FieldType.getCVRQualifiers()))
9703 return true;
9704 }
9705
9706 return false;
9707}
9708
9709/// C++11 [class.ctor] p5:
9710/// A defaulted default constructor for a class X is defined as deleted if
9711/// X is a union and all of its variant members are of const-qualified type.
9712bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9713 // This is a silly definition, because it gives an empty union a deleted
9714 // default constructor. Don't do that.
9715 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9716 bool AnyFields = false;
9717 for (auto *F : MD->getParent()->fields())
9718 if ((AnyFields = !F->isUnnamedBitfield()))
9719 break;
9720 if (!AnyFields)
9721 return false;
9722 if (Diagnose)
9723 S.Diag(MD->getParent()->getLocation(),
9724 diag::note_deleted_default_ctor_all_const)
9725 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9726 return true;
9727 }
9728 return false;
9729}
9730
9731/// Determine whether a defaulted special member function should be defined as
9732/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9733/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9736 bool Diagnose) {
9737 if (MD->isInvalidDecl())
9738 return false;
9739 CXXRecordDecl *RD = MD->getParent();
9740 assert(!RD->isDependentType() && "do deletion after instantiation");
9741 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9742 return false;
9743
9744 // C++11 [expr.lambda.prim]p19:
9745 // The closure type associated with a lambda-expression has a
9746 // deleted (8.4.3) default constructor and a deleted copy
9747 // assignment operator.
9748 // C++2a adds back these operators if the lambda has no lambda-capture.
9750 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9751 if (Diagnose)
9752 Diag(RD->getLocation(), diag::note_lambda_decl);
9753 return true;
9754 }
9755
9756 // For an anonymous struct or union, the copy and assignment special members
9757 // will never be used, so skip the check. For an anonymous union declared at
9758 // namespace scope, the constructor and destructor are used.
9759 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9761 return false;
9762
9763 // C++11 [class.copy]p7, p18:
9764 // If the class definition declares a move constructor or move assignment
9765 // operator, an implicitly declared copy constructor or copy assignment
9766 // operator is defined as deleted.
9767 if (MD->isImplicit() &&
9768 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9769 CXXMethodDecl *UserDeclaredMove = nullptr;
9770
9771 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9772 // deletion of the corresponding copy operation, not both copy operations.
9773 // MSVC 2015 has adopted the standards conforming behavior.
9774 bool DeletesOnlyMatchingCopy =
9775 getLangOpts().MSVCCompat &&
9777
9779 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9780 if (!Diagnose) return true;
9781
9782 // Find any user-declared move constructor.
9783 for (auto *I : RD->ctors()) {
9784 if (I->isMoveConstructor()) {
9785 UserDeclaredMove = I;
9786 break;
9787 }
9788 }
9789 assert(UserDeclaredMove);
9790 } else if (RD->hasUserDeclaredMoveAssignment() &&
9791 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9792 if (!Diagnose) return true;
9793
9794 // Find any user-declared move assignment operator.
9795 for (auto *I : RD->methods()) {
9796 if (I->isMoveAssignmentOperator()) {
9797 UserDeclaredMove = I;
9798 break;
9799 }
9800 }
9801 assert(UserDeclaredMove);
9802 }
9803
9804 if (UserDeclaredMove) {
9805 Diag(UserDeclaredMove->getLocation(),
9806 diag::note_deleted_copy_user_declared_move)
9807 << (CSM == CXXCopyAssignment) << RD
9808 << UserDeclaredMove->isMoveAssignmentOperator();
9809 return true;
9810 }
9811 }
9812
9813 // Do access control from the special member function
9814 ContextRAII MethodContext(*this, MD);
9815
9816 // C++11 [class.dtor]p5:
9817 // -- for a virtual destructor, lookup of the non-array deallocation function
9818 // results in an ambiguity or in a function that is deleted or inaccessible
9819 if (CSM == CXXDestructor && MD->isVirtual()) {
9820 FunctionDecl *OperatorDelete = nullptr;
9821 DeclarationName Name =
9823 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9824 OperatorDelete, /*Diagnose*/false)) {
9825 if (Diagnose)
9826 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9827 return true;
9828 }
9829 }
9830
9831 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9832
9833 // Per DR1611, do not consider virtual bases of constructors of abstract
9834 // classes, since we are not going to construct them.
9835 // Per DR1658, do not consider virtual bases of destructors of abstract
9836 // classes either.
9837 // Per DR2180, for assignment operators we only assign (and thus only
9838 // consider) direct bases.
9839 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9840 : SMI.VisitPotentiallyConstructedBases))
9841 return true;
9842
9843 if (SMI.shouldDeleteForAllConstMembers())
9844 return true;
9845
9846 if (getLangOpts().CUDA) {
9847 // We should delete the special member in CUDA mode if target inference
9848 // failed.
9849 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9850 // is treated as certain special member, which may not reflect what special
9851 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9852 // expects CSM to match MD, therefore recalculate CSM.
9853 assert(ICI || CSM == getSpecialMember(MD));
9854 auto RealCSM = CSM;
9855 if (ICI)
9856 RealCSM = getSpecialMember(MD);
9857
9858 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9859 SMI.ConstArg, Diagnose);
9860 }
9861
9862 return false;
9863}
9864
9867 assert(DFK && "not a defaultable function");
9868 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9869
9870 if (DFK.isSpecialMember()) {
9871 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9872 nullptr, /*Diagnose=*/true);
9873 } else {
9874 DefaultedComparisonAnalyzer(
9875 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9876 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9877 .visit();
9878 }
9879}
9880
9881/// Perform lookup for a special member of the specified kind, and determine
9882/// whether it is trivial. If the triviality can be determined without the
9883/// lookup, skip it. This is intended for use when determining whether a
9884/// special member of a containing object is trivial, and thus does not ever
9885/// perform overload resolution for default constructors.
9886///
9887/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9888/// member that was most likely to be intended to be trivial, if any.
9889///
9890/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9891/// determine whether the special member is trivial.
9893 Sema::CXXSpecialMember CSM, unsigned Quals,
9894 bool ConstRHS,
9896 CXXMethodDecl **Selected) {
9897 if (Selected)
9898 *Selected = nullptr;
9899
9900 switch (CSM) {
9901 case Sema::CXXInvalid:
9902 llvm_unreachable("not a special member");
9903
9905 // C++11 [class.ctor]p5:
9906 // A default constructor is trivial if:
9907 // - all the [direct subobjects] have trivial default constructors
9908 //
9909 // Note, no overload resolution is performed in this case.
9911 return true;
9912
9913 if (Selected) {
9914 // If there's a default constructor which could have been trivial, dig it
9915 // out. Otherwise, if there's any user-provided default constructor, point
9916 // to that as an example of why there's not a trivial one.
9917 CXXConstructorDecl *DefCtor = nullptr;
9920 for (auto *CI : RD->ctors()) {
9921 if (!CI->isDefaultConstructor())
9922 continue;
9923 DefCtor = CI;
9924 if (!DefCtor->isUserProvided())
9925 break;
9926 }
9927
9928 *Selected = DefCtor;
9929 }
9930
9931 return false;
9932
9934 // C++11 [class.dtor]p5:
9935 // A destructor is trivial if:
9936 // - all the direct [subobjects] have trivial destructors
9937 if (RD->hasTrivialDestructor() ||
9940 return true;
9941
9942 if (Selected) {
9943 if (RD->needsImplicitDestructor())
9945 *Selected = RD->getDestructor();
9946 }
9947
9948 return false;
9949
9951 // C++11 [class.copy]p12:
9952 // A copy constructor is trivial if:
9953 // - the constructor selected to copy each direct [subobject] is trivial
9954 if (RD->hasTrivialCopyConstructor() ||
9957 if (Quals == Qualifiers::Const)
9958 // We must either select the trivial copy constructor or reach an
9959 // ambiguity; no need to actually perform overload resolution.
9960 return true;
9961 } else if (!Selected) {
9962 return false;
9963 }
9964 // In C++98, we are not supposed to perform overload resolution here, but we
9965 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9966 // cases like B as having a non-trivial copy constructor:
9967 // struct A { template<typename T> A(T&); };
9968 // struct B { mutable A a; };
9969 goto NeedOverloadResolution;
9970
9972 // C++11 [class.copy]p25:
9973 // A copy assignment operator is trivial if:
9974 // - the assignment operator selected to copy each direct [subobject] is
9975 // trivial
9976 if (RD->hasTrivialCopyAssignment()) {
9977 if (Quals == Qualifiers::Const)
9978 return true;
9979 } else if (!Selected) {
9980 return false;
9981 }
9982 // In C++98, we are not supposed to perform overload resolution here, but we
9983 // treat that as a language defect.
9984 goto NeedOverloadResolution;
9985
9988 NeedOverloadResolution:
9990 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9991
9992 // The standard doesn't describe how to behave if the lookup is ambiguous.
9993 // We treat it as not making the member non-trivial, just like the standard
9994 // mandates for the default constructor. This should rarely matter, because
9995 // the member will also be deleted.
9997 return true;
9998
9999 if (!SMOR.getMethod()) {
10000 assert(SMOR.getKind() ==
10002 return false;
10003 }
10004
10005 // We deliberately don't check if we found a deleted special member. We're
10006 // not supposed to!
10007 if (Selected)
10008 *Selected = SMOR.getMethod();
10009
10010 if (TAH == Sema::TAH_ConsiderTrivialABI &&
10012 return SMOR.getMethod()->isTrivialForCall();
10013 return SMOR.getMethod()->isTrivial();
10014 }
10015
10016 llvm_unreachable("unknown special method kind");
10017}
10018
10020 for (auto *CI : RD->ctors())
10021 if (!CI->isImplicit())
10022 return CI;
10023
10024 // Look for constructor templates.
10026 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10027 if (CXXConstructorDecl *CD =
10028 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10029 return CD;
10030 }
10031
10032 return nullptr;
10033}
10034
10035/// The kind of subobject we are checking for triviality. The values of this
10036/// enumeration are used in diagnostics.
10038 /// The subobject is a base class.
10040 /// The subobject is a non-static data member.
10042 /// The object is actually the complete object.
10045
10046/// Check whether the special member selected for a given type would be trivial.
10048 QualType SubType, bool ConstRHS,
10052 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10053 if (!SubRD)
10054 return true;
10055
10056 CXXMethodDecl *Selected;
10057 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10058 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10059 return true;
10060
10061 if (Diagnose) {
10062 if (ConstRHS)
10063 SubType.addConst();
10064
10065 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
10066 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10067 << Kind << SubType.getUnqualifiedType();
10069 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10070 } else if (!Selected)
10071 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10072 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10073 else if (Selected->isUserProvided()) {
10074 if (Kind == TSK_CompleteObject)
10075 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10076 << Kind << SubType.getUnqualifiedType() << CSM;
10077 else {
10078 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10079 << Kind << SubType.getUnqualifiedType() << CSM;
10080 S.Diag(Selected->getLocation(), diag::note_declared_at);
10081 }
10082 } else {
10083 if (Kind != TSK_CompleteObject)
10084 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10085 << Kind << SubType.getUnqualifiedType() << CSM;
10086
10087 // Explain why the defaulted or deleted special member isn't trivial.
10089 Diagnose);
10090 }
10091 }
10092
10093 return false;
10094}
10095
10096/// Check whether the members of a class type allow a special member to be
10097/// trivial.
10100 bool ConstArg,
10102 bool Diagnose) {
10103 for (const auto *FI : RD->fields()) {
10104 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
10105 continue;
10106
10107 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10108
10109 // Pretend anonymous struct or union members are members of this class.
10110 if (FI->isAnonymousStructOrUnion()) {
10111 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10112 CSM, ConstArg, TAH, Diagnose))
10113 return false;
10114 continue;
10115 }
10116
10117 // C++11 [class.ctor]p5:
10118 // A default constructor is trivial if [...]
10119 // -- no non-static data member of its class has a
10120 // brace-or-equal-initializer
10121 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
10122 if (Diagnose)
10123 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10124 << FI;
10125 return false;
10126 }
10127
10128 // Objective C ARC 4.3.5:
10129 // [...] nontrivally ownership-qualified types are [...] not trivially
10130 // default constructible, copy constructible, move constructible, copy
10131 // assignable, move assignable, or destructible [...]
10132 if (FieldType.hasNonTrivialObjCLifetime()) {
10133 if (Diagnose)
10134 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10135 << RD << FieldType.getObjCLifetime();
10136 return false;
10137 }
10138
10139 bool ConstRHS = ConstArg && !FI->isMutable();
10140 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10141 CSM, TSK_Field, TAH, Diagnose))
10142 return false;
10143 }
10144
10145 return true;
10146}
10147
10148/// Diagnose why the specified class does not have a trivial special member of
10149/// the given kind.
10152
10153 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10154 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10156 /*Diagnose*/true);
10157}
10158
10159/// Determine whether a defaulted or deleted special member function is trivial,
10160/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10161/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10163 TrivialABIHandling TAH, bool Diagnose) {
10164 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10165
10166 CXXRecordDecl *RD = MD->getParent();
10167
10168 bool ConstArg = false;
10169
10170 // C++11 [class.copy]p12, p25: [DR1593]
10171 // A [special member] is trivial if [...] its parameter-type-list is
10172 // equivalent to the parameter-type-list of an implicit declaration [...]
10173 switch (CSM) {
10175 case CXXDestructor:
10176 // Trivial default constructors and destructors cannot have parameters.
10177 break;
10178
10179 case CXXCopyConstructor:
10180 case CXXCopyAssignment: {
10181 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10182 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10183
10184 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10185 // if they are not user-provided and their parameter-type-list is equivalent
10186 // to the parameter-type-list of an implicit declaration. This maintains the
10187 // behavior before dr2171 was implemented.
10188 //
10189 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10190 // trivial, if they are not user-provided, regardless of the qualifiers on
10191 // the reference type.
10192 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10194 if (!RT ||
10196 ClangABICompat14)) {
10197 if (Diagnose)
10198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10199 << Param0->getSourceRange() << Param0->getType()
10202 return false;
10203 }
10204
10205 ConstArg = RT->getPointeeType().isConstQualified();
10206 break;
10207 }
10208
10209 case CXXMoveConstructor:
10210 case CXXMoveAssignment: {
10211 // Trivial move operations always have non-cv-qualified parameters.
10212 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10213 const RValueReferenceType *RT =
10214 Param0->getType()->getAs<RValueReferenceType>();
10215 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10216 if (Diagnose)
10217 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10218 << Param0->getSourceRange() << Param0->getType()
10220 return false;
10221 }
10222 break;
10223 }
10224
10225 case CXXInvalid:
10226 llvm_unreachable("not a special member");
10227 }
10228
10229 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10230 if (Diagnose)
10232 diag::note_nontrivial_default_arg)
10234 return false;
10235 }
10236 if (MD->isVariadic()) {
10237 if (Diagnose)
10238 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10239 return false;
10240 }
10241
10242 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10243 // A copy/move [constructor or assignment operator] is trivial if
10244 // -- the [member] selected to copy/move each direct base class subobject
10245 // is trivial
10246 //
10247 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10248 // A [default constructor or destructor] is trivial if
10249 // -- all the direct base classes have trivial [default constructors or
10250 // destructors]
10251 for (const auto &BI : RD->bases())
10252 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10253 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10254 return false;
10255
10256 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10257 // A copy/move [constructor or assignment operator] for a class X is
10258 // trivial if
10259 // -- for each non-static data member of X that is of class type (or array
10260 // thereof), the constructor selected to copy/move that member is
10261 // trivial
10262 //
10263 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10264 // A [default constructor or destructor] is trivial if
10265 // -- for all of the non-static data members of its class that are of class
10266 // type (or array thereof), each such class has a trivial [default
10267 // constructor or destructor]
10268 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10269 return false;
10270
10271 // C++11 [class.dtor]p5:
10272 // A destructor is trivial if [...]
10273 // -- the destructor is not virtual
10274 if (CSM == CXXDestructor && MD->isVirtual()) {
10275 if (Diagnose)
10276 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10277 return false;
10278 }
10279
10280 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10281 // A [special member] for class X is trivial if [...]
10282 // -- class X has no virtual functions and no virtual base classes
10283 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10284 if (!Diagnose)
10285 return false;
10286
10287 if (RD->getNumVBases()) {
10288 // Check for virtual bases. We already know that the corresponding
10289 // member in all bases is trivial, so vbases must all be direct.
10290 CXXBaseSpecifier &BS = *RD->vbases_begin();
10291 assert(BS.isVirtual());
10292 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10293 return false;
10294 }
10295
10296 // Must have a virtual method.
10297 for (const auto *MI : RD->methods()) {
10298 if (MI->isVirtual()) {
10299 SourceLocation MLoc = MI->getBeginLoc();
10300 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10301 return false;
10302 }
10303 }
10304
10305 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10306 }
10307
10308 // Looks like it's trivial!
10309 return true;
10310}
10311
10312namespace {
10313struct FindHiddenVirtualMethod {
10314 Sema *S;
10315 CXXMethodDecl *Method;
10316 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10317 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10318
10319private:
10320 /// Check whether any most overridden method from MD in Methods
10321 static bool CheckMostOverridenMethods(
10322 const CXXMethodDecl *MD,
10323 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10324 if (MD->size_overridden_methods() == 0)
10325 return Methods.count(MD->getCanonicalDecl());
10326 for (const CXXMethodDecl *O : MD->overridden_methods())
10327 if (CheckMostOverridenMethods(O, Methods))
10328 return true;
10329 return false;
10330 }
10331
10332public:
10333 /// Member lookup function that determines whether a given C++
10334 /// method overloads virtual methods in a base class without overriding any,
10335 /// to be used with CXXRecordDecl::lookupInBases().
10336 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10337 RecordDecl *BaseRecord =
10338 Specifier->getType()->castAs<RecordType>()->getDecl();
10339
10340 DeclarationName Name = Method->getDeclName();
10341 assert(Name.getNameKind() == DeclarationName::Identifier);
10342
10343 bool foundSameNameMethod = false;
10344 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10345 for (Path.Decls = BaseRecord->lookup(Name).begin();
10346 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10347 NamedDecl *D = *Path.Decls;
10348 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10349 MD = MD->getCanonicalDecl();
10350 foundSameNameMethod = true;
10351 // Interested only in hidden virtual methods.
10352 if (!MD->isVirtual())
10353 continue;
10354 // If the method we are checking overrides a method from its base
10355 // don't warn about the other overloaded methods. Clang deviates from
10356 // GCC by only diagnosing overloads of inherited virtual functions that
10357 // do not override any other virtual functions in the base. GCC's
10358 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10359 // function from a base class. These cases may be better served by a
10360 // warning (not specific to virtual functions) on call sites when the
10361 // call would select a different function from the base class, were it
10362 // visible.
10363 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10364 if (!S->IsOverload(Method, MD, false))
10365 return true;
10366 // Collect the overload only if its hidden.
10367 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10368 overloadedMethods.push_back(MD);
10369 }
10370 }
10371
10372 if (foundSameNameMethod)
10373 OverloadedMethods.append(overloadedMethods.begin(),
10374 overloadedMethods.end());
10375 return foundSameNameMethod;
10376 }
10377};
10378} // end anonymous namespace
10379
10380/// Add the most overridden methods from MD to Methods
10382 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10383 if (MD->size_overridden_methods() == 0)
10384 Methods.insert(MD->getCanonicalDecl());
10385 else
10386 for (const CXXMethodDecl *O : MD->overridden_methods())
10387 AddMostOverridenMethods(O, Methods);
10388}
10389
10390/// Check if a method overloads virtual methods in a base class without
10391/// overriding any.
10393 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10394 if (!MD->getDeclName().isIdentifier())
10395 return;
10396
10397 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10398 /*bool RecordPaths=*/false,
10399 /*bool DetectVirtual=*/false);
10400 FindHiddenVirtualMethod FHVM;
10401 FHVM.Method = MD;
10402 FHVM.S = this;
10403
10404 // Keep the base methods that were overridden or introduced in the subclass
10405 // by 'using' in a set. A base method not in this set is hidden.
10406 CXXRecordDecl *DC = MD->getParent();
10408 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10409 NamedDecl *ND = *I;
10410 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10411 ND = shad->getTargetDecl();
10412 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10413 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10414 }
10415
10416 if (DC->lookupInBases(FHVM, Paths))
10417 OverloadedMethods = FHVM.OverloadedMethods;
10418}
10419
10421 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10422 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10423 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10425 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10426 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10427 Diag(overloadedMD->getLocation(), PD);
10428 }
10429}
10430
10431/// Diagnose methods which overload virtual methods in a base class
10432/// without overriding any.
10434 if (MD->isInvalidDecl())
10435 return;
10436
10437 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10438 return;
10439
10440 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10441 FindHiddenVirtualMethods(MD, OverloadedMethods);
10442 if (!OverloadedMethods.empty()) {
10443 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10444 << MD << (OverloadedMethods.size() > 1);
10445
10446 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10447 }
10448}
10449
10451 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10452 // No diagnostics if this is a template instantiation.
10454 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10455 diag::ext_cannot_use_trivial_abi) << &RD;
10456 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10457 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10458 }
10459 RD.dropAttr<TrivialABIAttr>();
10460 };
10461
10462 // Ill-formed if the copy and move constructors are deleted.
10463 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10464 // If the type is dependent, then assume it might have
10465 // implicit copy or move ctor because we won't know yet at this point.
10466 if (RD.isDependentType())
10467 return true;
10470 return true;
10473 return true;
10474 for (const CXXConstructorDecl *CD : RD.ctors())
10475 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10476 return true;
10477 return false;
10478 };
10479
10480 if (!HasNonDeletedCopyOrMoveConstructor()) {
10481 PrintDiagAndRemoveAttr(0);
10482 return;
10483 }
10484
10485 // Ill-formed if the struct has virtual functions.
10486 if (RD.isPolymorphic()) {
10487 PrintDiagAndRemoveAttr(1);
10488 return;
10489 }
10490
10491 for (const auto &B : RD.bases()) {
10492 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10493 // virtual base.
10494 if (!B.getType()->isDependentType() &&
10495 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10496 PrintDiagAndRemoveAttr(2);
10497 return;
10498 }
10499
10500 if (B.isVirtual()) {
10501 PrintDiagAndRemoveAttr(3);
10502 return;
10503 }
10504 }
10505
10506 for (const auto *FD : RD.fields()) {
10507 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10508 // non-trivial for the purpose of calls.
10509 QualType FT = FD->getType();
10511 PrintDiagAndRemoveAttr(4);
10512 return;
10513 }
10514
10515 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10516 if (!RT->isDependentType() &&
10517 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10518 PrintDiagAndRemoveAttr(5);
10519 return;
10520 }
10521 }
10522}
10523
10526 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10527 if (!TagDecl)
10528 return;
10529
10531
10532 for (const ParsedAttr &AL : AttrList) {
10533 if (AL.getKind() != ParsedAttr::AT_Visibility)
10534 continue;
10535 AL.setInvalid();
10536 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10537 }
10538
10539 ActOnFields(S, RLoc, TagDecl,
10541 // strict aliasing violation!
10542 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10543 FieldCollector->getCurNumFields()),
10544 LBrac, RBrac, AttrList);
10545
10546 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10547}
10548
10549/// Find the equality comparison functions that should be implicitly declared
10550/// in a given class definition, per C++2a [class.compare.default]p3.
10552 ASTContext &Ctx, CXXRecordDecl *RD,
10554 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10555 if (!RD->lookup(EqEq).empty())
10556 // Member operator== explicitly declared: no implicit operator==s.
10557 return;
10558
10559 // Traverse friends looking for an '==' or a '<=>'.
10560 for (FriendDecl *Friend : RD->friends()) {
10561 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10562 if (!FD) continue;
10563
10564 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10565 // Friend operator== explicitly declared: no implicit operator==s.
10566 Spaceships.clear();
10567 return;
10568 }
10569
10570 if (FD->getOverloadedOperator() == OO_Spaceship &&
10572 Spaceships.push_back(FD);
10573 }
10574
10575 // Look for members named 'operator<=>'.
10576 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10577 for (NamedDecl *ND : RD->lookup(Cmp)) {
10578 // Note that we could find a non-function here (either a function template
10579 // or a using-declaration). Neither case results in an implicit
10580 // 'operator=='.
10581 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10582 if (FD->isExplicitlyDefaulted())
10583 Spaceships.push_back(FD);
10584 }
10585}
10586
10587/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10588/// special functions, such as the default constructor, copy
10589/// constructor, or destructor, to the given C++ class (C++
10590/// [special]p1). This routine can only be executed just before the
10591/// definition of the class is complete.
10593 // Don't add implicit special members to templated classes.
10594 // FIXME: This means unqualified lookups for 'operator=' within a class
10595 // template don't work properly.
10596 if (!ClassDecl->isDependentType()) {
10597 if (ClassDecl->needsImplicitDefaultConstructor()) {
10599
10600 if (ClassDecl->hasInheritedConstructor())
10602 }
10603
10604 if (ClassDecl->needsImplicitCopyConstructor()) {
10606
10607 // If the properties or semantics of the copy constructor couldn't be
10608 // determined while the class was being declared, force a declaration
10609 // of it now.
10611 ClassDecl->hasInheritedConstructor())
10613 // For the MS ABI we need to know whether the copy ctor is deleted. A
10614 // prerequisite for deleting the implicit copy ctor is that the class has
10615 // a move ctor or move assignment that is either user-declared or whose
10616 // semantics are inherited from a subobject. FIXME: We should provide a
10617 // more direct way for CodeGen to ask whether the constructor was deleted.
10618 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10619 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10621 ClassDecl->hasUserDeclaredMoveAssignment() ||
10624 }
10625
10626 if (getLangOpts().CPlusPlus11 &&
10627 ClassDecl->needsImplicitMoveConstructor()) {
10629
10631 ClassDecl->hasInheritedConstructor())
10633 }
10634
10635 if (ClassDecl->needsImplicitCopyAssignment()) {
10637
10638 // If we have a dynamic class, then the copy assignment operator may be
10639 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10640 // it shows up in the right place in the vtable and that we diagnose
10641 // problems with the implicit exception specification.
10642 if (ClassDecl->isDynamicClass() ||
10644 ClassDecl->hasInheritedAssignment())
10646 }
10647
10648 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10650
10651 // Likewise for the move assignment operator.
10652 if (ClassDecl->isDynamicClass() ||
10654 ClassDecl->hasInheritedAssignment())
10656 }
10657
10658 if (ClassDecl->needsImplicitDestructor()) {
10660
10661 // If we have a dynamic class, then the destructor may be virtual, so we
10662 // have to declare the destructor immediately. This ensures that, e.g., it
10663 // shows up in the right place in the vtable and that we diagnose problems
10664 // with the implicit exception specification.
10665 if (ClassDecl->isDynamicClass() ||
10667 DeclareImplicitDestructor(ClassDecl);
10668 }
10669 }
10670
10671 // C++2a [class.compare.default]p3:
10672 // If the member-specification does not explicitly declare any member or
10673 // friend named operator==, an == operator function is declared implicitly
10674 // for each defaulted three-way comparison operator function defined in
10675 // the member-specification
10676 // FIXME: Consider doing this lazily.
10677 // We do this during the initial parse for a class template, not during
10678 // instantiation, so that we can handle unqualified lookups for 'operator=='
10679 // when parsing the template.
10681 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10683 DefaultedSpaceships);
10684 for (auto *FD : DefaultedSpaceships)
10685 DeclareImplicitEqualityComparison(ClassDecl, FD);
10686 }
10687}
10688
10689unsigned
10691 llvm::function_ref<Scope *()> EnterScope) {
10692 if (!D)
10693 return 0;
10695
10696 // In order to get name lookup right, reenter template scopes in order from
10697 // outermost to innermost.
10699 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10700
10701 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10702 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10703 ParameterLists.push_back(DD->getTemplateParameterList(i));
10704
10705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10706 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10707 ParameterLists.push_back(FTD->getTemplateParameters());
10708 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10709 LookupDC = VD->getDeclContext();
10710
10712 ParameterLists.push_back(VTD->getTemplateParameters());
10713 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10714 ParameterLists.push_back(PSD->getTemplateParameters());
10715 }
10716 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10717 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10718 ParameterLists.push_back(TD->getTemplateParameterList(i));
10719
10720 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10722 ParameterLists.push_back(CTD->getTemplateParameters());
10723 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10724 ParameterLists.push_back(PSD->getTemplateParameters());
10725 }
10726 }
10727 // FIXME: Alias declarations and concepts.
10728
10729 unsigned Count = 0;
10730 Scope *InnermostTemplateScope = nullptr;
10731 for (TemplateParameterList *Params : ParameterLists) {
10732 // Ignore explicit specializations; they don't contribute to the template
10733 // depth.
10734 if (Params->size() == 0)
10735 continue;
10736
10737 InnermostTemplateScope = EnterScope();
10738 for (NamedDecl *Param : *Params) {
10739 if (Param->getDeclName()) {
10740 InnermostTemplateScope->AddDecl(Param);
10741 IdResolver.AddDecl(Param);
10742 }
10743 }
10744 ++Count;
10745 }
10746
10747 // Associate the new template scopes with the corresponding entities.
10748 if (InnermostTemplateScope) {
10749 assert(LookupDC && "no enclosing DeclContext for template lookup");
10750 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10751 }
10752
10753 return Count;
10754}
10755
10757 if (!RecordD) return;
10758 AdjustDeclIfTemplate(RecordD);
10759 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10761}
10762
10764 if (!RecordD) return;
10766}
10767
10768/// This is used to implement the constant expression evaluation part of the
10769/// attribute enable_if extension. There is nothing in standard C++ which would
10770/// require reentering parameters.
10772 if (!Param)
10773 return;
10774
10775 S->AddDecl(Param);
10776 if (Param->getDeclName())
10777 IdResolver.AddDecl(Param);
10778}
10779
10780/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10781/// parsing a top-level (non-nested) C++ class, and we are now
10782/// parsing those parts of the given Method declaration that could
10783/// not be parsed earlier (C++ [class.mem]p2), such as default
10784/// arguments. This action should enter the scope of the given
10785/// Method declaration as if we had just parsed the qualified method
10786/// name. However, it should not bring the parameters into scope;
10787/// that will be performed by ActOnDelayedCXXMethodParameter.
10789}
10790
10791/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10792/// C++ method declaration. We're (re-)introducing the given
10793/// function parameter into scope for use in parsing later parts of
10794/// the method declaration. For example, we could see an
10795/// ActOnParamDefaultArgument event for this parameter.
10797 if (!ParamD)
10798 return;
10799
10800 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10801
10802 S->AddDecl(Param);
10803 if (Param->getDeclName())
10804 IdResolver.AddDecl(Param);
10805}
10806
10807/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10808/// processing the delayed method declaration for Method. The method
10809/// declaration is now considered finished. There may be a separate
10810/// ActOnStartOfFunctionDef action later (not necessarily
10811/// immediately!) for this method, if it was also defined inside the
10812/// class body.
10814 if (!MethodD)
10815 return;
10816
10817 AdjustDeclIfTemplate(MethodD);
10818
10819 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10820
10821 // Now that we have our default arguments, check the constructor
10822 // again. It could produce additional diagnostics or affect whether
10823 // the class has implicitly-declared destructors, among other
10824 // things.
10825 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10826 CheckConstructor(Constructor);
10827
10828 // Check the default arguments, which we may have added.
10829 if (!Method->isInvalidDecl())
10831}
10832
10833// Emit the given diagnostic for each non-address-space qualifier.
10834// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10835static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10837 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10838 bool DiagOccured = false;
10840 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10841 SourceLocation SL) {
10842 // This diagnostic should be emitted on any qualifier except an addr
10843 // space qualifier. However, forEachQualifier currently doesn't visit
10844 // addr space qualifiers, so there's no way to write this condition
10845 // right now; we just diagnose on everything.
10846 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10847 DiagOccured = true;
10848 });
10849 if (DiagOccured)
10850 D.setInvalidType();
10851 }
10852}
10853
10854/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10855/// the well-formedness of the constructor declarator @p D with type @p
10856/// R. If there are any errors in the declarator, this routine will
10857/// emit diagnostics and set the invalid bit to true. In any case, the type
10858/// will be updated to reflect a well-formed type for the constructor and
10859/// returned.
10861 StorageClass &SC) {
10862 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10863
10864 // C++ [class.ctor]p3:
10865 // A constructor shall not be virtual (10.3) or static (9.4). A
10866 // constructor can be invoked for a const, volatile or const
10867 // volatile object. A constructor shall not be declared const,
10868 // volatile, or const volatile (9.3.2).
10869 if (isVirtual) {
10870 if (!D.isInvalidType())
10871 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10872 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10874 D.setInvalidType();
10875 }
10876 if (SC == SC_Static) {
10877 if (!D.isInvalidType())
10878 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10879 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10881 D.setInvalidType();
10882 SC = SC_None;
10883 }
10884
10885 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10887 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10891 D.setInvalidType();
10892 }
10893
10894 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10895
10896 // C++0x [class.ctor]p4:
10897 // A constructor shall not be declared with a ref-qualifier.
10899 if (FTI.hasRefQualifier()) {
10900 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10903 D.setInvalidType();
10904 }
10905
10906 // Rebuild the function type "R" without any type qualifiers (in
10907 // case any of the errors above fired) and with "void" as the
10908 // return type, since constructors don't have return types.
10909 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10910 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10911 return R;
10912
10914 EPI.TypeQuals = Qualifiers();
10915 EPI.RefQualifier = RQ_None;
10916
10917 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10918}
10919
10920/// CheckConstructor - Checks a fully-formed constructor for
10921/// well-formedness, issuing any diagnostics required. Returns true if
10922/// the constructor declarator is invalid.
10924 CXXRecordDecl *ClassDecl
10925 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10926 if (!ClassDecl)
10927 return Constructor->setInvalidDecl();
10928
10929 // C++ [class.copy]p3:
10930 // A declaration of a constructor for a class X is ill-formed if
10931 // its first parameter is of type (optionally cv-qualified) X and
10932 // either there are no other parameters or else all other
10933 // parameters have default arguments.
10934 if (!Constructor->isInvalidDecl() &&
10935 Constructor->hasOneParamOrDefaultArgs() &&
10936 Constructor->getTemplateSpecializationKind() !=
10938 QualType ParamType = Constructor->getParamDecl(0)->getType();
10939 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10940 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10941 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10942 const char *ConstRef
10943 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10944 : " const &";
10945 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10946 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10947
10948 // FIXME: Rather that making the constructor invalid, we should endeavor
10949 // to fix the type.
10950 Constructor->setInvalidDecl();
10951 }
10952 }
10953}
10954
10955/// CheckDestructor - Checks a fully-formed destructor definition for
10956/// well-formedness, issuing any diagnostics required. Returns true
10957/// on error.
10959 CXXRecordDecl *RD = Destructor->getParent();
10960
10961 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10962 SourceLocation Loc;
10963
10964 if (!Destructor->isImplicit())
10965 Loc = Destructor->getLocation();
10966 else
10967 Loc = RD->getLocation();
10968
10969 // If we have a virtual destructor, look up the deallocation function
10970 if (FunctionDecl *OperatorDelete =
10972 Expr *ThisArg = nullptr;
10973
10974 // If the notional 'delete this' expression requires a non-trivial
10975 // conversion from 'this' to the type of a destroying operator delete's
10976 // first parameter, perform that conversion now.
10977 if (OperatorDelete->isDestroyingOperatorDelete()) {
10978 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10979 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10980 // C++ [class.dtor]p13:
10981 // ... as if for the expression 'delete this' appearing in a
10982 // non-virtual destructor of the destructor's class.
10983 ContextRAII SwitchContext(*this, Destructor);
10984 ExprResult This =
10985 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10986 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10987 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10988 if (This.isInvalid()) {
10989 // FIXME: Register this as a context note so that it comes out
10990 // in the right order.
10991 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10992 return true;
10993 }
10994 ThisArg = This.get();
10995 }
10996 }
10997
10998 DiagnoseUseOfDecl(OperatorDelete, Loc);
10999 MarkFunctionReferenced(Loc, OperatorDelete);
11000 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11001 }
11002 }
11003
11004 return false;
11005}
11006
11007/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
11008/// the well-formednes of the destructor declarator @p D with type @p
11009/// R. If there are any errors in the declarator, this routine will
11010/// emit diagnostics and set the declarator to invalid. Even if this happens,
11011/// will be updated to reflect a well-formed type for the destructor and
11012/// returned.
11014 StorageClass& SC) {
11015 // C++ [class.dtor]p1:
11016 // [...] A typedef-name that names a class is a class-name
11017 // (7.1.3); however, a typedef-name that names a class shall not
11018 // be used as the identifier in the declarator for a destructor
11019 // declaration.
11020 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11021 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11022 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11023 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11024 else if (const TemplateSpecializationType *TST =
11025 DeclaratorType->getAs<TemplateSpecializationType>())
11026 if (TST->isTypeAlias())
11027 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11028 << DeclaratorType << 1;
11029
11030 // C++ [class.dtor]p2:
11031 // A destructor is used to destroy objects of its class type. A
11032 // destructor takes no parameters, and no return type can be
11033 // specified for it (not even void). The address of a destructor
11034 // shall not be taken. A destructor shall not be static. A
11035 // destructor can be invoked for a const, volatile or const
11036 // volatile object. A destructor shall not be declared const,
11037 // volatile or const volatile (9.3.2).
11038 if (SC == SC_Static) {
11039 if (!D.isInvalidType())
11040 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11041 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11044
11045 SC = SC_None;
11046 }
11047 if (!D.isInvalidType()) {
11048 // Destructors don't have return types, but the parser will
11049 // happily parse something like:
11050 //
11051 // class X {
11052 // float ~X();
11053 // };
11054 //
11055 // The return type will be eliminated later.
11056 if (D.getDeclSpec().hasTypeSpecifier())
11057 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11060 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11061 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11067 D.setInvalidType();
11068 }
11069 }
11070
11071 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11072
11073 // C++0x [class.dtor]p2:
11074 // A destructor shall not be declared with a ref-qualifier.
11076 if (FTI.hasRefQualifier()) {
11077 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11080 D.setInvalidType();
11081 }
11082
11083 // Make sure we don't have any parameters.
11084 if (FTIHasNonVoidParameters(FTI)) {
11085 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11086
11087 // Delete the parameters.
11088 FTI.freeParams();
11089 D.setInvalidType();
11090 }
11091
11092 // Make sure the destructor isn't variadic.
11093 if (FTI.isVariadic) {
11094 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11095 D.setInvalidType();
11096 }
11097
11098 // Rebuild the function type "R" without any type qualifiers or
11099 // parameters (in case any of the errors above fired) and with
11100 // "void" as the return type, since destructors don't have return
11101 // types.
11102 if (!D.isInvalidType())
11103 return R;
11104
11105 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11107 EPI.Variadic = false;
11108 EPI.TypeQuals = Qualifiers();
11109 EPI.RefQualifier = RQ_None;
11110 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11111}
11112
11113static void extendLeft(SourceRange &R, SourceRange Before) {
11114 if (Before.isInvalid())
11115 return;
11116 R.setBegin(Before.getBegin());
11117 if (R.getEnd().isInvalid())
11118 R.setEnd(Before.getEnd());
11119}
11120
11121static void extendRight(SourceRange &R, SourceRange After) {
11122 if (After.isInvalid())
11123 return;
11124 if (R.getBegin().isInvalid())
11125 R.setBegin(After.getBegin());
11126 R.setEnd(After.getEnd());
11127}
11128
11129/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11130/// well-formednes of the conversion function declarator @p D with
11131/// type @p R. If there are any errors in the declarator, this routine
11132/// will emit diagnostics and return true. Otherwise, it will return
11133/// false. Either way, the type @p R will be updated to reflect a
11134/// well-formed type for the conversion operator.
11136 StorageClass& SC) {
11137 // C++ [class.conv.fct]p1:
11138 // Neither parameter types nor return type can be specified. The
11139 // type of a conversion function (8.3.5) is "function taking no
11140 // parameter returning conversion-type-id."
11141 if (SC == SC_Static) {
11142 if (!D.isInvalidType())
11143 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11145 << D.getName().getSourceRange();
11146 D.setInvalidType();
11147 SC = SC_None;
11148 }
11149
11150 TypeSourceInfo *ConvTSI = nullptr;
11151 QualType ConvType =
11153
11154 const DeclSpec &DS = D.getDeclSpec();
11155 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11156 // Conversion functions don't have return types, but the parser will
11157 // happily parse something like:
11158 //
11159 // class X {
11160 // float operator bool();
11161 // };
11162 //
11163 // The return type will be changed later anyway.
11164 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11167 D.setInvalidType();
11168 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11169 // It's also plausible that the user writes type qualifiers in the wrong
11170 // place, such as:
11171 // struct S { const operator int(); };
11172 // FIXME: we could provide a fixit to move the qualifiers onto the
11173 // conversion type.
11174 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11175 << SourceRange(D.getIdentifierLoc()) << 0;
11176 D.setInvalidType();
11177 }
11178 const auto *Proto = R->castAs<FunctionProtoType>();
11179 // Make sure we don't have any parameters.
11181 unsigned NumParam = Proto->getNumParams();
11182
11183 // [C++2b]
11184 // A conversion function shall have no non-object parameters.
11185 if (NumParam == 1) {
11187 if (const auto *First =
11188 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11189 First && First->isExplicitObjectParameter())
11190 NumParam--;
11191 }
11192
11193 if (NumParam != 0) {
11194 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11195 // Delete the parameters.
11196 FTI.freeParams();
11197 D.setInvalidType();
11198 } else if (Proto->isVariadic()) {
11199 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11200 D.setInvalidType();
11201 }
11202
11203 // Diagnose "&operator bool()" and other such nonsense. This
11204 // is actually a gcc extension which we don't support.
11205 if (Proto->getReturnType() != ConvType) {
11206 bool NeedsTypedef = false;
11207 SourceRange Before, After;
11208
11209 // Walk the chunks and extract information on them for our diagnostic.
11210 bool PastFunctionChunk = false;
11211 for (auto &Chunk : D.type_objects()) {
11212 switch (Chunk.Kind) {
11214 if (!PastFunctionChunk) {
11215 if (Chunk.Fun.HasTrailingReturnType) {
11216 TypeSourceInfo *TRT = nullptr;
11217 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11218 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11219 }
11220 PastFunctionChunk = true;
11221 break;
11222 }
11223 [[fallthrough]];
11225 NeedsTypedef = true;
11226 extendRight(After, Chunk.getSourceRange());
11227 break;
11228
11234 extendLeft(Before, Chunk.getSourceRange());
11235 break;
11236
11238 extendLeft(Before, Chunk.Loc);
11239 extendRight(After, Chunk.EndLoc);
11240 break;
11241 }
11242 }
11243
11244 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11245 After.isValid() ? After.getBegin() :
11246 D.getIdentifierLoc();
11247 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11248 DB << Before << After;
11249
11250 if (!NeedsTypedef) {
11251 DB << /*don't need a typedef*/0;
11252
11253 // If we can provide a correct fix-it hint, do so.
11254 if (After.isInvalid() && ConvTSI) {
11255 SourceLocation InsertLoc =
11257 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11259 InsertLoc, CharSourceRange::getTokenRange(Before))
11260 << FixItHint::CreateRemoval(Before);
11261 }
11262 } else if (!Proto->getReturnType()->isDependentType()) {
11263 DB << /*typedef*/1 << Proto->getReturnType();
11264 } else if (getLangOpts().CPlusPlus11) {
11265 DB << /*alias template*/2 << Proto->getReturnType();
11266 } else {
11267 DB << /*might not be fixable*/3;
11268 }
11269
11270 // Recover by incorporating the other type chunks into the result type.
11271 // Note, this does *not* change the name of the function. This is compatible
11272 // with the GCC extension:
11273 // struct S { &operator int(); } s;
11274 // int &r = s.operator int(); // ok in GCC
11275 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11276 ConvType = Proto->getReturnType();
11277 }
11278
11279 // C++ [class.conv.fct]p4:
11280 // The conversion-type-id shall not represent a function type nor
11281 // an array type.
11282 if (ConvType->isArrayType()) {
11283 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11284 ConvType = Context.getPointerType(ConvType);
11285 D.setInvalidType();
11286 } else if (ConvType->isFunctionType()) {
11287 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11288 ConvType = Context.getPointerType(ConvType);
11289 D.setInvalidType();
11290 }
11291
11292 // Rebuild the function type "R" without any parameters (in case any
11293 // of the errors above fired) and with the conversion type as the
11294 // return type.
11295 if (D.isInvalidType())
11296 R = Context.getFunctionType(ConvType, std::nullopt,
11297 Proto->getExtProtoInfo());
11298
11299 // C++0x explicit conversion operators.
11303 ? diag::warn_cxx98_compat_explicit_conversion_functions
11304 : diag::ext_explicit_conversion_functions)
11306}
11307
11308/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11309/// the declaration of the given C++ conversion function. This routine
11310/// is responsible for recording the conversion function in the C++
11311/// class, if possible.
11313 assert(Conversion && "Expected to receive a conversion function declaration");
11314
11315 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11316
11317 // Make sure we aren't redeclaring the conversion function.
11318 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11319 // C++ [class.conv.fct]p1:
11320 // [...] A conversion function is never used to convert a
11321 // (possibly cv-qualified) object to the (possibly cv-qualified)
11322 // same object type (or a reference to it), to a (possibly
11323 // cv-qualified) base class of that type (or a reference to it),
11324 // or to (possibly cv-qualified) void.
11325 QualType ClassType
11327 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11328 ConvType = ConvTypeRef->getPointeeType();
11329 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11331 /* Suppress diagnostics for instantiations. */;
11332 else if (Conversion->size_overridden_methods() != 0)
11333 /* Suppress diagnostics for overriding virtual function in a base class. */;
11334 else if (ConvType->isRecordType()) {
11335 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11336 if (ConvType == ClassType)
11337 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11338 << ClassType;
11339 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11340 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11341 << ClassType << ConvType;
11342 } else if (ConvType->isVoidType()) {
11343 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11344 << ClassType << ConvType;
11345 }
11346
11347 if (FunctionTemplateDecl *ConversionTemplate =
11348 Conversion->getDescribedFunctionTemplate()) {
11349 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11350 ConvType = ConvTypePtr->getPointeeType();
11351 }
11352 if (ConvType->isUndeducedAutoType()) {
11353 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11354 << getReturnTypeLoc(Conversion).getSourceRange()
11355 << llvm::to_underlying(ConvType->getAs<AutoType>()->getKeyword())
11356 << /* in declaration of conversion function template= */ 24;
11357 }
11358
11359 return ConversionTemplate;
11360 }
11361
11362 return Conversion;
11363}
11364
11366 DeclarationName Name, QualType R) {
11367 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11368}
11369
11371 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11372}
11373
11375 DeclarationName Name, QualType R,
11376 bool IsLambda, DeclContext *DC) {
11377 if (!D.isFunctionDeclarator())
11378 return;
11379
11381 if (FTI.NumParams == 0)
11382 return;
11383 ParmVarDecl *ExplicitObjectParam = nullptr;
11384 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11385 const auto &ParamInfo = FTI.Params[Idx];
11386 if (!ParamInfo.Param)
11387 continue;
11388 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11389 if (!Param->isExplicitObjectParameter())
11390 continue;
11391 if (Idx == 0) {
11392 ExplicitObjectParam = Param;
11393 continue;
11394 } else {
11395 Diag(Param->getLocation(),
11396 diag::err_explicit_object_parameter_must_be_first)
11397 << IsLambda << Param->getSourceRange();
11398 }
11399 }
11400 if (!ExplicitObjectParam)
11401 return;
11402
11403 if (ExplicitObjectParam->hasDefaultArg()) {
11404 Diag(ExplicitObjectParam->getLocation(),
11405 diag::err_explicit_object_default_arg)
11406 << ExplicitObjectParam->getSourceRange();
11407 }
11408
11411 D.isStaticMember())) {
11412 Diag(ExplicitObjectParam->getBeginLoc(),
11413 diag::err_explicit_object_parameter_nonmember)
11414 << D.getSourceRange() << /*static=*/0 << IsLambda;
11415 D.setInvalidType();
11416 }
11417
11418 if (D.getDeclSpec().isVirtualSpecified()) {
11419 Diag(ExplicitObjectParam->getBeginLoc(),
11420 diag::err_explicit_object_parameter_nonmember)
11421 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11422 D.setInvalidType();
11423 }
11424
11425 if (IsLambda && FTI.hasMutableQualifier()) {
11426 Diag(ExplicitObjectParam->getBeginLoc(),
11427 diag::err_explicit_object_parameter_mutable)
11428 << D.getSourceRange();
11429 }
11430
11431 if (IsLambda)
11432 return;
11433
11434 if (!DC || !DC->isRecord()) {
11435 Diag(ExplicitObjectParam->getLocation(),
11436 diag::err_explicit_object_parameter_nonmember)
11437 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11438 D.setInvalidType();
11439 return;
11440 }
11441
11442 // CWG2674: constructors and destructors cannot have explicit parameters.
11443 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11444 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11445 Diag(ExplicitObjectParam->getBeginLoc(),
11446 diag::err_explicit_object_parameter_constructor)
11447 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11448 << D.getSourceRange();
11449 D.setInvalidType();
11450 }
11451}
11452
11453namespace {
11454/// Utility class to accumulate and print a diagnostic listing the invalid
11455/// specifier(s) on a declaration.
11456struct BadSpecifierDiagnoser {
11457 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11458 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11459 ~BadSpecifierDiagnoser() {
11460 Diagnostic << Specifiers;
11461 }
11462
11463 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11464 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11465 }
11466 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11467 return check(SpecLoc,
11469 }
11470 void check(SourceLocation SpecLoc, const char *Spec) {
11471 if (SpecLoc.isInvalid()) return;
11472 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11473 if (!Specifiers.empty()) Specifiers += " ";
11474 Specifiers += Spec;
11475 }
11476
11477 Sema &S;
11479 std::string Specifiers;
11480};
11481}
11482
11483/// Check the validity of a declarator that we parsed for a deduction-guide.
11484/// These aren't actually declarators in the grammar, so we need to check that
11485/// the user didn't specify any pieces that are not part of the deduction-guide
11486/// grammar. Return true on invalid deduction-guide.
11488 StorageClass &SC) {
11489 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11490 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11491 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11492
11493 // C++ [temp.deduct.guide]p3:
11494 // A deduction-gide shall be declared in the same scope as the
11495 // corresponding class template.
11497 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11498 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11499 << GuidedTemplateDecl;
11500 NoteTemplateLocation(*GuidedTemplateDecl);
11501 }
11502
11503 auto &DS = D.getMutableDeclSpec();
11504 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11505 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11506 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11507 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11508 BadSpecifierDiagnoser Diagnoser(
11509 *this, D.getIdentifierLoc(),
11510 diag::err_deduction_guide_invalid_specifier);
11511
11512 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11513 DS.ClearStorageClassSpecs();
11514 SC = SC_None;
11515
11516 // 'explicit' is permitted.
11517 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11518 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11519 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11520 DS.ClearConstexprSpec();
11521
11522 Diagnoser.check(DS.getConstSpecLoc(), "const");
11523 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11524 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11525 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11526 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11527 DS.ClearTypeQualifiers();
11528
11529 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11530 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11531 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11532 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11533 DS.ClearTypeSpecType();
11534 }
11535
11536 if (D.isInvalidType())
11537 return true;
11538
11539 // Check the declarator is simple enough.
11540 bool FoundFunction = false;
11541 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11542 if (Chunk.Kind == DeclaratorChunk::Paren)
11543 continue;
11544 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11546 diag::err_deduction_guide_with_complex_decl)
11547 << D.getSourceRange();
11548 break;
11549 }
11550 if (!Chunk.Fun.hasTrailingReturnType())
11551 return Diag(D.getName().getBeginLoc(),
11552 diag::err_deduction_guide_no_trailing_return_type);
11553
11554 // Check that the return type is written as a specialization of
11555 // the template specified as the deduction-guide's name.
11556 // The template name may not be qualified. [temp.deduct.guide]
11557 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11558 TypeSourceInfo *TSI = nullptr;
11559 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11560 assert(TSI && "deduction guide has valid type but invalid return type?");
11561 bool AcceptableReturnType = false;
11562 bool MightInstantiateToSpecialization = false;
11563 if (auto RetTST =
11565 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11566 bool TemplateMatches =
11567 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11568 auto TKind = SpecifiedName.getKind();
11569 // A Using TemplateName can't actually be valid (either it's qualified, or
11570 // we're in the wrong scope). But we have diagnosed these problems
11571 // already.
11572 bool SimplyWritten = TKind == TemplateName::Template ||
11574 if (SimplyWritten && TemplateMatches)
11575 AcceptableReturnType = true;
11576 else {
11577 // This could still instantiate to the right type, unless we know it
11578 // names the wrong class template.
11579 auto *TD = SpecifiedName.getAsTemplateDecl();
11580 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11581 !TemplateMatches);
11582 }
11583 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11584 MightInstantiateToSpecialization = true;
11585 }
11586
11587 if (!AcceptableReturnType)
11588 return Diag(TSI->getTypeLoc().getBeginLoc(),
11589 diag::err_deduction_guide_bad_trailing_return_type)
11590 << GuidedTemplate << TSI->getType()
11591 << MightInstantiateToSpecialization
11592 << TSI->getTypeLoc().getSourceRange();
11593
11594 // Keep going to check that we don't have any inner declarator pieces (we
11595 // could still have a function returning a pointer to a function).
11596 FoundFunction = true;
11597 }
11598
11599 if (D.isFunctionDefinition())
11600 // we can still create a valid deduction guide here.
11601 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11602 return false;
11603}
11604
11605//===----------------------------------------------------------------------===//
11606// Namespace Handling
11607//===----------------------------------------------------------------------===//
11608
11609/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11610/// reopened.
11612 SourceLocation Loc,
11613 IdentifierInfo *II, bool *IsInline,
11614 NamespaceDecl *PrevNS) {
11615 assert(*IsInline != PrevNS->isInline());
11616
11617 // 'inline' must appear on the original definition, but not necessarily
11618 // on all extension definitions, so the note should point to the first
11619 // definition to avoid confusion.
11620 PrevNS = PrevNS->getFirstDecl();
11621
11622 if (PrevNS->isInline())
11623 // The user probably just forgot the 'inline', so suggest that it
11624 // be added back.
11625 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11626 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11627 else
11628 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11629
11630 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11631 *IsInline = PrevNS->isInline();
11632}
11633
11634/// ActOnStartNamespaceDef - This is called at the start of a namespace
11635/// definition.
11637 SourceLocation InlineLoc,
11638 SourceLocation NamespaceLoc,
11639 SourceLocation IdentLoc, IdentifierInfo *II,
11640 SourceLocation LBrace,
11641 const ParsedAttributesView &AttrList,
11642 UsingDirectiveDecl *&UD, bool IsNested) {
11643 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11644 // For anonymous namespace, take the location of the left brace.
11645 SourceLocation Loc = II ? IdentLoc : LBrace;
11646 bool IsInline = InlineLoc.isValid();
11647 bool IsInvalid = false;
11648 bool IsStd = false;
11649 bool AddToKnown = false;
11650 Scope *DeclRegionScope = NamespcScope->getParent();
11651
11652 NamespaceDecl *PrevNS = nullptr;
11653 if (II) {
11654 // C++ [namespace.std]p7:
11655 // A translation unit shall not declare namespace std to be an inline
11656 // namespace (9.8.2).
11657 //
11658 // Precondition: the std namespace is in the file scope and is declared to
11659 // be inline
11660 auto DiagnoseInlineStdNS = [&]() {
11661 assert(IsInline && II->isStr("std") &&
11663 "Precondition of DiagnoseInlineStdNS not met");
11664 Diag(InlineLoc, diag::err_inline_namespace_std)
11665 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11666 IsInline = false;
11667 };
11668 // C++ [namespace.def]p2:
11669 // The identifier in an original-namespace-definition shall not
11670 // have been previously defined in the declarative region in
11671 // which the original-namespace-definition appears. The
11672 // identifier in an original-namespace-definition is the name of
11673 // the namespace. Subsequently in that declarative region, it is
11674 // treated as an original-namespace-name.
11675 //
11676 // Since namespace names are unique in their scope, and we don't
11677 // look through using directives, just look for any ordinary names
11678 // as if by qualified name lookup.
11679 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11682 NamedDecl *PrevDecl =
11683 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11684 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11685
11686 if (PrevNS) {
11687 // This is an extended namespace definition.
11688 if (IsInline && II->isStr("std") &&
11690 DiagnoseInlineStdNS();
11691 else if (IsInline != PrevNS->isInline())
11692 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11693 &IsInline, PrevNS);
11694 } else if (PrevDecl) {
11695 // This is an invalid name redefinition.
11696 Diag(Loc, diag::err_redefinition_different_kind)
11697 << II;
11698 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11699 IsInvalid = true;
11700 // Continue on to push Namespc as current DeclContext and return it.
11701 } else if (II->isStr("std") &&
11703 if (IsInline)
11704 DiagnoseInlineStdNS();
11705 // This is the first "real" definition of the namespace "std", so update
11706 // our cache of the "std" namespace to point at this definition.
11707 PrevNS = getStdNamespace();
11708 IsStd = true;
11709 AddToKnown = !IsInline;
11710 } else {
11711 // We've seen this namespace for the first time.
11712 AddToKnown = !IsInline;
11713 }
11714 } else {
11715 // Anonymous namespaces.
11716
11717 // Determine whether the parent already has an anonymous namespace.
11719 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11720 PrevNS = TU->getAnonymousNamespace();
11721 } else {
11722 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11723 PrevNS = ND->getAnonymousNamespace();
11724 }
11725
11726 if (PrevNS && IsInline != PrevNS->isInline())
11727 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11728 &IsInline, PrevNS);
11729 }
11730
11732 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11733 if (IsInvalid)
11734 Namespc->setInvalidDecl();
11735
11736 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11737 AddPragmaAttributes(DeclRegionScope, Namespc);
11738 ProcessAPINotes(Namespc);
11739
11740 // FIXME: Should we be merging attributes?
11741 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11743
11744 if (IsStd)
11745 StdNamespace = Namespc;
11746 if (AddToKnown)
11747 KnownNamespaces[Namespc] = false;
11748
11749 if (II) {
11750 PushOnScopeChains(Namespc, DeclRegionScope);
11751 } else {
11752 // Link the anonymous namespace into its parent.
11754 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11755 TU->setAnonymousNamespace(Namespc);
11756 } else {
11757 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11758 }
11759
11760 CurContext->addDecl(Namespc);
11761
11762 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11763 // behaves as if it were replaced by
11764 // namespace unique { /* empty body */ }
11765 // using namespace unique;
11766 // namespace unique { namespace-body }
11767 // where all occurrences of 'unique' in a translation unit are
11768 // replaced by the same identifier and this identifier differs
11769 // from all other identifiers in the entire program.
11770
11771 // We just create the namespace with an empty name and then add an
11772 // implicit using declaration, just like the standard suggests.
11773 //
11774 // CodeGen enforces the "universally unique" aspect by giving all
11775 // declarations semantically contained within an anonymous
11776 // namespace internal linkage.
11777
11778 if (!PrevNS) {
11780 /* 'using' */ LBrace,
11781 /* 'namespace' */ SourceLocation(),
11782 /* qualifier */ NestedNameSpecifierLoc(),
11783 /* identifier */ SourceLocation(),
11784 Namespc,
11785 /* Ancestor */ Parent);
11786 UD->setImplicit();
11787 Parent->addDecl(UD);
11788 }
11789 }
11790
11791 ActOnDocumentableDecl(Namespc);
11792
11793 // Although we could have an invalid decl (i.e. the namespace name is a
11794 // redefinition), push it as current DeclContext and try to continue parsing.
11795 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11796 // for the namespace has the declarations that showed up in that particular
11797 // namespace definition.
11798 PushDeclContext(NamespcScope, Namespc);
11799 return Namespc;
11800}
11801
11802/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11803/// is a namespace alias, returns the namespace it points to.
11805 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11806 return AD->getNamespace();
11807 return dyn_cast_or_null<NamespaceDecl>(D);
11808}
11809
11810/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11811/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11813 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11814 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11815 Namespc->setRBraceLoc(RBrace);
11817 if (Namespc->hasAttr<VisibilityAttr>())
11818 PopPragmaVisibility(true, RBrace);
11819 // If this namespace contains an export-declaration, export it now.
11820 if (DeferredExportedNamespaces.erase(Namespc))
11822}
11823
11825 return cast_or_null<CXXRecordDecl>(
11827}
11828
11830 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11831}
11832
11834 return cast_or_null<NamespaceDecl>(
11836}
11837namespace {
11838
11839enum UnsupportedSTLSelect {
11840 USS_InvalidMember,
11841 USS_MissingMember,
11842 USS_NonTrivial,
11843 USS_Other
11844};
11845
11846struct InvalidSTLDiagnoser {
11847 Sema &S;
11848 SourceLocation Loc;
11849 QualType TyForDiags;
11850
11851 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11852 const VarDecl *VD = nullptr) {
11853 {
11854 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11855 << TyForDiags << ((int)Sel);
11856 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11857 assert(!Name.empty());
11858 D << Name;
11859 }
11860 }
11861 if (Sel == USS_InvalidMember) {
11862 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11863 << VD << VD->getSourceRange();
11864 }
11865 return QualType();
11866 }
11867};
11868} // namespace
11869
11871 SourceLocation Loc,
11873 assert(getLangOpts().CPlusPlus &&
11874 "Looking for comparison category type outside of C++.");
11875
11876 // Use an elaborated type for diagnostics which has a name containing the
11877 // prepended 'std' namespace but not any inline namespace names.
11878 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11879 auto *NNS =
11882 Info->getType());
11883 };
11884
11885 // Check if we've already successfully checked the comparison category type
11886 // before. If so, skip checking it again.
11888 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11889 // The only thing we need to check is that the type has a reachable
11890 // definition in the current context.
11891 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11892 return QualType();
11893
11894 return Info->getType();
11895 }
11896
11897 // If lookup failed
11898 if (!Info) {
11899 std::string NameForDiags = "std::";
11900 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11901 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11902 << NameForDiags << (int)Usage;
11903 return QualType();
11904 }
11905
11906 assert(Info->Kind == Kind);
11907 assert(Info->Record);
11908
11909 // Update the Record decl in case we encountered a forward declaration on our
11910 // first pass. FIXME: This is a bit of a hack.
11911 if (Info->Record->hasDefinition())
11912 Info->Record = Info->Record->getDefinition();
11913
11914 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11915 return QualType();
11916
11917 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11918
11919 if (!Info->Record->isTriviallyCopyable())
11920 return UnsupportedSTLError(USS_NonTrivial);
11921
11922 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11923 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11924 // Tolerate empty base classes.
11925 if (Base->isEmpty())
11926 continue;
11927 // Reject STL implementations which have at least one non-empty base.
11928 return UnsupportedSTLError();
11929 }
11930
11931 // Check that the STL has implemented the types using a single integer field.
11932 // This expectation allows better codegen for builtin operators. We require:
11933 // (1) The class has exactly one field.
11934 // (2) The field is an integral or enumeration type.
11935 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11936 if (std::distance(FIt, FEnd) != 1 ||
11937 !FIt->getType()->isIntegralOrEnumerationType()) {
11938 return UnsupportedSTLError();
11939 }
11940
11941 // Build each of the require values and store them in Info.
11942 for (ComparisonCategoryResult CCR :
11944 StringRef MemName = ComparisonCategories::getResultString(CCR);
11945 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11946
11947 if (!ValInfo)
11948 return UnsupportedSTLError(USS_MissingMember, MemName);
11949
11950 VarDecl *VD = ValInfo->VD;
11951 assert(VD && "should not be null!");
11952
11953 // Attempt to diagnose reasons why the STL definition of this type
11954 // might be foobar, including it failing to be a constant expression.
11955 // TODO Handle more ways the lookup or result can be invalid.
11956 if (!VD->isStaticDataMember() ||
11958 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11959
11960 // Attempt to evaluate the var decl as a constant expression and extract
11961 // the value of its first field as a ICE. If this fails, the STL
11962 // implementation is not supported.
11963 if (!ValInfo->hasValidIntValue())
11964 return UnsupportedSTLError();
11965
11966 MarkVariableReferenced(Loc, VD);
11967 }
11968
11969 // We've successfully built the required types and expressions. Update
11970 // the cache and return the newly cached value.
11971 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11972 return Info->getType();
11973}
11974
11975/// Retrieve the special "std" namespace, which may require us to
11976/// implicitly define the namespace.
11978 if (!StdNamespace) {
11979 // The "std" namespace has not yet been defined, so build one implicitly.
11982 /*Inline=*/false, SourceLocation(), SourceLocation(),
11983 &PP.getIdentifierTable().get("std"),
11984 /*PrevDecl=*/nullptr, /*Nested=*/false);
11986 // We want the created NamespaceDecl to be available for redeclaration
11987 // lookups, but not for regular name lookups.
11990 }
11991
11992 return getStdNamespace();
11993}
11994
11996 assert(getLangOpts().CPlusPlus &&
11997 "Looking for std::initializer_list outside of C++.");
11998
11999 // We're looking for implicit instantiations of
12000 // template <typename E> class std::initializer_list.
12001
12002 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
12003 return false;
12004
12005 ClassTemplateDecl *Template = nullptr;
12006 const TemplateArgument *Arguments = nullptr;
12007
12008 if (const RecordType *RT = Ty->getAs<RecordType>()) {
12009
12011 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
12012 if (!Specialization)
12013 return false;
12014
12015 Template = Specialization->getSpecializedTemplate();
12016 Arguments = Specialization->getTemplateArgs().data();
12017 } else if (const TemplateSpecializationType *TST =
12019 Template = dyn_cast_or_null<ClassTemplateDecl>(
12020 TST->getTemplateName().getAsTemplateDecl());
12021 Arguments = TST->template_arguments().begin();
12022 }
12023 if (!Template)
12024 return false;
12025
12026 if (!StdInitializerList) {
12027 // Haven't recognized std::initializer_list yet, maybe this is it.
12028 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12029 if (TemplateClass->getIdentifier() !=
12030 &PP.getIdentifierTable().get("initializer_list") ||
12031 !getStdNamespace()->InEnclosingNamespaceSetOf(
12032 TemplateClass->getDeclContext()))
12033 return false;
12034 // This is a template called std::initializer_list, but is it the right
12035 // template?
12036 TemplateParameterList *Params = Template->getTemplateParameters();
12037 if (Params->getMinRequiredArguments() != 1)
12038 return false;
12039 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12040 return false;
12041
12042 // It's the right template.
12043 StdInitializerList = Template;
12044 }
12045
12047 return false;
12048
12049 // This is an instance of std::initializer_list. Find the argument type.
12050 if (Element)
12051 *Element = Arguments[0].getAsType();
12052 return true;
12053}
12054
12057 if (!Std) {
12058 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12059 return nullptr;
12060 }
12061
12062 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12064 if (!S.LookupQualifiedName(Result, Std)) {
12065 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12066 return nullptr;
12067 }
12068 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12069 if (!Template) {
12070 Result.suppressDiagnostics();
12071 // We found something weird. Complain about the first thing we found.
12072 NamedDecl *Found = *Result.begin();
12073 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12074 return nullptr;
12075 }
12076
12077 // We found some template called std::initializer_list. Now verify that it's
12078 // correct.
12079 TemplateParameterList *Params = Template->getTemplateParameters();
12080 if (Params->getMinRequiredArguments() != 1 ||
12081 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12082 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12083 return nullptr;
12084 }
12085
12086 return Template;
12087}
12088
12090 if (!StdInitializerList) {
12092 if (!StdInitializerList)
12093 return QualType();
12094 }
12095
12096 TemplateArgumentListInfo Args(Loc, Loc);
12099 Loc)));
12104}
12105
12107 // C++ [dcl.init.list]p2:
12108 // A constructor is an initializer-list constructor if its first parameter
12109 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12110 // std::initializer_list<E> for some type E, and either there are no other
12111 // parameters or else all other parameters have default arguments.
12112 if (!Ctor->hasOneParamOrDefaultArgs())
12113 return false;
12114
12115 QualType ArgType = Ctor->getParamDecl(0)->getType();
12116 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12117 ArgType = RT->getPointeeType().getUnqualifiedType();
12118
12119 return isStdInitializerList(ArgType, nullptr);
12120}
12121
12122/// Determine whether a using statement is in a context where it will be
12123/// apply in all contexts.
12125 switch (CurContext->getDeclKind()) {
12126 case Decl::TranslationUnit:
12127 return true;
12128 case Decl::LinkageSpec:
12130 default:
12131 return false;
12132 }
12133}
12134
12135namespace {
12136
12137// Callback to only accept typo corrections that are namespaces.
12138class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12139public:
12140 bool ValidateCandidate(const TypoCorrection &candidate) override {
12141 if (NamedDecl *ND = candidate.getCorrectionDecl())
12142 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12143 return false;
12144 }
12145
12146 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12147 return std::make_unique<NamespaceValidatorCCC>(*this);
12148 }
12149};
12150
12151}
12152
12153static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12154 Sema &S) {
12155 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12156 Module *M = ND->getOwningModule();
12157 assert(M && "hidden namespace definition not in a module?");
12158
12159 if (M->isExplicitGlobalModule())
12160 S.Diag(Corrected.getCorrectionRange().getBegin(),
12161 diag::err_module_unimported_use_header)
12163 << /*Header Name*/ false;
12164 else
12165 S.Diag(Corrected.getCorrectionRange().getBegin(),
12166 diag::err_module_unimported_use)
12168 << M->getTopLevelModuleName();
12169}
12170
12172 CXXScopeSpec &SS,
12173 SourceLocation IdentLoc,
12174 IdentifierInfo *Ident) {
12175 R.clear();
12176 NamespaceValidatorCCC CCC{};
12177 if (TypoCorrection Corrected =
12178 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12180 // Generally we find it is confusing more than helpful to diagnose the
12181 // invisible namespace.
12182 // See https://github.com/llvm/llvm-project/issues/73893.
12183 //
12184 // However, we should diagnose when the users are trying to using an
12185 // invisible namespace. So we handle the case specially here.
12186 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12187 Corrected.requiresImport()) {
12188 DiagnoseInvisibleNamespace(Corrected, S);
12189 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12190 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12191 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12192 Ident->getName().equals(CorrectedStr);
12193 S.diagnoseTypo(Corrected,
12194 S.PDiag(diag::err_using_directive_member_suggest)
12195 << Ident << DC << DroppedSpecifier << SS.getRange(),
12196 S.PDiag(diag::note_namespace_defined_here));
12197 } else {
12198 S.diagnoseTypo(Corrected,
12199 S.PDiag(diag::err_using_directive_suggest) << Ident,
12200 S.PDiag(diag::note_namespace_defined_here));
12201 }
12202 R.addDecl(Corrected.getFoundDecl());
12203 return true;
12204 }
12205 return false;
12206}
12207
12209 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12210 SourceLocation IdentLoc,
12211 IdentifierInfo *NamespcName,
12212 const ParsedAttributesView &AttrList) {
12213 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12214 assert(NamespcName && "Invalid NamespcName.");
12215 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12216
12217 // Get the innermost enclosing declaration scope.
12218 S = S->getDeclParent();
12219
12220 UsingDirectiveDecl *UDir = nullptr;
12221 NestedNameSpecifier *Qualifier = nullptr;
12222 if (SS.isSet())
12223 Qualifier = SS.getScopeRep();
12224
12225 // Lookup namespace name.
12226 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12227 LookupParsedName(R, S, &SS);
12228 if (R.isAmbiguous())
12229 return nullptr;
12230
12231 if (R.empty()) {
12232 R.clear();
12233 // Allow "using namespace std;" or "using namespace ::std;" even if
12234 // "std" hasn't been defined yet, for GCC compatibility.
12235 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12236 NamespcName->isStr("std")) {
12237 Diag(IdentLoc, diag::ext_using_undefined_std);
12239 R.resolveKind();
12240 }
12241 // Otherwise, attempt typo correction.
12242 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12243 }
12244
12245 if (!R.empty()) {
12246 NamedDecl *Named = R.getRepresentativeDecl();
12248 assert(NS && "expected namespace decl");
12249
12250 // The use of a nested name specifier may trigger deprecation warnings.
12251 DiagnoseUseOfDecl(Named, IdentLoc);
12252
12253 // C++ [namespace.udir]p1:
12254 // A using-directive specifies that the names in the nominated
12255 // namespace can be used in the scope in which the
12256 // using-directive appears after the using-directive. During
12257 // unqualified name lookup (3.4.1), the names appear as if they
12258 // were declared in the nearest enclosing namespace which
12259 // contains both the using-directive and the nominated
12260 // namespace. [Note: in this context, "contains" means "contains
12261 // directly or indirectly". ]
12262
12263 // Find enclosing context containing both using-directive and
12264 // nominated namespace.
12265 DeclContext *CommonAncestor = NS;
12266 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12267 CommonAncestor = CommonAncestor->getParent();
12268
12269 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12271 IdentLoc, Named, CommonAncestor);
12272
12275 Diag(IdentLoc, diag::warn_using_directive_in_header);
12276 }
12277
12278 PushUsingDirective(S, UDir);
12279 } else {
12280 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12281 }
12282
12283 if (UDir) {
12284 ProcessDeclAttributeList(S, UDir, AttrList);
12285 ProcessAPINotes(UDir);
12286 }
12287
12288 return UDir;
12289}
12290
12292 // If the scope has an associated entity and the using directive is at
12293 // namespace or translation unit scope, add the UsingDirectiveDecl into
12294 // its lookup structure so qualified name lookup can find it.
12295 DeclContext *Ctx = S->getEntity();
12296 if (Ctx && !Ctx->isFunctionOrMethod())
12297 Ctx->addDecl(UDir);
12298 else
12299 // Otherwise, it is at block scope. The using-directives will affect lookup
12300 // only to the end of the scope.
12301 S->PushUsingDirective(UDir);
12302}
12303
12305 SourceLocation UsingLoc,
12306 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12307 UnqualifiedId &Name,
12308 SourceLocation EllipsisLoc,
12309 const ParsedAttributesView &AttrList) {
12310 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12311
12312 if (SS.isEmpty()) {
12313 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12314 return nullptr;
12315 }
12316
12317 switch (Name.getKind()) {
12323 break;
12324
12327 // C++11 inheriting constructors.
12328 Diag(Name.getBeginLoc(),
12330 ? diag::warn_cxx98_compat_using_decl_constructor
12331 : diag::err_using_decl_constructor)
12332 << SS.getRange();
12333
12334 if (getLangOpts().CPlusPlus11) break;
12335
12336 return nullptr;
12337
12339 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12340 return nullptr;
12341
12343 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12344 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12345 return nullptr;
12346
12348 llvm_unreachable("cannot parse qualified deduction guide name");
12349 }
12350
12351 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12352 DeclarationName TargetName = TargetNameInfo.getName();
12353 if (!TargetName)
12354 return nullptr;
12355
12356 // Warn about access declarations.
12357 if (UsingLoc.isInvalid()) {
12358 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12359 ? diag::err_access_decl
12360 : diag::warn_access_decl_deprecated)
12361 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12362 }
12363
12364 if (EllipsisLoc.isInvalid()) {
12367 return nullptr;
12368 } else {
12370 !TargetNameInfo.containsUnexpandedParameterPack()) {
12371 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12372 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12373 EllipsisLoc = SourceLocation();
12374 }
12375 }
12376
12377 NamedDecl *UD =
12378 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12379 SS, TargetNameInfo, EllipsisLoc, AttrList,
12380 /*IsInstantiation*/ false,
12381 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12382 if (UD)
12383 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12384
12385 return UD;
12386}
12387
12389 SourceLocation UsingLoc,
12390 SourceLocation EnumLoc,
12391 SourceLocation IdentLoc,
12392 IdentifierInfo &II, CXXScopeSpec *SS) {
12393 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12394 TypeSourceInfo *TSI = nullptr;
12395 QualType EnumTy = GetTypeFromParser(
12396 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12397 /*HasTrailingDot=*/false,
12398 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12399 /*WantNontrivialTypeSourceInfo=*/true),
12400 &TSI);
12401 if (EnumTy.isNull()) {
12402 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12403 ? diag::err_using_enum_is_dependent
12404 : diag::err_unknown_typename)
12405 << II.getName()
12406 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12407 return nullptr;
12408 }
12409
12410 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12411 if (!Enum) {
12412 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12413 return nullptr;
12414 }
12415
12416 if (auto *Def = Enum->getDefinition())
12417 Enum = Def;
12418
12419 if (TSI == nullptr)
12420 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12421
12422 auto *UD =
12423 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12424
12425 if (UD)
12426 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12427
12428 return UD;
12429}
12430
12431/// Determine whether a using declaration considers the given
12432/// declarations as "equivalent", e.g., if they are redeclarations of
12433/// the same entity or are both typedefs of the same type.
12434static bool
12436 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12437 return true;
12438
12439 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12440 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12441 return Context.hasSameType(TD1->getUnderlyingType(),
12442 TD2->getUnderlyingType());
12443
12444 // Two using_if_exists using-declarations are equivalent if both are
12445 // unresolved.
12446 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12447 isa<UnresolvedUsingIfExistsDecl>(D2))
12448 return true;
12449
12450 return false;
12451}
12452
12453
12454/// Determines whether to create a using shadow decl for a particular
12455/// decl, given the set of decls existing prior to this using lookup.
12457 const LookupResult &Previous,
12458 UsingShadowDecl *&PrevShadow) {
12459 // Diagnose finding a decl which is not from a base class of the
12460 // current class. We do this now because there are cases where this
12461 // function will silently decide not to build a shadow decl, which
12462 // will pre-empt further diagnostics.
12463 //
12464 // We don't need to do this in C++11 because we do the check once on
12465 // the qualifier.
12466 //
12467 // FIXME: diagnose the following if we care enough:
12468 // struct A { int foo; };
12469 // struct B : A { using A::foo; };
12470 // template <class T> struct C : A {};
12471 // template <class T> struct D : C<T> { using B::foo; } // <---
12472 // This is invalid (during instantiation) in C++03 because B::foo
12473 // resolves to the using decl in B, which is not a base class of D<T>.
12474 // We can't diagnose it immediately because C<T> is an unknown
12475 // specialization. The UsingShadowDecl in D<T> then points directly
12476 // to A::foo, which will look well-formed when we instantiate.
12477 // The right solution is to not collapse the shadow-decl chain.
12479 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12480 DeclContext *OrigDC = Orig->getDeclContext();
12481
12482 // Handle enums and anonymous structs.
12483 if (isa<EnumDecl>(OrigDC))
12484 OrigDC = OrigDC->getParent();
12485 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12486 while (OrigRec->isAnonymousStructOrUnion())
12487 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12488
12489 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12490 if (OrigDC == CurContext) {
12491 Diag(Using->getLocation(),
12492 diag::err_using_decl_nested_name_specifier_is_current_class)
12493 << Using->getQualifierLoc().getSourceRange();
12494 Diag(Orig->getLocation(), diag::note_using_decl_target);
12495 Using->setInvalidDecl();
12496 return true;
12497 }
12498
12499 Diag(Using->getQualifierLoc().getBeginLoc(),
12500 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12501 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12502 << Using->getQualifierLoc().getSourceRange();
12503 Diag(Orig->getLocation(), diag::note_using_decl_target);
12504 Using->setInvalidDecl();
12505 return true;
12506 }
12507 }
12508
12509 if (Previous.empty()) return false;
12510
12511 NamedDecl *Target = Orig;
12512 if (isa<UsingShadowDecl>(Target))
12513 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12514
12515 // If the target happens to be one of the previous declarations, we
12516 // don't have a conflict.
12517 //
12518 // FIXME: but we might be increasing its access, in which case we
12519 // should redeclare it.
12520 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12521 bool FoundEquivalentDecl = false;
12522 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12523 I != E; ++I) {
12524 NamedDecl *D = (*I)->getUnderlyingDecl();
12525 // We can have UsingDecls in our Previous results because we use the same
12526 // LookupResult for checking whether the UsingDecl itself is a valid
12527 // redeclaration.
12528 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12529 continue;
12530
12531 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12532 // C++ [class.mem]p19:
12533 // If T is the name of a class, then [every named member other than
12534 // a non-static data member] shall have a name different from T
12535 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12536 !isa<IndirectFieldDecl>(Target) &&
12537 !isa<UnresolvedUsingValueDecl>(Target) &&
12539 CurContext,
12541 return true;
12542 }
12543
12545 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12546 PrevShadow = Shadow;
12547 FoundEquivalentDecl = true;
12549 // We don't conflict with an existing using shadow decl of an equivalent
12550 // declaration, but we're not a redeclaration of it.
12551 FoundEquivalentDecl = true;
12552 }
12553
12554 if (isVisible(D))
12555 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12556 }
12557
12558 if (FoundEquivalentDecl)
12559 return false;
12560
12561 // Always emit a diagnostic for a mismatch between an unresolved
12562 // using_if_exists and a resolved using declaration in either direction.
12563 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12564 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12565 if (!NonTag && !Tag)
12566 return false;
12567 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12568 Diag(Target->getLocation(), diag::note_using_decl_target);
12569 Diag((NonTag ? NonTag : Tag)->getLocation(),
12570 diag::note_using_decl_conflict);
12571 BUD->setInvalidDecl();
12572 return true;
12573 }
12574
12575 if (FunctionDecl *FD = Target->getAsFunction()) {
12576 NamedDecl *OldDecl = nullptr;
12577 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12578 /*IsForUsingDecl*/ true)) {
12579 case Ovl_Overload:
12580 return false;
12581
12582 case Ovl_NonFunction:
12583 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12584 break;
12585
12586 // We found a decl with the exact signature.
12587 case Ovl_Match:
12588 // If we're in a record, we want to hide the target, so we
12589 // return true (without a diagnostic) to tell the caller not to
12590 // build a shadow decl.
12591 if (CurContext->isRecord())
12592 return true;
12593
12594 // If we're not in a record, this is an error.
12595 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12596 break;
12597 }
12598
12599 Diag(Target->getLocation(), diag::note_using_decl_target);
12600 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12601 BUD->setInvalidDecl();
12602 return true;
12603 }
12604
12605 // Target is not a function.
12606
12607 if (isa<TagDecl>(Target)) {
12608 // No conflict between a tag and a non-tag.
12609 if (!Tag) return false;
12610
12611 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12612 Diag(Target->getLocation(), diag::note_using_decl_target);
12613 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12614 BUD->setInvalidDecl();
12615 return true;
12616 }
12617
12618 // No conflict between a tag and a non-tag.
12619 if (!NonTag) return false;
12620
12621 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12622 Diag(Target->getLocation(), diag::note_using_decl_target);
12623 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12624 BUD->setInvalidDecl();
12625 return true;
12626}
12627
12628/// Determine whether a direct base class is a virtual base class.
12630 if (!Derived->getNumVBases())
12631 return false;
12632 for (auto &B : Derived->bases())
12633 if (B.getType()->getAsCXXRecordDecl() == Base)
12634 return B.isVirtual();
12635 llvm_unreachable("not a direct base class");
12636}
12637
12638/// Builds a shadow declaration corresponding to a 'using' declaration.
12640 NamedDecl *Orig,
12641 UsingShadowDecl *PrevDecl) {
12642 // If we resolved to another shadow declaration, just coalesce them.
12643 NamedDecl *Target = Orig;
12644 if (isa<UsingShadowDecl>(Target)) {
12645 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12646 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12647 }
12648
12649 NamedDecl *NonTemplateTarget = Target;
12650 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12651 NonTemplateTarget = TargetTD->getTemplatedDecl();
12652
12653 UsingShadowDecl *Shadow;
12654 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12655 UsingDecl *Using = cast<UsingDecl>(BUD);
12656 bool IsVirtualBase =
12657 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12658 Using->getQualifier()->getAsRecordDecl());
12660 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12661 } else {
12663 Target->getDeclName(), BUD, Target);
12664 }
12665 BUD->addShadowDecl(Shadow);
12666
12667 Shadow->setAccess(BUD->getAccess());
12668 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12669 Shadow->setInvalidDecl();
12670
12671 Shadow->setPreviousDecl(PrevDecl);
12672
12673 if (S)
12674 PushOnScopeChains(Shadow, S);
12675 else
12676 CurContext->addDecl(Shadow);
12677
12678
12679 return Shadow;
12680}
12681
12682/// Hides a using shadow declaration. This is required by the current
12683/// using-decl implementation when a resolvable using declaration in a
12684/// class is followed by a declaration which would hide or override
12685/// one or more of the using decl's targets; for example:
12686///
12687/// struct Base { void foo(int); };
12688/// struct Derived : Base {
12689/// using Base::foo;
12690/// void foo(int);
12691/// };
12692///
12693/// The governing language is C++03 [namespace.udecl]p12:
12694///
12695/// When a using-declaration brings names from a base class into a
12696/// derived class scope, member functions in the derived class
12697/// override and/or hide member functions with the same name and
12698/// parameter types in a base class (rather than conflicting).
12699///
12700/// There are two ways to implement this:
12701/// (1) optimistically create shadow decls when they're not hidden
12702/// by existing declarations, or
12703/// (2) don't create any shadow decls (or at least don't make them
12704/// visible) until we've fully parsed/instantiated the class.
12705/// The problem with (1) is that we might have to retroactively remove
12706/// a shadow decl, which requires several O(n) operations because the
12707/// decl structures are (very reasonably) not designed for removal.
12708/// (2) avoids this but is very fiddly and phase-dependent.
12710 if (Shadow->getDeclName().getNameKind() ==
12712 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12713
12714 // Remove it from the DeclContext...
12715 Shadow->getDeclContext()->removeDecl(Shadow);
12716
12717 // ...and the scope, if applicable...
12718 if (S) {
12719 S->RemoveDecl(Shadow);
12720 IdResolver.RemoveDecl(Shadow);
12721 }
12722
12723 // ...and the using decl.
12724 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12725
12726 // TODO: complain somehow if Shadow was used. It shouldn't
12727 // be possible for this to happen, because...?
12728}
12729
12730/// Find the base specifier for a base class with the given type.
12732 QualType DesiredBase,
12733 bool &AnyDependentBases) {
12734 // Check whether the named type is a direct base class.
12735 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12737 for (auto &Base : Derived->bases()) {
12738 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12739 if (CanonicalDesiredBase == BaseType)
12740 return &Base;
12741 if (BaseType->isDependentType())
12742 AnyDependentBases = true;
12743 }
12744 return nullptr;
12745}
12746
12747namespace {
12748class UsingValidatorCCC final : public CorrectionCandidateCallback {
12749public:
12750 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12751 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12752 : HasTypenameKeyword(HasTypenameKeyword),
12753 IsInstantiation(IsInstantiation), OldNNS(NNS),
12754 RequireMemberOf(RequireMemberOf) {}
12755
12756 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12757 NamedDecl *ND = Candidate.getCorrectionDecl();
12758
12759 // Keywords are not valid here.
12760 if (!ND || isa<NamespaceDecl>(ND))
12761 return false;
12762
12763 // Completely unqualified names are invalid for a 'using' declaration.
12764 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12765 return false;
12766
12767 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12768 // reject.
12769
12770 if (RequireMemberOf) {
12771 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12772 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12773 // No-one ever wants a using-declaration to name an injected-class-name
12774 // of a base class, unless they're declaring an inheriting constructor.
12775 ASTContext &Ctx = ND->getASTContext();
12776 if (!Ctx.getLangOpts().CPlusPlus11)
12777 return false;
12778 QualType FoundType = Ctx.getRecordType(FoundRecord);
12779
12780 // Check that the injected-class-name is named as a member of its own
12781 // type; we don't want to suggest 'using Derived::Base;', since that
12782 // means something else.
12784 Candidate.WillReplaceSpecifier()
12785 ? Candidate.getCorrectionSpecifier()
12786 : OldNNS;
12787 if (!Specifier->getAsType() ||
12788 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12789 return false;
12790
12791 // Check that this inheriting constructor declaration actually names a
12792 // direct base class of the current class.
12793 bool AnyDependentBases = false;
12794 if (!findDirectBaseWithType(RequireMemberOf,
12795 Ctx.getRecordType(FoundRecord),
12796 AnyDependentBases) &&
12797 !AnyDependentBases)
12798 return false;
12799 } else {
12800 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12801 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12802 return false;
12803
12804 // FIXME: Check that the base class member is accessible?
12805 }
12806 } else {
12807 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12808 if (FoundRecord && FoundRecord->isInjectedClassName())
12809 return false;
12810 }
12811
12812 if (isa<TypeDecl>(ND))
12813 return HasTypenameKeyword || !IsInstantiation;
12814
12815 return !HasTypenameKeyword;
12816 }
12817
12818 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12819 return std::make_unique<UsingValidatorCCC>(*this);
12820 }
12821
12822private:
12823 bool HasTypenameKeyword;
12824 bool IsInstantiation;
12825 NestedNameSpecifier *OldNNS;
12826 CXXRecordDecl *RequireMemberOf;
12827};
12828} // end anonymous namespace
12829
12830/// Remove decls we can't actually see from a lookup being used to declare
12831/// shadow using decls.
12832///
12833/// \param S - The scope of the potential shadow decl
12834/// \param Previous - The lookup of a potential shadow decl's name.
12836 // It is really dumb that we have to do this.
12837 LookupResult::Filter F = Previous.makeFilter();
12838 while (F.hasNext()) {
12839 NamedDecl *D = F.next();
12840 if (!isDeclInScope(D, CurContext, S))
12841 F.erase();
12842 // If we found a local extern declaration that's not ordinarily visible,
12843 // and this declaration is being added to a non-block scope, ignore it.
12844 // We're only checking for scope conflicts here, not also for violations
12845 // of the linkage rules.
12846 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12848 F.erase();
12849 }
12850 F.done();
12851}
12852
12853/// Builds a using declaration.
12854///
12855/// \param IsInstantiation - Whether this call arises from an
12856/// instantiation of an unresolved using declaration. We treat
12857/// the lookup differently for these declarations.
12859 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12860 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12861 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12862 const ParsedAttributesView &AttrList, bool IsInstantiation,
12863 bool IsUsingIfExists) {
12864 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12865 SourceLocation IdentLoc = NameInfo.getLoc();
12866 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12867
12868 // FIXME: We ignore attributes for now.
12869
12870 // For an inheriting constructor declaration, the name of the using
12871 // declaration is the name of a constructor in this class, not in the
12872 // base class.
12873 DeclarationNameInfo UsingName = NameInfo;
12875 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12878
12879 // Do the redeclaration lookup in the current scope.
12880 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12882 Previous.setHideTags(false);
12883 if (S) {
12884 LookupName(Previous, S);
12885
12887 } else {
12888 assert(IsInstantiation && "no scope in non-instantiation");
12889 if (CurContext->isRecord())
12891 else {
12892 // No redeclaration check is needed here; in non-member contexts we
12893 // diagnosed all possible conflicts with other using-declarations when
12894 // building the template:
12895 //
12896 // For a dependent non-type using declaration, the only valid case is
12897 // if we instantiate to a single enumerator. We check for conflicts
12898 // between shadow declarations we introduce, and we check in the template
12899 // definition for conflicts between a non-type using declaration and any
12900 // other declaration, which together covers all cases.
12901 //
12902 // A dependent typename using declaration will never successfully
12903 // instantiate, since it will always name a class member, so we reject
12904 // that in the template definition.
12905 }
12906 }
12907
12908 // Check for invalid redeclarations.
12909 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12910 SS, IdentLoc, Previous))
12911 return nullptr;
12912
12913 // 'using_if_exists' doesn't make sense on an inherited constructor.
12914 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12916 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12917 return nullptr;
12918 }
12919
12920 DeclContext *LookupContext = computeDeclContext(SS);
12922 if (!LookupContext || EllipsisLoc.isValid()) {
12923 NamedDecl *D;
12924 // Dependent scope, or an unexpanded pack
12925 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12926 SS, NameInfo, IdentLoc))
12927 return nullptr;
12928
12929 if (HasTypenameKeyword) {
12930 // FIXME: not all declaration name kinds are legal here
12932 UsingLoc, TypenameLoc,
12933 QualifierLoc,
12934 IdentLoc, NameInfo.getName(),
12935 EllipsisLoc);
12936 } else {
12938 QualifierLoc, NameInfo, EllipsisLoc);
12939 }
12940 D->setAccess(AS);
12941 CurContext->addDecl(D);
12942 ProcessDeclAttributeList(S, D, AttrList);
12943 return D;
12944 }
12945
12946 auto Build = [&](bool Invalid) {
12947 UsingDecl *UD =
12948 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12949 UsingName, HasTypenameKeyword);
12950 UD->setAccess(AS);
12951 CurContext->addDecl(UD);
12952 ProcessDeclAttributeList(S, UD, AttrList);
12954 return UD;
12955 };
12956 auto BuildInvalid = [&]{ return Build(true); };
12957 auto BuildValid = [&]{ return Build(false); };
12958
12959 if (RequireCompleteDeclContext(SS, LookupContext))
12960 return BuildInvalid();
12961
12962 // Look up the target name.
12963 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12964
12965 // Unlike most lookups, we don't always want to hide tag
12966 // declarations: tag names are visible through the using declaration
12967 // even if hidden by ordinary names, *except* in a dependent context
12968 // where they may be used by two-phase lookup.
12969 if (!IsInstantiation)
12970 R.setHideTags(false);
12971
12972 // For the purposes of this lookup, we have a base object type
12973 // equal to that of the current context.
12974 if (CurContext->isRecord()) {
12976 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12977 }
12978
12979 LookupQualifiedName(R, LookupContext);
12980
12981 // Validate the context, now we have a lookup
12982 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12983 IdentLoc, &R))
12984 return nullptr;
12985
12986 if (R.empty() && IsUsingIfExists)
12988 UsingName.getName()),
12989 AS_public);
12990
12991 // Try to correct typos if possible. If constructor name lookup finds no
12992 // results, that means the named class has no explicit constructors, and we
12993 // suppressed declaring implicit ones (probably because it's dependent or
12994 // invalid).
12995 if (R.empty() &&
12997 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12998 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12999 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13000 auto *II = NameInfo.getName().getAsIdentifierInfo();
13001 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13003 isa<TranslationUnitDecl>(LookupContext) &&
13004 getSourceManager().isInSystemHeader(UsingLoc))
13005 return nullptr;
13006 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13007 dyn_cast<CXXRecordDecl>(CurContext));
13008 if (TypoCorrection Corrected =
13009 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13011 // We reject candidates where DroppedSpecifier == true, hence the
13012 // literal '0' below.
13013 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13014 << NameInfo.getName() << LookupContext << 0
13015 << SS.getRange());
13016
13017 // If we picked a correction with no attached Decl we can't do anything
13018 // useful with it, bail out.
13019 NamedDecl *ND = Corrected.getCorrectionDecl();
13020 if (!ND)
13021 return BuildInvalid();
13022
13023 // If we corrected to an inheriting constructor, handle it as one.
13024 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13025 if (RD && RD->isInjectedClassName()) {
13026 // The parent of the injected class name is the class itself.
13027 RD = cast<CXXRecordDecl>(RD->getParent());
13028
13029 // Fix up the information we'll use to build the using declaration.
13030 if (Corrected.WillReplaceSpecifier()) {
13032 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13033 QualifierLoc.getSourceRange());
13034 QualifierLoc = Builder.getWithLocInContext(Context);
13035 }
13036
13037 // In this case, the name we introduce is the name of a derived class
13038 // constructor.
13039 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13042 UsingName.setNamedTypeInfo(nullptr);
13043 for (auto *Ctor : LookupConstructors(RD))
13044 R.addDecl(Ctor);
13045 R.resolveKind();
13046 } else {
13047 // FIXME: Pick up all the declarations if we found an overloaded
13048 // function.
13049 UsingName.setName(ND->getDeclName());
13050 R.addDecl(ND);
13051 }
13052 } else {
13053 Diag(IdentLoc, diag::err_no_member)
13054 << NameInfo.getName() << LookupContext << SS.getRange();
13055 return BuildInvalid();
13056 }
13057 }
13058
13059 if (R.isAmbiguous())
13060 return BuildInvalid();
13061
13062 if (HasTypenameKeyword) {
13063 // If we asked for a typename and got a non-type decl, error out.
13064 if (!R.getAsSingle<TypeDecl>() &&
13066 Diag(IdentLoc, diag::err_using_typename_non_type);
13067 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13068 Diag((*I)->getUnderlyingDecl()->getLocation(),
13069 diag::note_using_decl_target);
13070 return BuildInvalid();
13071 }
13072 } else {
13073 // If we asked for a non-typename and we got a type, error out,
13074 // but only if this is an instantiation of an unresolved using
13075 // decl. Otherwise just silently find the type name.
13076 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13077 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13078 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13079 return BuildInvalid();
13080 }
13081 }
13082
13083 // C++14 [namespace.udecl]p6:
13084 // A using-declaration shall not name a namespace.
13085 if (R.getAsSingle<NamespaceDecl>()) {
13086 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13087 << SS.getRange();
13088 return BuildInvalid();
13089 }
13090
13091 UsingDecl *UD = BuildValid();
13092
13093 // Some additional rules apply to inheriting constructors.
13094 if (UsingName.getName().getNameKind() ==
13096 // Suppress access diagnostics; the access check is instead performed at the
13097 // point of use for an inheriting constructor.
13100 return UD;
13101 }
13102
13103 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13104 UsingShadowDecl *PrevDecl = nullptr;
13105 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13106 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13107 }
13108
13109 return UD;
13110}
13111
13113 SourceLocation UsingLoc,
13114 SourceLocation EnumLoc,
13115 SourceLocation NameLoc,
13117 EnumDecl *ED) {
13118 bool Invalid = false;
13119
13121 /// In class scope, check if this is a duplicate, for better a diagnostic.
13122 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13123 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13125
13126 LookupName(Previous, S);
13127
13128 for (NamedDecl *D : Previous)
13129 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13130 if (UED->getEnumDecl() == ED) {
13131 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13132 << SourceRange(EnumLoc, NameLoc);
13133 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13134 Invalid = true;
13135 break;
13136 }
13137 }
13138
13139 if (RequireCompleteEnumDecl(ED, NameLoc))
13140 Invalid = true;
13141
13143 EnumLoc, NameLoc, EnumType);
13144 UD->setAccess(AS);
13145 CurContext->addDecl(UD);
13146
13147 if (Invalid) {
13148 UD->setInvalidDecl();
13149 return UD;
13150 }
13151
13152 // Create the shadow decls for each enumerator
13153 for (EnumConstantDecl *EC : ED->enumerators()) {
13154 UsingShadowDecl *PrevDecl = nullptr;
13155 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13158 LookupName(Previous, S);
13160
13161 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13162 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13163 }
13164
13165 return UD;
13166}
13167
13169 ArrayRef<NamedDecl *> Expansions) {
13170 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13171 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13172 isa<UsingPackDecl>(InstantiatedFrom));
13173
13174 auto *UPD =
13175 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13176 UPD->setAccess(InstantiatedFrom->getAccess());
13177 CurContext->addDecl(UPD);
13178 return UPD;
13179}
13180
13181/// Additional checks for a using declaration referring to a constructor name.
13183 assert(!UD->hasTypename() && "expecting a constructor name");
13184
13185 const Type *SourceType = UD->getQualifier()->getAsType();
13186 assert(SourceType &&
13187 "Using decl naming constructor doesn't have type in scope spec.");
13188 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13189
13190 // Check whether the named type is a direct base class.
13191 bool AnyDependentBases = false;
13192 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13193 AnyDependentBases);
13194 if (!Base && !AnyDependentBases) {
13195 Diag(UD->getUsingLoc(),
13196 diag::err_using_decl_constructor_not_in_direct_base)
13197 << UD->getNameInfo().getSourceRange()
13198 << QualType(SourceType, 0) << TargetClass;
13199 UD->setInvalidDecl();
13200 return true;
13201 }
13202
13203 if (Base)
13204 Base->setInheritConstructors();
13205
13206 return false;
13207}
13208
13209/// Checks that the given using declaration is not an invalid
13210/// redeclaration. Note that this is checking only for the using decl
13211/// itself, not for any ill-formedness among the UsingShadowDecls.
13213 bool HasTypenameKeyword,
13214 const CXXScopeSpec &SS,
13215 SourceLocation NameLoc,
13216 const LookupResult &Prev) {
13217 NestedNameSpecifier *Qual = SS.getScopeRep();
13218
13219 // C++03 [namespace.udecl]p8:
13220 // C++0x [namespace.udecl]p10:
13221 // A using-declaration is a declaration and can therefore be used
13222 // repeatedly where (and only where) multiple declarations are
13223 // allowed.
13224 //
13225 // That's in non-member contexts.
13227 // A dependent qualifier outside a class can only ever resolve to an
13228 // enumeration type. Therefore it conflicts with any other non-type
13229 // declaration in the same scope.
13230 // FIXME: How should we check for dependent type-type conflicts at block
13231 // scope?
13232 if (Qual->isDependent() && !HasTypenameKeyword) {
13233 for (auto *D : Prev) {
13234 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13235 bool OldCouldBeEnumerator =
13236 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13237 Diag(NameLoc,
13238 OldCouldBeEnumerator ? diag::err_redefinition
13239 : diag::err_redefinition_different_kind)
13240 << Prev.getLookupName();
13241 Diag(D->getLocation(), diag::note_previous_definition);
13242 return true;
13243 }
13244 }
13245 }
13246 return false;
13247 }
13248
13249 const NestedNameSpecifier *CNNS =
13251 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13252 NamedDecl *D = *I;
13253
13254 bool DTypename;
13255 NestedNameSpecifier *DQual;
13256 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13257 DTypename = UD->hasTypename();
13258 DQual = UD->getQualifier();
13259 } else if (UnresolvedUsingValueDecl *UD
13260 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13261 DTypename = false;
13262 DQual = UD->getQualifier();
13263 } else if (UnresolvedUsingTypenameDecl *UD
13264 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13265 DTypename = true;
13266 DQual = UD->getQualifier();
13267 } else continue;
13268
13269 // using decls differ if one says 'typename' and the other doesn't.
13270 // FIXME: non-dependent using decls?
13271 if (HasTypenameKeyword != DTypename) continue;
13272
13273 // using decls differ if they name different scopes (but note that
13274 // template instantiation can cause this check to trigger when it
13275 // didn't before instantiation).
13276 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13277 continue;
13278
13279 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13280 Diag(D->getLocation(), diag::note_using_decl) << 1;
13281 return true;
13282 }
13283
13284 return false;
13285}
13286
13287/// Checks that the given nested-name qualifier used in a using decl
13288/// in the current context is appropriately related to the current
13289/// scope. If an error is found, diagnoses it and returns true.
13290/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13291/// result of that lookup. UD is likewise nullptr, except when we have an
13292/// already-populated UsingDecl whose shadow decls contain the same information
13293/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13294bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13295 const CXXScopeSpec &SS,
13296 const DeclarationNameInfo &NameInfo,
13297 SourceLocation NameLoc,
13298 const LookupResult *R, const UsingDecl *UD) {
13299 DeclContext *NamedContext = computeDeclContext(SS);
13300 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13301 "resolvable context must have exactly one set of decls");
13302
13303 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13304 // relationship.
13305 bool Cxx20Enumerator = false;
13306 if (NamedContext) {
13307 EnumConstantDecl *EC = nullptr;
13308 if (R)
13309 EC = R->getAsSingle<EnumConstantDecl>();
13310 else if (UD && UD->shadow_size() == 1)
13311 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13312 if (EC)
13313 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13314
13315 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13316 // C++14 [namespace.udecl]p7:
13317 // A using-declaration shall not name a scoped enumerator.
13318 // C++20 p1099 permits enumerators.
13319 if (EC && R && ED->isScoped())
13320 Diag(SS.getBeginLoc(),
13322 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13323 : diag::ext_using_decl_scoped_enumerator)
13324 << SS.getRange();
13325
13326 // We want to consider the scope of the enumerator
13327 NamedContext = ED->getDeclContext();
13328 }
13329 }
13330
13331 if (!CurContext->isRecord()) {
13332 // C++03 [namespace.udecl]p3:
13333 // C++0x [namespace.udecl]p8:
13334 // A using-declaration for a class member shall be a member-declaration.
13335 // C++20 [namespace.udecl]p7
13336 // ... other than an enumerator ...
13337
13338 // If we weren't able to compute a valid scope, it might validly be a
13339 // dependent class or enumeration scope. If we have a 'typename' keyword,
13340 // the scope must resolve to a class type.
13341 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13342 : !HasTypename)
13343 return false; // OK
13344
13345 Diag(NameLoc,
13346 Cxx20Enumerator
13347 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13348 : diag::err_using_decl_can_not_refer_to_class_member)
13349 << SS.getRange();
13350
13351 if (Cxx20Enumerator)
13352 return false; // OK
13353
13354 auto *RD = NamedContext
13355 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13356 : nullptr;
13357 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13358 // See if there's a helpful fixit
13359
13360 if (!R) {
13361 // We will have already diagnosed the problem on the template
13362 // definition, Maybe we should do so again?
13363 } else if (R->getAsSingle<TypeDecl>()) {
13364 if (getLangOpts().CPlusPlus11) {
13365 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13366 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13367 << 0 // alias declaration
13369 NameInfo.getName().getAsString() +
13370 " = ");
13371 } else {
13372 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13373 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13374 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13375 << 1 // typedef declaration
13376 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13378 InsertLoc, " " + NameInfo.getName().getAsString());
13379 }
13380 } else if (R->getAsSingle<VarDecl>()) {
13381 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13382 // repeating the type of the static data member here.
13383 FixItHint FixIt;
13384 if (getLangOpts().CPlusPlus11) {
13385 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13387 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13388 }
13389
13390 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13391 << 2 // reference declaration
13392 << FixIt;
13393 } else if (R->getAsSingle<EnumConstantDecl>()) {
13394 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13395 // repeating the type of the enumeration here, and we can't do so if
13396 // the type is anonymous.
13397 FixItHint FixIt;
13398 if (getLangOpts().CPlusPlus11) {
13399 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13401 UsingLoc,
13402 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13403 }
13404
13405 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13406 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13407 << FixIt;
13408 }
13409 }
13410
13411 return true; // Fail
13412 }
13413
13414 // If the named context is dependent, we can't decide much.
13415 if (!NamedContext) {
13416 // FIXME: in C++0x, we can diagnose if we can prove that the
13417 // nested-name-specifier does not refer to a base class, which is
13418 // still possible in some cases.
13419
13420 // Otherwise we have to conservatively report that things might be
13421 // okay.
13422 return false;
13423 }
13424
13425 // The current scope is a record.
13426 if (!NamedContext->isRecord()) {
13427 // Ideally this would point at the last name in the specifier,
13428 // but we don't have that level of source info.
13429 Diag(SS.getBeginLoc(),
13430 Cxx20Enumerator
13431 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13432 : diag::err_using_decl_nested_name_specifier_is_not_class)
13433 << SS.getScopeRep() << SS.getRange();
13434
13435 if (Cxx20Enumerator)
13436 return false; // OK
13437
13438 return true;
13439 }
13440
13441 if (!NamedContext->isDependentContext() &&
13442 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13443 return true;
13444
13445 if (getLangOpts().CPlusPlus11) {
13446 // C++11 [namespace.udecl]p3:
13447 // In a using-declaration used as a member-declaration, the
13448 // nested-name-specifier shall name a base class of the class
13449 // being defined.
13450
13451 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13452 cast<CXXRecordDecl>(NamedContext))) {
13453
13454 if (Cxx20Enumerator) {
13455 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13456 << SS.getRange();
13457 return false;
13458 }
13459
13460 if (CurContext == NamedContext) {
13461 Diag(SS.getBeginLoc(),
13462 diag::err_using_decl_nested_name_specifier_is_current_class)
13463 << SS.getRange();
13464 return !getLangOpts().CPlusPlus20;
13465 }
13466
13467 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13468 Diag(SS.getBeginLoc(),
13469 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13470 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13471 << SS.getRange();
13472 }
13473 return true;
13474 }
13475
13476 return false;
13477 }
13478
13479 // C++03 [namespace.udecl]p4:
13480 // A using-declaration used as a member-declaration shall refer
13481 // to a member of a base class of the class being defined [etc.].
13482
13483 // Salient point: SS doesn't have to name a base class as long as
13484 // lookup only finds members from base classes. Therefore we can
13485 // diagnose here only if we can prove that can't happen,
13486 // i.e. if the class hierarchies provably don't intersect.
13487
13488 // TODO: it would be nice if "definitely valid" results were cached
13489 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13490 // need to be repeated.
13491
13493 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13494 Bases.insert(Base);
13495 return true;
13496 };
13497
13498 // Collect all bases. Return false if we find a dependent base.
13499 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13500 return false;
13501
13502 // Returns true if the base is dependent or is one of the accumulated base
13503 // classes.
13504 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13505 return !Bases.count(Base);
13506 };
13507
13508 // Return false if the class has a dependent base or if it or one
13509 // of its bases is present in the base set of the current context.
13510 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13511 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13512 return false;
13513
13514 Diag(SS.getRange().getBegin(),
13515 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13516 << SS.getScopeRep()
13517 << cast<CXXRecordDecl>(CurContext)
13518 << SS.getRange();
13519
13520 return true;
13521}
13522
13524 MultiTemplateParamsArg TemplateParamLists,
13525 SourceLocation UsingLoc, UnqualifiedId &Name,
13526 const ParsedAttributesView &AttrList,
13527 TypeResult Type, Decl *DeclFromDeclSpec) {
13528 // Get the innermost enclosing declaration scope.
13529 S = S->getDeclParent();
13530
13531 if (Type.isInvalid())
13532 return nullptr;
13533
13534 bool Invalid = false;
13536 TypeSourceInfo *TInfo = nullptr;
13537 GetTypeFromParser(Type.get(), &TInfo);
13538
13539 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13540 return nullptr;
13541
13542 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13544 Invalid = true;
13546 TInfo->getTypeLoc().getBeginLoc());
13547 }
13548
13549 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13550 TemplateParamLists.size()
13553 LookupName(Previous, S);
13554
13555 // Warn about shadowing the name of a template parameter.
13556 if (Previous.isSingleResult() &&
13557 Previous.getFoundDecl()->isTemplateParameter()) {
13558 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13559 Previous.clear();
13560 }
13561
13562 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13563 "name in alias declaration must be an identifier");
13565 Name.StartLocation,
13566 Name.Identifier, TInfo);
13567
13568 NewTD->setAccess(AS);
13569
13570 if (Invalid)
13571 NewTD->setInvalidDecl();
13572
13573 ProcessDeclAttributeList(S, NewTD, AttrList);
13574 AddPragmaAttributes(S, NewTD);
13575 ProcessAPINotes(NewTD);
13576
13578 Invalid |= NewTD->isInvalidDecl();
13579
13580 bool Redeclaration = false;
13581
13582 NamedDecl *NewND;
13583 if (TemplateParamLists.size()) {
13584 TypeAliasTemplateDecl *OldDecl = nullptr;
13585 TemplateParameterList *OldTemplateParams = nullptr;
13586
13587 if (TemplateParamLists.size() != 1) {
13588 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13589 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13590 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13591 }
13592 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13593
13594 // Check that we can declare a template here.
13595 if (CheckTemplateDeclScope(S, TemplateParams))
13596 return nullptr;
13597
13598 // Only consider previous declarations in the same scope.
13599 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13600 /*ExplicitInstantiationOrSpecialization*/false);
13601 if (!Previous.empty()) {
13602 Redeclaration = true;
13603
13604 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13605 if (!OldDecl && !Invalid) {
13606 Diag(UsingLoc, diag::err_redefinition_different_kind)
13607 << Name.Identifier;
13608
13609 NamedDecl *OldD = Previous.getRepresentativeDecl();
13610 if (OldD->getLocation().isValid())
13611 Diag(OldD->getLocation(), diag::note_previous_definition);
13612
13613 Invalid = true;
13614 }
13615
13616 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13617 if (TemplateParameterListsAreEqual(TemplateParams,
13618 OldDecl->getTemplateParameters(),
13619 /*Complain=*/true,
13621 OldTemplateParams =
13623 else
13624 Invalid = true;
13625
13626 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13627 if (!Invalid &&
13629 NewTD->getUnderlyingType())) {
13630 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13631 // but we can't reasonably accept it.
13632 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13633 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13634 if (OldTD->getLocation().isValid())
13635 Diag(OldTD->getLocation(), diag::note_previous_definition);
13636 Invalid = true;
13637 }
13638 }
13639 }
13640
13641 // Merge any previous default template arguments into our parameters,
13642 // and check the parameter list.
13643 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13645 return nullptr;
13646
13647 TypeAliasTemplateDecl *NewDecl =
13649 Name.Identifier, TemplateParams,
13650 NewTD);
13651 NewTD->setDescribedAliasTemplate(NewDecl);
13652
13653 NewDecl->setAccess(AS);
13654
13655 if (Invalid)
13656 NewDecl->setInvalidDecl();
13657 else if (OldDecl) {
13658 NewDecl->setPreviousDecl(OldDecl);
13659 CheckRedeclarationInModule(NewDecl, OldDecl);
13660 }
13661
13662 NewND = NewDecl;
13663 } else {
13664 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13666 handleTagNumbering(TD, S);
13667 }
13668 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13669 NewND = NewTD;
13670 }
13671
13672 PushOnScopeChains(NewND, S);
13673 ActOnDocumentableDecl(NewND);
13674 return NewND;
13675}
13676
13678 SourceLocation AliasLoc,
13679 IdentifierInfo *Alias, CXXScopeSpec &SS,
13680 SourceLocation IdentLoc,
13681 IdentifierInfo *Ident) {
13682
13683 // Lookup the namespace name.
13684 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13685 LookupParsedName(R, S, &SS);
13686
13687 if (R.isAmbiguous())
13688 return nullptr;
13689
13690 if (R.empty()) {
13691 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13692 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13693 return nullptr;
13694 }
13695 }
13696 assert(!R.isAmbiguous() && !R.empty());
13698
13699 // Check if we have a previous declaration with the same name.
13700 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13702 LookupName(PrevR, S);
13703
13704 // Check we're not shadowing a template parameter.
13705 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13707 PrevR.clear();
13708 }
13709
13710 // Filter out any other lookup result from an enclosing scope.
13711 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13712 /*AllowInlineNamespace*/false);
13713
13714 // Find the previous declaration and check that we can redeclare it.
13715 NamespaceAliasDecl *Prev = nullptr;
13716 if (PrevR.isSingleResult()) {
13717 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13718 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13719 // We already have an alias with the same name that points to the same
13720 // namespace; check that it matches.
13721 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13722 Prev = AD;
13723 } else if (isVisible(PrevDecl)) {
13724 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13725 << Alias;
13726 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13727 << AD->getNamespace();
13728 return nullptr;
13729 }
13730 } else if (isVisible(PrevDecl)) {
13731 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13732 ? diag::err_redefinition
13733 : diag::err_redefinition_different_kind;
13734 Diag(AliasLoc, DiagID) << Alias;
13735 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13736 return nullptr;
13737 }
13738 }
13739
13740 // The use of a nested name specifier may trigger deprecation warnings.
13741 DiagnoseUseOfDecl(ND, IdentLoc);
13742
13744 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13745 Alias, SS.getWithLocInContext(Context),
13746 IdentLoc, ND);
13747 if (Prev)
13748 AliasDecl->setPreviousDecl(Prev);
13749
13751 return AliasDecl;
13752}
13753
13754namespace {
13755struct SpecialMemberExceptionSpecInfo
13756 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13757 SourceLocation Loc;
13759
13760 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13763 SourceLocation Loc)
13764 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13765
13766 bool visitBase(CXXBaseSpecifier *Base);
13767 bool visitField(FieldDecl *FD);
13768
13769 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13770 unsigned Quals);
13771
13772 void visitSubobjectCall(Subobject Subobj,
13774};
13775}
13776
13777bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13778 auto *RT = Base->getType()->getAs<RecordType>();
13779 if (!RT)
13780 return false;
13781
13782 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13783 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13784 if (auto *BaseCtor = SMOR.getMethod()) {
13785 visitSubobjectCall(Base, BaseCtor);
13786 return false;
13787 }
13788
13789 visitClassSubobject(BaseClass, Base, 0);
13790 return false;
13791}
13792
13793bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13795 Expr *E = FD->getInClassInitializer();
13796 if (!E)
13797 // FIXME: It's a little wasteful to build and throw away a
13798 // CXXDefaultInitExpr here.
13799 // FIXME: We should have a single context note pointing at Loc, and
13800 // this location should be MD->getLocation() instead, since that's
13801 // the location where we actually use the default init expression.
13802 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13803 if (E)
13804 ExceptSpec.CalledExpr(E);
13805 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13806 ->getAs<RecordType>()) {
13807 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13808 FD->getType().getCVRQualifiers());
13809 }
13810 return false;
13811}
13812
13813void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13814 Subobject Subobj,
13815 unsigned Quals) {
13816 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13817 bool IsMutable = Field && Field->isMutable();
13818 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13819}
13820
13821void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13822 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13823 // Note, if lookup fails, it doesn't matter what exception specification we
13824 // choose because the special member will be deleted.
13825 if (CXXMethodDecl *MD = SMOR.getMethod())
13826 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13827}
13828
13830 llvm::APSInt Result;
13832 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13833 ExplicitSpec.setExpr(Converted.get());
13834 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13835 ExplicitSpec.setKind(Result.getBoolValue()
13838 return true;
13839 }
13841 return false;
13842}
13843
13846 if (!ExplicitExpr->isTypeDependent())
13848 return ES;
13849}
13850
13855 ComputingExceptionSpec CES(S, MD, Loc);
13856
13857 CXXRecordDecl *ClassDecl = MD->getParent();
13858
13859 // C++ [except.spec]p14:
13860 // An implicitly declared special member function (Clause 12) shall have an
13861 // exception-specification. [...]
13862 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13863 if (ClassDecl->isInvalidDecl())
13864 return Info.ExceptSpec;
13865
13866 // FIXME: If this diagnostic fires, we're probably missing a check for
13867 // attempting to resolve an exception specification before it's known
13868 // at a higher level.
13869 if (S.RequireCompleteType(MD->getLocation(),
13870 S.Context.getRecordType(ClassDecl),
13871 diag::err_exception_spec_incomplete_type))
13872 return Info.ExceptSpec;
13873
13874 // C++1z [except.spec]p7:
13875 // [Look for exceptions thrown by] a constructor selected [...] to
13876 // initialize a potentially constructed subobject,
13877 // C++1z [except.spec]p8:
13878 // The exception specification for an implicitly-declared destructor, or a
13879 // destructor without a noexcept-specifier, is potentially-throwing if and
13880 // only if any of the destructors for any of its potentially constructed
13881 // subojects is potentially throwing.
13882 // FIXME: We respect the first rule but ignore the "potentially constructed"
13883 // in the second rule to resolve a core issue (no number yet) that would have
13884 // us reject:
13885 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13886 // struct B : A {};
13887 // struct C : B { void f(); };
13888 // ... due to giving B::~B() a non-throwing exception specification.
13889 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13890 : Info.VisitAllBases);
13891
13892 return Info.ExceptSpec;
13893}
13894
13895namespace {
13896/// RAII object to register a special member as being currently declared.
13897struct DeclaringSpecialMember {
13898 Sema &S;
13900 Sema::ContextRAII SavedContext;
13901 bool WasAlreadyBeingDeclared;
13902
13903 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13904 : S(S), D(RD, CSM), SavedContext(S, RD) {
13905 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13906 if (WasAlreadyBeingDeclared)
13907 // This almost never happens, but if it does, ensure that our cache
13908 // doesn't contain a stale result.
13909 S.SpecialMemberCache.clear();
13910 else {
13911 // Register a note to be produced if we encounter an error while
13912 // declaring the special member.
13915 // FIXME: We don't have a location to use here. Using the class's
13916 // location maintains the fiction that we declare all special members
13917 // with the class, but (1) it's not clear that lying about that helps our
13918 // users understand what's going on, and (2) there may be outer contexts
13919 // on the stack (some of which are relevant) and printing them exposes
13920 // our lies.
13922 Ctx.Entity = RD;
13923 Ctx.SpecialMember = CSM;
13925 }
13926 }
13927 ~DeclaringSpecialMember() {
13928 if (!WasAlreadyBeingDeclared) {
13929 S.SpecialMembersBeingDeclared.erase(D);
13931 }
13932 }
13933
13934 /// Are we already trying to declare this special member?
13935 bool isAlreadyBeingDeclared() const {
13936 return WasAlreadyBeingDeclared;
13937 }
13938};
13939}
13940
13942 // Look up any existing declarations, but don't trigger declaration of all
13943 // implicit special members with this name.
13944 DeclarationName Name = FD->getDeclName();
13947 for (auto *D : FD->getParent()->lookup(Name))
13948 if (auto *Acceptable = R.getAcceptableDecl(D))
13949 R.addDecl(Acceptable);
13950 R.resolveKind();
13952
13953 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13955}
13956
13957void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13958 QualType ResultTy,
13959 ArrayRef<QualType> Args) {
13960 // Build an exception specification pointing back at this constructor.
13962
13964 if (AS != LangAS::Default) {
13965 EPI.TypeQuals.addAddressSpace(AS);
13966 }
13967
13968 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13969 SpecialMem->setType(QT);
13970
13971 // During template instantiation of implicit special member functions we need
13972 // a reliable TypeSourceInfo for the function prototype in order to allow
13973 // functions to be substituted.
13975 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13976 TypeSourceInfo *TSI =
13978 SpecialMem->setTypeSourceInfo(TSI);
13979 }
13980}
13981
13983 CXXRecordDecl *ClassDecl) {
13984 // C++ [class.ctor]p5:
13985 // A default constructor for a class X is a constructor of class X
13986 // that can be called without an argument. If there is no
13987 // user-declared constructor for class X, a default constructor is
13988 // implicitly declared. An implicitly-declared default constructor
13989 // is an inline public member of its class.
13990 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13991 "Should not build implicit default constructor!");
13992
13993 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13994 if (DSM.isAlreadyBeingDeclared())
13995 return nullptr;
13996
13997 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13999 false);
14000
14001 // Create the actual constructor declaration.
14002 CanQualType ClassType
14004 SourceLocation ClassLoc = ClassDecl->getLocation();
14005 DeclarationName Name
14007 DeclarationNameInfo NameInfo(Name, ClassLoc);
14009 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14010 /*TInfo=*/nullptr, ExplicitSpecifier(),
14011 getCurFPFeatures().isFPConstrained(),
14012 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14015 DefaultCon->setAccess(AS_public);
14016 DefaultCon->setDefaulted();
14017
14018 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
14019
14020 if (getLangOpts().CUDA)
14022 DefaultCon,
14023 /* ConstRHS */ false,
14024 /* Diagnose */ false);
14025
14026 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14027 // constructors is easy to compute.
14028 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14029
14030 // Note that we have declared this constructor.
14032
14033 Scope *S = getScopeForContext(ClassDecl);
14035
14037 SetDeclDeleted(DefaultCon, ClassLoc);
14038
14039 if (S)
14040 PushOnScopeChains(DefaultCon, S, false);
14041 ClassDecl->addDecl(DefaultCon);
14042
14043 return DefaultCon;
14044}
14045
14047 CXXConstructorDecl *Constructor) {
14048 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14049 !Constructor->doesThisDeclarationHaveABody() &&
14050 !Constructor->isDeleted()) &&
14051 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14052 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14053 return;
14054
14055 CXXRecordDecl *ClassDecl = Constructor->getParent();
14056 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14057 if (ClassDecl->isInvalidDecl()) {
14058 return;
14059 }
14060
14061 SynthesizedFunctionScope Scope(*this, Constructor);
14062
14063 // The exception specification is needed because we are defining the
14064 // function.
14065 ResolveExceptionSpec(CurrentLocation,
14066 Constructor->getType()->castAs<FunctionProtoType>());
14067 MarkVTableUsed(CurrentLocation, ClassDecl);
14068
14069 // Add a context note for diagnostics produced after this point.
14070 Scope.addContextNote(CurrentLocation);
14071
14072 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14073 Constructor->setInvalidDecl();
14074 return;
14075 }
14076
14077 SourceLocation Loc = Constructor->getEndLoc().isValid()
14078 ? Constructor->getEndLoc()
14079 : Constructor->getLocation();
14080 Constructor->setBody(new (Context) CompoundStmt(Loc));
14081 Constructor->markUsed(Context);
14082
14084 L->CompletedImplicitDefinition(Constructor);
14085 }
14086
14087 DiagnoseUninitializedFields(*this, Constructor);
14088}
14089
14091 // Perform any delayed checks on exception specifications.
14093}
14094
14095/// Find or create the fake constructor we synthesize to model constructing an
14096/// object of a derived class via a constructor of a base class.
14099 CXXConstructorDecl *BaseCtor,
14101 CXXRecordDecl *Derived = Shadow->getParent();
14102 SourceLocation UsingLoc = Shadow->getLocation();
14103
14104 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14105 // For now we use the name of the base class constructor as a member of the
14106 // derived class to indicate a (fake) inherited constructor name.
14107 DeclarationName Name = BaseCtor->getDeclName();
14108
14109 // Check to see if we already have a fake constructor for this inherited
14110 // constructor call.
14111 for (NamedDecl *Ctor : Derived->lookup(Name))
14112 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14113 ->getInheritedConstructor()
14114 .getConstructor(),
14115 BaseCtor))
14116 return cast<CXXConstructorDecl>(Ctor);
14117
14118 DeclarationNameInfo NameInfo(Name, UsingLoc);
14119 TypeSourceInfo *TInfo =
14120 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14121 FunctionProtoTypeLoc ProtoLoc =
14123
14124 // Check the inherited constructor is valid and find the list of base classes
14125 // from which it was inherited.
14126 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14127
14128 bool Constexpr =
14129 BaseCtor->isConstexpr() &&
14131 false, BaseCtor, &ICI);
14132
14134 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14135 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14136 /*isInline=*/true,
14137 /*isImplicitlyDeclared=*/true,
14139 InheritedConstructor(Shadow, BaseCtor),
14140 BaseCtor->getTrailingRequiresClause());
14141 if (Shadow->isInvalidDecl())
14142 DerivedCtor->setInvalidDecl();
14143
14144 // Build an unevaluated exception specification for this fake constructor.
14145 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14148 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14149 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14150 FPT->getParamTypes(), EPI));
14151
14152 // Build the parameter declarations.
14154 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14155 TypeSourceInfo *TInfo =
14158 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14159 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14160 PD->setScopeInfo(0, I);
14161 PD->setImplicit();
14162 // Ensure attributes are propagated onto parameters (this matters for
14163 // format, pass_object_size, ...).
14164 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14165 ParamDecls.push_back(PD);
14166 ProtoLoc.setParam(I, PD);
14167 }
14168
14169 // Set up the new constructor.
14170 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14171 DerivedCtor->setAccess(BaseCtor->getAccess());
14172 DerivedCtor->setParams(ParamDecls);
14173 Derived->addDecl(DerivedCtor);
14174
14175 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
14176 SetDeclDeleted(DerivedCtor, UsingLoc);
14177
14178 return DerivedCtor;
14179}
14180
14182 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14185 /*Diagnose*/true);
14186}
14187
14189 CXXConstructorDecl *Constructor) {
14190 CXXRecordDecl *ClassDecl = Constructor->getParent();
14191 assert(Constructor->getInheritedConstructor() &&
14192 !Constructor->doesThisDeclarationHaveABody() &&
14193 !Constructor->isDeleted());
14194 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14195 return;
14196
14197 // Initializations are performed "as if by a defaulted default constructor",
14198 // so enter the appropriate scope.
14199 SynthesizedFunctionScope Scope(*this, Constructor);
14200
14201 // The exception specification is needed because we are defining the
14202 // function.
14203 ResolveExceptionSpec(CurrentLocation,
14204 Constructor->getType()->castAs<FunctionProtoType>());
14205 MarkVTableUsed(CurrentLocation, ClassDecl);
14206
14207 // Add a context note for diagnostics produced after this point.
14208 Scope.addContextNote(CurrentLocation);
14209
14211 Constructor->getInheritedConstructor().getShadowDecl();
14212 CXXConstructorDecl *InheritedCtor =
14213 Constructor->getInheritedConstructor().getConstructor();
14214
14215 // [class.inhctor.init]p1:
14216 // initialization proceeds as if a defaulted default constructor is used to
14217 // initialize the D object and each base class subobject from which the
14218 // constructor was inherited
14219
14220 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14221 CXXRecordDecl *RD = Shadow->getParent();
14222 SourceLocation InitLoc = Shadow->getLocation();
14223
14224 // Build explicit initializers for all base classes from which the
14225 // constructor was inherited.
14227 for (bool VBase : {false, true}) {
14228 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14229 if (B.isVirtual() != VBase)
14230 continue;
14231
14232 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14233 if (!BaseRD)
14234 continue;
14235
14236 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14237 if (!BaseCtor.first)
14238 continue;
14239
14240 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14242 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14243
14244 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14245 Inits.push_back(new (Context) CXXCtorInitializer(
14246 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14247 SourceLocation()));
14248 }
14249 }
14250
14251 // We now proceed as if for a defaulted default constructor, with the relevant
14252 // initializers replaced.
14253
14254 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14255 Constructor->setInvalidDecl();
14256 return;
14257 }
14258
14259 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14260 Constructor->markUsed(Context);
14261
14263 L->CompletedImplicitDefinition(Constructor);
14264 }
14265
14266 DiagnoseUninitializedFields(*this, Constructor);
14267}
14268
14270 // C++ [class.dtor]p2:
14271 // If a class has no user-declared destructor, a destructor is
14272 // declared implicitly. An implicitly-declared destructor is an
14273 // inline public member of its class.
14274 assert(ClassDecl->needsImplicitDestructor());
14275
14276 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
14277 if (DSM.isAlreadyBeingDeclared())
14278 return nullptr;
14279
14280 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14282 false);
14283
14284 // Create the actual destructor declaration.
14285 CanQualType ClassType
14287 SourceLocation ClassLoc = ClassDecl->getLocation();
14288 DeclarationName Name
14290 DeclarationNameInfo NameInfo(Name, ClassLoc);
14292 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14293 getCurFPFeatures().isFPConstrained(),
14294 /*isInline=*/true,
14295 /*isImplicitlyDeclared=*/true,
14298 Destructor->setAccess(AS_public);
14299 Destructor->setDefaulted();
14300
14301 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14302
14303 if (getLangOpts().CUDA)
14305 Destructor,
14306 /* ConstRHS */ false,
14307 /* Diagnose */ false);
14308
14309 // We don't need to use SpecialMemberIsTrivial here; triviality for
14310 // destructors is easy to compute.
14311 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14312 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14313 ClassDecl->hasTrivialDestructorForCall());
14314
14315 // Note that we have declared this destructor.
14317
14318 Scope *S = getScopeForContext(ClassDecl);
14320
14321 // We can't check whether an implicit destructor is deleted before we complete
14322 // the definition of the class, because its validity depends on the alignment
14323 // of the class. We'll check this from ActOnFields once the class is complete.
14324 if (ClassDecl->isCompleteDefinition() &&
14326 SetDeclDeleted(Destructor, ClassLoc);
14327
14328 // Introduce this destructor into its scope.
14329 if (S)
14330 PushOnScopeChains(Destructor, S, false);
14331 ClassDecl->addDecl(Destructor);
14332
14333 return Destructor;
14334}
14335
14337 CXXDestructorDecl *Destructor) {
14338 assert((Destructor->isDefaulted() &&
14339 !Destructor->doesThisDeclarationHaveABody() &&
14340 !Destructor->isDeleted()) &&
14341 "DefineImplicitDestructor - call it for implicit default dtor");
14342 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14343 return;
14344
14345 CXXRecordDecl *ClassDecl = Destructor->getParent();
14346 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14347
14348 SynthesizedFunctionScope Scope(*this, Destructor);
14349
14350 // The exception specification is needed because we are defining the
14351 // function.
14352 ResolveExceptionSpec(CurrentLocation,
14353 Destructor->getType()->castAs<FunctionProtoType>());
14354 MarkVTableUsed(CurrentLocation, ClassDecl);
14355
14356 // Add a context note for diagnostics produced after this point.
14357 Scope.addContextNote(CurrentLocation);
14358
14359 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14360 Destructor->getParent());
14361
14362 if (CheckDestructor(Destructor)) {
14363 Destructor->setInvalidDecl();
14364 return;
14365 }
14366
14367 SourceLocation Loc = Destructor->getEndLoc().isValid()
14368 ? Destructor->getEndLoc()
14369 : Destructor->getLocation();
14370 Destructor->setBody(new (Context) CompoundStmt(Loc));
14371 Destructor->markUsed(Context);
14372
14374 L->CompletedImplicitDefinition(Destructor);
14375 }
14376}
14377
14379 CXXDestructorDecl *Destructor) {
14380 if (Destructor->isInvalidDecl())
14381 return;
14382
14383 CXXRecordDecl *ClassDecl = Destructor->getParent();
14385 "implicit complete dtors unneeded outside MS ABI");
14386 assert(ClassDecl->getNumVBases() > 0 &&
14387 "complete dtor only exists for classes with vbases");
14388
14389 SynthesizedFunctionScope Scope(*this, Destructor);
14390
14391 // Add a context note for diagnostics produced after this point.
14392 Scope.addContextNote(CurrentLocation);
14393
14394 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14395}
14396
14397/// Perform any semantic analysis which needs to be delayed until all
14398/// pending class member declarations have been parsed.
14400 // If the context is an invalid C++ class, just suppress these checks.
14401 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14402 if (Record->isInvalidDecl()) {
14405 return;
14406 }
14408 }
14409}
14410
14413
14414 if (!DelayedDllExportMemberFunctions.empty()) {
14416 std::swap(DelayedDllExportMemberFunctions, WorkList);
14417 for (CXXMethodDecl *M : WorkList) {
14418 DefineDefaultedFunction(*this, M, M->getLocation());
14419
14420 // Pass the method to the consumer to get emitted. This is not necessary
14421 // for explicit instantiation definitions, as they will get emitted
14422 // anyway.
14423 if (M->getParent()->getTemplateSpecializationKind() !=
14426 }
14427 }
14428}
14429
14431 if (!DelayedDllExportClasses.empty()) {
14432 // Calling ReferenceDllExportedMembers might cause the current function to
14433 // be called again, so use a local copy of DelayedDllExportClasses.
14435 std::swap(DelayedDllExportClasses, WorkList);
14436 for (CXXRecordDecl *Class : WorkList)
14438 }
14439}
14440
14442 assert(getLangOpts().CPlusPlus11 &&
14443 "adjusting dtor exception specs was introduced in c++11");
14444
14445 if (Destructor->isDependentContext())
14446 return;
14447
14448 // C++11 [class.dtor]p3:
14449 // A declaration of a destructor that does not have an exception-
14450 // specification is implicitly considered to have the same exception-
14451 // specification as an implicit declaration.
14452 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14453 if (DtorType->hasExceptionSpec())
14454 return;
14455
14456 // Replace the destructor's type, building off the existing one. Fortunately,
14457 // the only thing of interest in the destructor type is its extended info.
14458 // The return and arguments are fixed.
14459 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14461 EPI.ExceptionSpec.SourceDecl = Destructor;
14462 Destructor->setType(
14463 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14464
14465 // FIXME: If the destructor has a body that could throw, and the newly created
14466 // spec doesn't allow exceptions, we should emit a warning, because this
14467 // change in behavior can break conforming C++03 programs at runtime.
14468 // However, we don't have a body or an exception specification yet, so it
14469 // needs to be done somewhere else.
14470}
14471
14472namespace {
14473/// An abstract base class for all helper classes used in building the
14474// copy/move operators. These classes serve as factory functions and help us
14475// avoid using the same Expr* in the AST twice.
14476class ExprBuilder {
14477 ExprBuilder(const ExprBuilder&) = delete;
14478 ExprBuilder &operator=(const ExprBuilder&) = delete;
14479
14480protected:
14481 static Expr *assertNotNull(Expr *E) {
14482 assert(E && "Expression construction must not fail.");
14483 return E;
14484 }
14485
14486public:
14487 ExprBuilder() {}
14488 virtual ~ExprBuilder() {}
14489
14490 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14491};
14492
14493class RefBuilder: public ExprBuilder {
14494 VarDecl *Var;
14495 QualType VarType;
14496
14497public:
14498 Expr *build(Sema &S, SourceLocation Loc) const override {
14499 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14500 }
14501
14502 RefBuilder(VarDecl *Var, QualType VarType)
14503 : Var(Var), VarType(VarType) {}
14504};
14505
14506class ThisBuilder: public ExprBuilder {
14507public:
14508 Expr *build(Sema &S, SourceLocation Loc) const override {
14509 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14510 }
14511};
14512
14513class CastBuilder: public ExprBuilder {
14514 const ExprBuilder &Builder;
14515 QualType Type;
14517 const CXXCastPath &Path;
14518
14519public:
14520 Expr *build(Sema &S, SourceLocation Loc) const override {
14521 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14522 CK_UncheckedDerivedToBase, Kind,
14523 &Path).get());
14524 }
14525
14526 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14527 const CXXCastPath &Path)
14528 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14529};
14530
14531class DerefBuilder: public ExprBuilder {
14532 const ExprBuilder &Builder;
14533
14534public:
14535 Expr *build(Sema &S, SourceLocation Loc) const override {
14536 return assertNotNull(
14537 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14538 }
14539
14540 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14541};
14542
14543class MemberBuilder: public ExprBuilder {
14544 const ExprBuilder &Builder;
14545 QualType Type;
14546 CXXScopeSpec SS;
14547 bool IsArrow;
14548 LookupResult &MemberLookup;
14549
14550public:
14551 Expr *build(Sema &S, SourceLocation Loc) const override {
14552 return assertNotNull(S.BuildMemberReferenceExpr(
14553 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14554 nullptr, MemberLookup, nullptr, nullptr).get());
14555 }
14556
14557 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14558 LookupResult &MemberLookup)
14559 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14560 MemberLookup(MemberLookup) {}
14561};
14562
14563class MoveCastBuilder: public ExprBuilder {
14564 const ExprBuilder &Builder;
14565
14566public:
14567 Expr *build(Sema &S, SourceLocation Loc) const override {
14568 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14569 }
14570
14571 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14572};
14573
14574class LvalueConvBuilder: public ExprBuilder {
14575 const ExprBuilder &Builder;
14576
14577public:
14578 Expr *build(Sema &S, SourceLocation Loc) const override {
14579 return assertNotNull(
14580 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14581 }
14582
14583 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14584};
14585
14586class SubscriptBuilder: public ExprBuilder {
14587 const ExprBuilder &Base;
14588 const ExprBuilder &Index;
14589
14590public:
14591 Expr *build(Sema &S, SourceLocation Loc) const override {
14592 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14593 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14594 }
14595
14596 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14597 : Base(Base), Index(Index) {}
14598};
14599
14600} // end anonymous namespace
14601
14602/// When generating a defaulted copy or move assignment operator, if a field
14603/// should be copied with __builtin_memcpy rather than via explicit assignments,
14604/// do so. This optimization only applies for arrays of scalars, and for arrays
14605/// of class type where the selected copy/move-assignment operator is trivial.
14606static StmtResult
14608 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14609 // Compute the size of the memory buffer to be copied.
14610 QualType SizeType = S.Context.getSizeType();
14611 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14613
14614 // Take the address of the field references for "from" and "to". We
14615 // directly construct UnaryOperators here because semantic analysis
14616 // does not permit us to take the address of an xvalue.
14617 Expr *From = FromB.build(S, Loc);
14618 From = UnaryOperator::Create(
14619 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14620 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14621 Expr *To = ToB.build(S, Loc);
14623 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14624 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14625
14626 const Type *E = T->getBaseElementTypeUnsafe();
14627 bool NeedsCollectableMemCpy =
14628 E->isRecordType() &&
14629 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14630
14631 // Create a reference to the __builtin_objc_memmove_collectable function
14632 StringRef MemCpyName = NeedsCollectableMemCpy ?
14633 "__builtin_objc_memmove_collectable" :
14634 "__builtin_memcpy";
14635 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14637 S.LookupName(R, S.TUScope, true);
14638
14639 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14640 if (!MemCpy)
14641 // Something went horribly wrong earlier, and we will have complained
14642 // about it.
14643 return StmtError();
14644
14645 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14646 VK_PRValue, Loc, nullptr);
14647 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14648
14649 Expr *CallArgs[] = {
14650 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14651 };
14652 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14653 Loc, CallArgs, Loc);
14654
14655 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14656 return Call.getAs<Stmt>();
14657}
14658
14659/// Builds a statement that copies/moves the given entity from \p From to
14660/// \c To.
14661///
14662/// This routine is used to copy/move the members of a class with an
14663/// implicitly-declared copy/move assignment operator. When the entities being
14664/// copied are arrays, this routine builds for loops to copy them.
14665///
14666/// \param S The Sema object used for type-checking.
14667///
14668/// \param Loc The location where the implicit copy/move is being generated.
14669///
14670/// \param T The type of the expressions being copied/moved. Both expressions
14671/// must have this type.
14672///
14673/// \param To The expression we are copying/moving to.
14674///
14675/// \param From The expression we are copying/moving from.
14676///
14677/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14678/// Otherwise, it's a non-static member subobject.
14679///
14680/// \param Copying Whether we're copying or moving.
14681///
14682/// \param Depth Internal parameter recording the depth of the recursion.
14683///
14684/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14685/// if a memcpy should be used instead.
14686static StmtResult
14688 const ExprBuilder &To, const ExprBuilder &From,
14689 bool CopyingBaseSubobject, bool Copying,
14690 unsigned Depth = 0) {
14691 // C++11 [class.copy]p28:
14692 // Each subobject is assigned in the manner appropriate to its type:
14693 //
14694 // - if the subobject is of class type, as if by a call to operator= with
14695 // the subobject as the object expression and the corresponding
14696 // subobject of x as a single function argument (as if by explicit
14697 // qualification; that is, ignoring any possible virtual overriding
14698 // functions in more derived classes);
14699 //
14700 // C++03 [class.copy]p13:
14701 // - if the subobject is of class type, the copy assignment operator for
14702 // the class is used (as if by explicit qualification; that is,
14703 // ignoring any possible virtual overriding functions in more derived
14704 // classes);
14705 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14706 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14707
14708 // Look for operator=.
14709 DeclarationName Name
14711 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14712 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14713
14714 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14715 // operator.
14716 if (!S.getLangOpts().CPlusPlus11) {
14717 LookupResult::Filter F = OpLookup.makeFilter();
14718 while (F.hasNext()) {
14719 NamedDecl *D = F.next();
14720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14721 if (Method->isCopyAssignmentOperator() ||
14722 (!Copying && Method->isMoveAssignmentOperator()))
14723 continue;
14724
14725 F.erase();
14726 }
14727 F.done();
14728 }
14729
14730 // Suppress the protected check (C++ [class.protected]) for each of the
14731 // assignment operators we found. This strange dance is required when
14732 // we're assigning via a base classes's copy-assignment operator. To
14733 // ensure that we're getting the right base class subobject (without
14734 // ambiguities), we need to cast "this" to that subobject type; to
14735 // ensure that we don't go through the virtual call mechanism, we need
14736 // to qualify the operator= name with the base class (see below). However,
14737 // this means that if the base class has a protected copy assignment
14738 // operator, the protected member access check will fail. So, we
14739 // rewrite "protected" access to "public" access in this case, since we
14740 // know by construction that we're calling from a derived class.
14741 if (CopyingBaseSubobject) {
14742 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14743 L != LEnd; ++L) {
14744 if (L.getAccess() == AS_protected)
14745 L.setAccess(AS_public);
14746 }
14747 }
14748
14749 // Create the nested-name-specifier that will be used to qualify the
14750 // reference to operator=; this is required to suppress the virtual
14751 // call mechanism.
14752 CXXScopeSpec SS;
14753 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14754 SS.MakeTrivial(S.Context,
14755 NestedNameSpecifier::Create(S.Context, nullptr, false,
14756 CanonicalT),
14757 Loc);
14758
14759 // Create the reference to operator=.
14760 ExprResult OpEqualRef
14761 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14762 SS, /*TemplateKWLoc=*/SourceLocation(),
14763 /*FirstQualifierInScope=*/nullptr,
14764 OpLookup,
14765 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14766 /*SuppressQualifierCheck=*/true);
14767 if (OpEqualRef.isInvalid())
14768 return StmtError();
14769
14770 // Build the call to the assignment operator.
14771
14772 Expr *FromInst = From.build(S, Loc);
14773 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14774 OpEqualRef.getAs<Expr>(),
14775 Loc, FromInst, Loc);
14776 if (Call.isInvalid())
14777 return StmtError();
14778
14779 // If we built a call to a trivial 'operator=' while copying an array,
14780 // bail out. We'll replace the whole shebang with a memcpy.
14781 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14782 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14783 return StmtResult((Stmt*)nullptr);
14784
14785 // Convert to an expression-statement, and clean up any produced
14786 // temporaries.
14787 return S.ActOnExprStmt(Call);
14788 }
14789
14790 // - if the subobject is of scalar type, the built-in assignment
14791 // operator is used.
14792 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14793 if (!ArrayTy) {
14794 ExprResult Assignment = S.CreateBuiltinBinOp(
14795 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14796 if (Assignment.isInvalid())
14797 return StmtError();
14798 return S.ActOnExprStmt(Assignment);
14799 }
14800
14801 // - if the subobject is an array, each element is assigned, in the
14802 // manner appropriate to the element type;
14803
14804 // Construct a loop over the array bounds, e.g.,
14805 //
14806 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14807 //
14808 // that will copy each of the array elements.
14809 QualType SizeType = S.Context.getSizeType();
14810
14811 // Create the iteration variable.
14812 IdentifierInfo *IterationVarName = nullptr;
14813 {
14814 SmallString<8> Str;
14815 llvm::raw_svector_ostream OS(Str);
14816 OS << "__i" << Depth;
14817 IterationVarName = &S.Context.Idents.get(OS.str());
14818 }
14819 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14820 IterationVarName, SizeType,
14821 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14822 SC_None);
14823
14824 // Initialize the iteration variable to zero.
14825 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14826 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14827
14828 // Creates a reference to the iteration variable.
14829 RefBuilder IterationVarRef(IterationVar, SizeType);
14830 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14831
14832 // Create the DeclStmt that holds the iteration variable.
14833 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14834
14835 // Subscript the "from" and "to" expressions with the iteration variable.
14836 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14837 MoveCastBuilder FromIndexMove(FromIndexCopy);
14838 const ExprBuilder *FromIndex;
14839 if (Copying)
14840 FromIndex = &FromIndexCopy;
14841 else
14842 FromIndex = &FromIndexMove;
14843
14844 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14845
14846 // Build the copy/move for an individual element of the array.
14849 ToIndex, *FromIndex, CopyingBaseSubobject,
14850 Copying, Depth + 1);
14851 // Bail out if copying fails or if we determined that we should use memcpy.
14852 if (Copy.isInvalid() || !Copy.get())
14853 return Copy;
14854
14855 // Create the comparison against the array bound.
14856 llvm::APInt Upper
14857 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14858 Expr *Comparison = BinaryOperator::Create(
14859 S.Context, IterationVarRefRVal.build(S, Loc),
14860 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14863
14864 // Create the pre-increment of the iteration variable. We can determine
14865 // whether the increment will overflow based on the value of the array
14866 // bound.
14867 Expr *Increment = UnaryOperator::Create(
14868 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14869 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14870
14871 // Construct the loop that copies all elements of this array.
14872 return S.ActOnForStmt(
14873 Loc, Loc, InitStmt,
14874 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14875 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14876}
14877
14878static StmtResult
14880 const ExprBuilder &To, const ExprBuilder &From,
14881 bool CopyingBaseSubobject, bool Copying) {
14882 // Maybe we should use a memcpy?
14883 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14885 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14886
14888 CopyingBaseSubobject,
14889 Copying, 0));
14890
14891 // If we ended up picking a trivial assignment operator for an array of a
14892 // non-trivially-copyable class type, just emit a memcpy.
14893 if (!Result.isInvalid() && !Result.get())
14894 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14895
14896 return Result;
14897}
14898
14900 // Note: The following rules are largely analoguous to the copy
14901 // constructor rules. Note that virtual bases are not taken into account
14902 // for determining the argument type of the operator. Note also that
14903 // operators taking an object instead of a reference are allowed.
14904 assert(ClassDecl->needsImplicitCopyAssignment());
14905
14906 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14907 if (DSM.isAlreadyBeingDeclared())
14908 return nullptr;
14909
14910 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14912 ArgType, nullptr);
14914 if (AS != LangAS::Default)
14915 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14916 QualType RetType = Context.getLValueReferenceType(ArgType);
14917 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14918 if (Const)
14919 ArgType = ArgType.withConst();
14920
14921 ArgType = Context.getLValueReferenceType(ArgType);
14922
14923 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14925 Const);
14926
14927 // An implicitly-declared copy assignment operator is an inline public
14928 // member of its class.
14930 SourceLocation ClassLoc = ClassDecl->getLocation();
14931 DeclarationNameInfo NameInfo(Name, ClassLoc);
14932 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14933 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14934 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14935 getCurFPFeatures().isFPConstrained(),
14936 /*isInline=*/true,
14938 SourceLocation());
14939 CopyAssignment->setAccess(AS_public);
14940 CopyAssignment->setDefaulted();
14941 CopyAssignment->setImplicit();
14942
14943 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14944
14945 if (getLangOpts().CUDA)
14947 CopyAssignment,
14948 /* ConstRHS */ Const,
14949 /* Diagnose */ false);
14950
14951 // Add the parameter to the operator.
14952 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14953 ClassLoc, ClassLoc,
14954 /*Id=*/nullptr, ArgType,
14955 /*TInfo=*/nullptr, SC_None,
14956 nullptr);
14957 CopyAssignment->setParams(FromParam);
14958
14959 CopyAssignment->setTrivial(
14961 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14962 : ClassDecl->hasTrivialCopyAssignment());
14963
14964 // Note that we have added this copy-assignment operator.
14966
14967 Scope *S = getScopeForContext(ClassDecl);
14968 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14969
14970 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14972 SetDeclDeleted(CopyAssignment, ClassLoc);
14973 }
14974
14975 if (S)
14976 PushOnScopeChains(CopyAssignment, S, false);
14977 ClassDecl->addDecl(CopyAssignment);
14978
14979 return CopyAssignment;
14980}
14981
14982/// Diagnose an implicit copy operation for a class which is odr-used, but
14983/// which is deprecated because the class has a user-declared copy constructor,
14984/// copy assignment operator, or destructor.
14986 assert(CopyOp->isImplicit());
14987
14988 CXXRecordDecl *RD = CopyOp->getParent();
14989 CXXMethodDecl *UserDeclaredOperation = nullptr;
14990
14991 if (RD->hasUserDeclaredDestructor()) {
14992 UserDeclaredOperation = RD->getDestructor();
14993 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14995 // Find any user-declared copy constructor.
14996 for (auto *I : RD->ctors()) {
14997 if (I->isCopyConstructor()) {
14998 UserDeclaredOperation = I;
14999 break;
15000 }
15001 }
15002 assert(UserDeclaredOperation);
15003 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15005 // Find any user-declared move assignment operator.
15006 for (auto *I : RD->methods()) {
15007 if (I->isCopyAssignmentOperator()) {
15008 UserDeclaredOperation = I;
15009 break;
15010 }
15011 }
15012 assert(UserDeclaredOperation);
15013 }
15014
15015 if (UserDeclaredOperation) {
15016 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15017 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15018 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15019 unsigned DiagID =
15020 (UDOIsUserProvided && UDOIsDestructor)
15021 ? diag::warn_deprecated_copy_with_user_provided_dtor
15022 : (UDOIsUserProvided && !UDOIsDestructor)
15023 ? diag::warn_deprecated_copy_with_user_provided_copy
15024 : (!UDOIsUserProvided && UDOIsDestructor)
15025 ? diag::warn_deprecated_copy_with_dtor
15026 : diag::warn_deprecated_copy;
15027 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15028 << RD << IsCopyAssignment;
15029 }
15030}
15031
15033 CXXMethodDecl *CopyAssignOperator) {
15034 assert((CopyAssignOperator->isDefaulted() &&
15035 CopyAssignOperator->isOverloadedOperator() &&
15036 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15037 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15038 !CopyAssignOperator->isDeleted()) &&
15039 "DefineImplicitCopyAssignment called for wrong function");
15040 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15041 return;
15042
15043 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15044 if (ClassDecl->isInvalidDecl()) {
15045 CopyAssignOperator->setInvalidDecl();
15046 return;
15047 }
15048
15049 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15050
15051 // The exception specification is needed because we are defining the
15052 // function.
15053 ResolveExceptionSpec(CurrentLocation,
15054 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15055
15056 // Add a context note for diagnostics produced after this point.
15057 Scope.addContextNote(CurrentLocation);
15058
15059 // C++11 [class.copy]p18:
15060 // The [definition of an implicitly declared copy assignment operator] is
15061 // deprecated if the class has a user-declared copy constructor or a
15062 // user-declared destructor.
15063 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15064 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15065
15066 // C++0x [class.copy]p30:
15067 // The implicitly-defined or explicitly-defaulted copy assignment operator
15068 // for a non-union class X performs memberwise copy assignment of its
15069 // subobjects. The direct base classes of X are assigned first, in the
15070 // order of their declaration in the base-specifier-list, and then the
15071 // immediate non-static data members of X are assigned, in the order in
15072 // which they were declared in the class definition.
15073
15074 // The statements that form the synthesized function body.
15075 SmallVector<Stmt*, 8> Statements;
15076
15077 // The parameter for the "other" object, which we are copying from.
15078 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15079 Qualifiers OtherQuals = Other->getType().getQualifiers();
15080 QualType OtherRefType = Other->getType();
15081 if (OtherRefType->isLValueReferenceType()) {
15082 OtherRefType = OtherRefType->getPointeeType();
15083 OtherQuals = OtherRefType.getQualifiers();
15084 }
15085
15086 // Our location for everything implicitly-generated.
15087 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15088 ? CopyAssignOperator->getEndLoc()
15089 : CopyAssignOperator->getLocation();
15090
15091 // Builds a DeclRefExpr for the "other" object.
15092 RefBuilder OtherRef(Other, OtherRefType);
15093
15094 // Builds the function object parameter.
15095 std::optional<ThisBuilder> This;
15096 std::optional<DerefBuilder> DerefThis;
15097 std::optional<RefBuilder> ExplicitObject;
15098 bool IsArrow = false;
15099 QualType ObjectType;
15100 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15101 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15102 if (ObjectType->isReferenceType())
15103 ObjectType = ObjectType->getPointeeType();
15104 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15105 } else {
15106 ObjectType = getCurrentThisType();
15107 This.emplace();
15108 DerefThis.emplace(*This);
15109 IsArrow = !LangOpts.HLSL;
15110 }
15111 ExprBuilder &ObjectParameter =
15112 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15113 : static_cast<ExprBuilder &>(*This);
15114
15115 // Assign base classes.
15116 bool Invalid = false;
15117 for (auto &Base : ClassDecl->bases()) {
15118 // Form the assignment:
15119 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15120 QualType BaseType = Base.getType().getUnqualifiedType();
15121 if (!BaseType->isRecordType()) {
15122 Invalid = true;
15123 continue;
15124 }
15125
15126 CXXCastPath BasePath;
15127 BasePath.push_back(&Base);
15128
15129 // Construct the "from" expression, which is an implicit cast to the
15130 // appropriately-qualified base type.
15131 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15132 VK_LValue, BasePath);
15133
15134 // Dereference "this".
15135 CastBuilder To(
15136 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15137 : static_cast<ExprBuilder &>(*DerefThis),
15138 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15139 VK_LValue, BasePath);
15140
15141 // Build the copy.
15142 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15143 To, From,
15144 /*CopyingBaseSubobject=*/true,
15145 /*Copying=*/true);
15146 if (Copy.isInvalid()) {
15147 CopyAssignOperator->setInvalidDecl();
15148 return;
15149 }
15150
15151 // Success! Record the copy.
15152 Statements.push_back(Copy.getAs<Expr>());
15153 }
15154
15155 // Assign non-static members.
15156 for (auto *Field : ClassDecl->fields()) {
15157 // FIXME: We should form some kind of AST representation for the implied
15158 // memcpy in a union copy operation.
15159 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15160 continue;
15161
15162 if (Field->isInvalidDecl()) {
15163 Invalid = true;
15164 continue;
15165 }
15166
15167 // Check for members of reference type; we can't copy those.
15168 if (Field->getType()->isReferenceType()) {
15169 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15170 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15171 Diag(Field->getLocation(), diag::note_declared_at);
15172 Invalid = true;
15173 continue;
15174 }
15175
15176 // Check for members of const-qualified, non-class type.
15177 QualType BaseType = Context.getBaseElementType(Field->getType());
15178 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15179 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15180 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15181 Diag(Field->getLocation(), diag::note_declared_at);
15182 Invalid = true;
15183 continue;
15184 }
15185
15186 // Suppress assigning zero-width bitfields.
15187 if (Field->isZeroLengthBitField(Context))
15188 continue;
15189
15190 QualType FieldType = Field->getType().getNonReferenceType();
15191 if (FieldType->isIncompleteArrayType()) {
15192 assert(ClassDecl->hasFlexibleArrayMember() &&
15193 "Incomplete array type is not valid");
15194 continue;
15195 }
15196
15197 // Build references to the field in the object we're copying from and to.
15198 CXXScopeSpec SS; // Intentionally empty
15199 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15201 MemberLookup.addDecl(Field);
15202 MemberLookup.resolveKind();
15203
15204 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15205 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15206 // Build the copy of this field.
15207 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15208 To, From,
15209 /*CopyingBaseSubobject=*/false,
15210 /*Copying=*/true);
15211 if (Copy.isInvalid()) {
15212 CopyAssignOperator->setInvalidDecl();
15213 return;
15214 }
15215
15216 // Success! Record the copy.
15217 Statements.push_back(Copy.getAs<Stmt>());
15218 }
15219
15220 if (!Invalid) {
15221 // Add a "return *this;"
15222 Expr *ThisExpr =
15223 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15224 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15225 : static_cast<ExprBuilder &>(*DerefThis))
15226 .build(*this, Loc);
15227 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15228 if (Return.isInvalid())
15229 Invalid = true;
15230 else
15231 Statements.push_back(Return.getAs<Stmt>());
15232 }
15233
15234 if (Invalid) {
15235 CopyAssignOperator->setInvalidDecl();
15236 return;
15237 }
15238
15239 StmtResult Body;
15240 {
15241 CompoundScopeRAII CompoundScope(*this);
15242 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15243 /*isStmtExpr=*/false);
15244 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15245 }
15246 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15247 CopyAssignOperator->markUsed(Context);
15248
15250 L->CompletedImplicitDefinition(CopyAssignOperator);
15251 }
15252}
15253
15255 assert(ClassDecl->needsImplicitMoveAssignment());
15256
15257 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
15258 if (DSM.isAlreadyBeingDeclared())
15259 return nullptr;
15260
15261 // Note: The following rules are largely analoguous to the move
15262 // constructor rules.
15263
15264 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15266 ArgType, nullptr);
15268 if (AS != LangAS::Default)
15269 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15270 QualType RetType = Context.getLValueReferenceType(ArgType);
15271 ArgType = Context.getRValueReferenceType(ArgType);
15272
15273 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15275 false);
15276
15277 // An implicitly-declared move assignment operator is an inline public
15278 // member of its class.
15280 SourceLocation ClassLoc = ClassDecl->getLocation();
15281 DeclarationNameInfo NameInfo(Name, ClassLoc);
15282 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15283 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15284 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15285 getCurFPFeatures().isFPConstrained(),
15286 /*isInline=*/true,
15288 SourceLocation());
15289 MoveAssignment->setAccess(AS_public);
15290 MoveAssignment->setDefaulted();
15291 MoveAssignment->setImplicit();
15292
15293 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15294
15295 if (getLangOpts().CUDA)
15297 MoveAssignment,
15298 /* ConstRHS */ false,
15299 /* Diagnose */ false);
15300
15301 // Add the parameter to the operator.
15302 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15303 ClassLoc, ClassLoc,
15304 /*Id=*/nullptr, ArgType,
15305 /*TInfo=*/nullptr, SC_None,
15306 nullptr);
15307 MoveAssignment->setParams(FromParam);
15308
15309 MoveAssignment->setTrivial(
15311 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
15312 : ClassDecl->hasTrivialMoveAssignment());
15313
15314 // Note that we have added this copy-assignment operator.
15316
15317 Scope *S = getScopeForContext(ClassDecl);
15318 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15319
15320 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
15322 SetDeclDeleted(MoveAssignment, ClassLoc);
15323 }
15324
15325 if (S)
15326 PushOnScopeChains(MoveAssignment, S, false);
15327 ClassDecl->addDecl(MoveAssignment);
15328
15329 return MoveAssignment;
15330}
15331
15332/// Check if we're implicitly defining a move assignment operator for a class
15333/// with virtual bases. Such a move assignment might move-assign the virtual
15334/// base multiple times.
15336 SourceLocation CurrentLocation) {
15337 assert(!Class->isDependentContext() && "should not define dependent move");
15338
15339 // Only a virtual base could get implicitly move-assigned multiple times.
15340 // Only a non-trivial move assignment can observe this. We only want to
15341 // diagnose if we implicitly define an assignment operator that assigns
15342 // two base classes, both of which move-assign the same virtual base.
15343 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15344 Class->getNumBases() < 2)
15345 return;
15346
15348 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15349 VBaseMap VBases;
15350
15351 for (auto &BI : Class->bases()) {
15352 Worklist.push_back(&BI);
15353 while (!Worklist.empty()) {
15354 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15355 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15356
15357 // If the base has no non-trivial move assignment operators,
15358 // we don't care about moves from it.
15359 if (!Base->hasNonTrivialMoveAssignment())
15360 continue;
15361
15362 // If there's nothing virtual here, skip it.
15363 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15364 continue;
15365
15366 // If we're not actually going to call a move assignment for this base,
15367 // or the selected move assignment is trivial, skip it.
15370 /*ConstArg*/false, /*VolatileArg*/false,
15371 /*RValueThis*/true, /*ConstThis*/false,
15372 /*VolatileThis*/false);
15373 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15375 continue;
15376
15377 if (BaseSpec->isVirtual()) {
15378 // We're going to move-assign this virtual base, and its move
15379 // assignment operator is not trivial. If this can happen for
15380 // multiple distinct direct bases of Class, diagnose it. (If it
15381 // only happens in one base, we'll diagnose it when synthesizing
15382 // that base class's move assignment operator.)
15383 CXXBaseSpecifier *&Existing =
15384 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15385 .first->second;
15386 if (Existing && Existing != &BI) {
15387 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15388 << Class << Base;
15389 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15390 << (Base->getCanonicalDecl() ==
15392 << Base << Existing->getType() << Existing->getSourceRange();
15393 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15394 << (Base->getCanonicalDecl() ==
15395 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15396 << Base << BI.getType() << BaseSpec->getSourceRange();
15397
15398 // Only diagnose each vbase once.
15399 Existing = nullptr;
15400 }
15401 } else {
15402 // Only walk over bases that have defaulted move assignment operators.
15403 // We assume that any user-provided move assignment operator handles
15404 // the multiple-moves-of-vbase case itself somehow.
15405 if (!SMOR.getMethod()->isDefaulted())
15406 continue;
15407
15408 // We're going to move the base classes of Base. Add them to the list.
15409 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15410 }
15411 }
15412 }
15413}
15414
15416 CXXMethodDecl *MoveAssignOperator) {
15417 assert((MoveAssignOperator->isDefaulted() &&
15418 MoveAssignOperator->isOverloadedOperator() &&
15419 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15420 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15421 !MoveAssignOperator->isDeleted()) &&
15422 "DefineImplicitMoveAssignment called for wrong function");
15423 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15424 return;
15425
15426 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15427 if (ClassDecl->isInvalidDecl()) {
15428 MoveAssignOperator->setInvalidDecl();
15429 return;
15430 }
15431
15432 // C++0x [class.copy]p28:
15433 // The implicitly-defined or move assignment operator for a non-union class
15434 // X performs memberwise move assignment of its subobjects. The direct base
15435 // classes of X are assigned first, in the order of their declaration in the
15436 // base-specifier-list, and then the immediate non-static data members of X
15437 // are assigned, in the order in which they were declared in the class
15438 // definition.
15439
15440 // Issue a warning if our implicit move assignment operator will move
15441 // from a virtual base more than once.
15442 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15443
15444 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15445
15446 // The exception specification is needed because we are defining the
15447 // function.
15448 ResolveExceptionSpec(CurrentLocation,
15449 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15450
15451 // Add a context note for diagnostics produced after this point.
15452 Scope.addContextNote(CurrentLocation);
15453
15454 // The statements that form the synthesized function body.
15455 SmallVector<Stmt*, 8> Statements;
15456
15457 // The parameter for the "other" object, which we are move from.
15458 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15459 QualType OtherRefType =
15460 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15461
15462 // Our location for everything implicitly-generated.
15463 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15464 ? MoveAssignOperator->getEndLoc()
15465 : MoveAssignOperator->getLocation();
15466
15467 // Builds a reference to the "other" object.
15468 RefBuilder OtherRef(Other, OtherRefType);
15469 // Cast to rvalue.
15470 MoveCastBuilder MoveOther(OtherRef);
15471
15472 // Builds the function object parameter.
15473 std::optional<ThisBuilder> This;
15474 std::optional<DerefBuilder> DerefThis;
15475 std::optional<RefBuilder> ExplicitObject;
15476 QualType ObjectType;
15477 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15478 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15479 if (ObjectType->isReferenceType())
15480 ObjectType = ObjectType->getPointeeType();
15481 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15482 } else {
15483 ObjectType = getCurrentThisType();
15484 This.emplace();
15485 DerefThis.emplace(*This);
15486 }
15487 ExprBuilder &ObjectParameter =
15488 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15489
15490 // Assign base classes.
15491 bool Invalid = false;
15492 for (auto &Base : ClassDecl->bases()) {
15493 // C++11 [class.copy]p28:
15494 // It is unspecified whether subobjects representing virtual base classes
15495 // are assigned more than once by the implicitly-defined copy assignment
15496 // operator.
15497 // FIXME: Do not assign to a vbase that will be assigned by some other base
15498 // class. For a move-assignment, this can result in the vbase being moved
15499 // multiple times.
15500
15501 // Form the assignment:
15502 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15503 QualType BaseType = Base.getType().getUnqualifiedType();
15504 if (!BaseType->isRecordType()) {
15505 Invalid = true;
15506 continue;
15507 }
15508
15509 CXXCastPath BasePath;
15510 BasePath.push_back(&Base);
15511
15512 // Construct the "from" expression, which is an implicit cast to the
15513 // appropriately-qualified base type.
15514 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15515
15516 // Implicitly cast "this" to the appropriately-qualified base type.
15517 // Dereference "this".
15518 CastBuilder To(
15519 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15520 : static_cast<ExprBuilder &>(*DerefThis),
15521 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15522 VK_LValue, BasePath);
15523
15524 // Build the move.
15525 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15526 To, From,
15527 /*CopyingBaseSubobject=*/true,
15528 /*Copying=*/false);
15529 if (Move.isInvalid()) {
15530 MoveAssignOperator->setInvalidDecl();
15531 return;
15532 }
15533
15534 // Success! Record the move.
15535 Statements.push_back(Move.getAs<Expr>());
15536 }
15537
15538 // Assign non-static members.
15539 for (auto *Field : ClassDecl->fields()) {
15540 // FIXME: We should form some kind of AST representation for the implied
15541 // memcpy in a union copy operation.
15542 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15543 continue;
15544
15545 if (Field->isInvalidDecl()) {
15546 Invalid = true;
15547 continue;
15548 }
15549
15550 // Check for members of reference type; we can't move those.
15551 if (Field->getType()->isReferenceType()) {
15552 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15553 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15554 Diag(Field->getLocation(), diag::note_declared_at);
15555 Invalid = true;
15556 continue;
15557 }
15558
15559 // Check for members of const-qualified, non-class type.
15560 QualType BaseType = Context.getBaseElementType(Field->getType());
15561 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15562 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15563 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15564 Diag(Field->getLocation(), diag::note_declared_at);
15565 Invalid = true;
15566 continue;
15567 }
15568
15569 // Suppress assigning zero-width bitfields.
15570 if (Field->isZeroLengthBitField(Context))
15571 continue;
15572
15573 QualType FieldType = Field->getType().getNonReferenceType();
15574 if (FieldType->isIncompleteArrayType()) {
15575 assert(ClassDecl->hasFlexibleArrayMember() &&
15576 "Incomplete array type is not valid");
15577 continue;
15578 }
15579
15580 // Build references to the field in the object we're copying from and to.
15581 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15583 MemberLookup.addDecl(Field);
15584 MemberLookup.resolveKind();
15585 MemberBuilder From(MoveOther, OtherRefType,
15586 /*IsArrow=*/false, MemberLookup);
15587 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15588 MemberLookup);
15589
15590 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15591 "Member reference with rvalue base must be rvalue except for reference "
15592 "members, which aren't allowed for move assignment.");
15593
15594 // Build the move of this field.
15595 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15596 To, From,
15597 /*CopyingBaseSubobject=*/false,
15598 /*Copying=*/false);
15599 if (Move.isInvalid()) {
15600 MoveAssignOperator->setInvalidDecl();
15601 return;
15602 }
15603
15604 // Success! Record the copy.
15605 Statements.push_back(Move.getAs<Stmt>());
15606 }
15607
15608 if (!Invalid) {
15609 // Add a "return *this;"
15610 Expr *ThisExpr =
15611 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15612 : static_cast<ExprBuilder &>(*DerefThis))
15613 .build(*this, Loc);
15614
15615 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15616 if (Return.isInvalid())
15617 Invalid = true;
15618 else
15619 Statements.push_back(Return.getAs<Stmt>());
15620 }
15621
15622 if (Invalid) {
15623 MoveAssignOperator->setInvalidDecl();
15624 return;
15625 }
15626
15627 StmtResult Body;
15628 {
15629 CompoundScopeRAII CompoundScope(*this);
15630 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15631 /*isStmtExpr=*/false);
15632 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15633 }
15634 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15635 MoveAssignOperator->markUsed(Context);
15636
15638 L->CompletedImplicitDefinition(MoveAssignOperator);
15639 }
15640}
15641
15643 CXXRecordDecl *ClassDecl) {
15644 // C++ [class.copy]p4:
15645 // If the class definition does not explicitly declare a copy
15646 // constructor, one is declared implicitly.
15647 assert(ClassDecl->needsImplicitCopyConstructor());
15648
15649 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15650 if (DSM.isAlreadyBeingDeclared())
15651 return nullptr;
15652
15653 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15654 QualType ArgType = ClassType;
15656 ArgType, nullptr);
15657 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15658 if (Const)
15659 ArgType = ArgType.withConst();
15660
15662 if (AS != LangAS::Default)
15663 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15664
15665 ArgType = Context.getLValueReferenceType(ArgType);
15666
15667 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15669 Const);
15670
15671 DeclarationName Name
15673 Context.getCanonicalType(ClassType));
15674 SourceLocation ClassLoc = ClassDecl->getLocation();
15675 DeclarationNameInfo NameInfo(Name, ClassLoc);
15676
15677 // An implicitly-declared copy constructor is an inline public
15678 // member of its class.
15680 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15681 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15682 /*isInline=*/true,
15683 /*isImplicitlyDeclared=*/true,
15686 CopyConstructor->setAccess(AS_public);
15687 CopyConstructor->setDefaulted();
15688
15689 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15690
15691 if (getLangOpts().CUDA)
15693 CopyConstructor,
15694 /* ConstRHS */ Const,
15695 /* Diagnose */ false);
15696
15697 // During template instantiation of special member functions we need a
15698 // reliable TypeSourceInfo for the parameter types in order to allow functions
15699 // to be substituted.
15700 TypeSourceInfo *TSI = nullptr;
15701 if (inTemplateInstantiation() && ClassDecl->isLambda())
15702 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15703
15704 // Add the parameter to the constructor.
15705 ParmVarDecl *FromParam =
15706 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15707 /*IdentifierInfo=*/nullptr, ArgType,
15708 /*TInfo=*/TSI, SC_None, nullptr);
15709 CopyConstructor->setParams(FromParam);
15710
15711 CopyConstructor->setTrivial(
15713 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15714 : ClassDecl->hasTrivialCopyConstructor());
15715
15716 CopyConstructor->setTrivialForCall(
15717 ClassDecl->hasAttr<TrivialABIAttr>() ||
15719 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15721 : ClassDecl->hasTrivialCopyConstructorForCall()));
15722
15723 // Note that we have declared this constructor.
15725
15726 Scope *S = getScopeForContext(ClassDecl);
15727 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15728
15729 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15731 SetDeclDeleted(CopyConstructor, ClassLoc);
15732 }
15733
15734 if (S)
15735 PushOnScopeChains(CopyConstructor, S, false);
15736 ClassDecl->addDecl(CopyConstructor);
15737
15738 return CopyConstructor;
15739}
15740
15742 CXXConstructorDecl *CopyConstructor) {
15743 assert((CopyConstructor->isDefaulted() &&
15744 CopyConstructor->isCopyConstructor() &&
15745 !CopyConstructor->doesThisDeclarationHaveABody() &&
15746 !CopyConstructor->isDeleted()) &&
15747 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15748 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15749 return;
15750
15751 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15752 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15753
15754 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15755
15756 // The exception specification is needed because we are defining the
15757 // function.
15758 ResolveExceptionSpec(CurrentLocation,
15759 CopyConstructor->getType()->castAs<FunctionProtoType>());
15760 MarkVTableUsed(CurrentLocation, ClassDecl);
15761
15762 // Add a context note for diagnostics produced after this point.
15763 Scope.addContextNote(CurrentLocation);
15764
15765 // C++11 [class.copy]p7:
15766 // The [definition of an implicitly declared copy constructor] is
15767 // deprecated if the class has a user-declared copy assignment operator
15768 // or a user-declared destructor.
15769 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15770 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15771
15772 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15773 CopyConstructor->setInvalidDecl();
15774 } else {
15775 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15776 ? CopyConstructor->getEndLoc()
15777 : CopyConstructor->getLocation();
15778 Sema::CompoundScopeRAII CompoundScope(*this);
15779 CopyConstructor->setBody(
15780 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15781 .getAs<Stmt>());
15782 CopyConstructor->markUsed(Context);
15783 }
15784
15786 L->CompletedImplicitDefinition(CopyConstructor);
15787 }
15788}
15789
15791 CXXRecordDecl *ClassDecl) {
15792 assert(ClassDecl->needsImplicitMoveConstructor());
15793
15794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15795 if (DSM.isAlreadyBeingDeclared())
15796 return nullptr;
15797
15798 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15799
15800 QualType ArgType = ClassType;
15802 ArgType, nullptr);
15804 if (AS != LangAS::Default)
15805 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15806 ArgType = Context.getRValueReferenceType(ArgType);
15807
15808 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15810 false);
15811
15812 DeclarationName Name
15814 Context.getCanonicalType(ClassType));
15815 SourceLocation ClassLoc = ClassDecl->getLocation();
15816 DeclarationNameInfo NameInfo(Name, ClassLoc);
15817
15818 // C++11 [class.copy]p11:
15819 // An implicitly-declared copy/move constructor is an inline public
15820 // member of its class.
15822 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15823 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15824 /*isInline=*/true,
15825 /*isImplicitlyDeclared=*/true,
15828 MoveConstructor->setAccess(AS_public);
15829 MoveConstructor->setDefaulted();
15830
15831 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15832
15833 if (getLangOpts().CUDA)
15835 MoveConstructor,
15836 /* ConstRHS */ false,
15837 /* Diagnose */ false);
15838
15839 // Add the parameter to the constructor.
15840 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15841 ClassLoc, ClassLoc,
15842 /*IdentifierInfo=*/nullptr,
15843 ArgType, /*TInfo=*/nullptr,
15844 SC_None, nullptr);
15845 MoveConstructor->setParams(FromParam);
15846
15847 MoveConstructor->setTrivial(
15849 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15850 : ClassDecl->hasTrivialMoveConstructor());
15851
15852 MoveConstructor->setTrivialForCall(
15853 ClassDecl->hasAttr<TrivialABIAttr>() ||
15855 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15857 : ClassDecl->hasTrivialMoveConstructorForCall()));
15858
15859 // Note that we have declared this constructor.
15861
15862 Scope *S = getScopeForContext(ClassDecl);
15863 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15864
15865 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15867 SetDeclDeleted(MoveConstructor, ClassLoc);
15868 }
15869
15870 if (S)
15871 PushOnScopeChains(MoveConstructor, S, false);
15872 ClassDecl->addDecl(MoveConstructor);
15873
15874 return MoveConstructor;
15875}
15876
15878 CXXConstructorDecl *MoveConstructor) {
15879 assert((MoveConstructor->isDefaulted() &&
15880 MoveConstructor->isMoveConstructor() &&
15881 !MoveConstructor->doesThisDeclarationHaveABody() &&
15882 !MoveConstructor->isDeleted()) &&
15883 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15884 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15885 return;
15886
15887 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15888 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15889
15890 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15891
15892 // The exception specification is needed because we are defining the
15893 // function.
15894 ResolveExceptionSpec(CurrentLocation,
15895 MoveConstructor->getType()->castAs<FunctionProtoType>());
15896 MarkVTableUsed(CurrentLocation, ClassDecl);
15897
15898 // Add a context note for diagnostics produced after this point.
15899 Scope.addContextNote(CurrentLocation);
15900
15901 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15902 MoveConstructor->setInvalidDecl();
15903 } else {
15904 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15905 ? MoveConstructor->getEndLoc()
15906 : MoveConstructor->getLocation();
15907 Sema::CompoundScopeRAII CompoundScope(*this);
15908 MoveConstructor->setBody(
15909 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15910 .getAs<Stmt>());
15911 MoveConstructor->markUsed(Context);
15912 }
15913
15915 L->CompletedImplicitDefinition(MoveConstructor);
15916 }
15917}
15918
15920 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15921}
15922
15924 SourceLocation CurrentLocation,
15925 CXXConversionDecl *Conv) {
15926 SynthesizedFunctionScope Scope(*this, Conv);
15927 assert(!Conv->getReturnType()->isUndeducedType());
15928
15929 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15930 CallingConv CC =
15931 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15932
15933 CXXRecordDecl *Lambda = Conv->getParent();
15934 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15935 FunctionDecl *Invoker =
15936 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15937 ? CallOp
15938 : Lambda->getLambdaStaticInvoker(CC);
15939
15940 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15942 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15943 if (!CallOp)
15944 return;
15945
15946 if (CallOp != Invoker) {
15948 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15949 CurrentLocation);
15950 if (!Invoker)
15951 return;
15952 }
15953 }
15954
15955 if (CallOp->isInvalidDecl())
15956 return;
15957
15958 // Mark the call operator referenced (and add to pending instantiations
15959 // if necessary).
15960 // For both the conversion and static-invoker template specializations
15961 // we construct their body's in this function, so no need to add them
15962 // to the PendingInstantiations.
15963 MarkFunctionReferenced(CurrentLocation, CallOp);
15964
15965 if (Invoker != CallOp) {
15966 // Fill in the __invoke function with a dummy implementation. IR generation
15967 // will fill in the actual details. Update its type in case it contained
15968 // an 'auto'.
15969 Invoker->markUsed(Context);
15970 Invoker->setReferenced();
15971 Invoker->setType(Conv->getReturnType()->getPointeeType());
15972 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15973 }
15974
15975 // Construct the body of the conversion function { return __invoke; }.
15976 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15977 Conv->getLocation());
15978 assert(FunctionRef && "Can't refer to __invoke function?");
15979 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15981 Conv->getLocation(), Conv->getLocation()));
15982 Conv->markUsed(Context);
15983 Conv->setReferenced();
15984
15986 L->CompletedImplicitDefinition(Conv);
15987 if (Invoker != CallOp)
15988 L->CompletedImplicitDefinition(Invoker);
15989 }
15990}
15991
15993 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15994 assert(!Conv->getParent()->isGenericLambda());
15995
15996 SynthesizedFunctionScope Scope(*this, Conv);
15997
15998 // Copy-initialize the lambda object as needed to capture it.
15999 Expr *This = ActOnCXXThis(CurrentLocation).get();
16000 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16001
16002 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16003 Conv->getLocation(),
16004 Conv, DerefThis);
16005
16006 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16007 // behavior. Note that only the general conversion function does this
16008 // (since it's unusable otherwise); in the case where we inline the
16009 // block literal, it has block literal lifetime semantics.
16010 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16011 BuildBlock = ImplicitCastExpr::Create(
16012 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16013 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16014
16015 if (BuildBlock.isInvalid()) {
16016 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16017 Conv->setInvalidDecl();
16018 return;
16019 }
16020
16021 // Create the return statement that returns the block from the conversion
16022 // function.
16023 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16024 if (Return.isInvalid()) {
16025 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16026 Conv->setInvalidDecl();
16027 return;
16028 }
16029
16030 // Set the body of the conversion function.
16031 Stmt *ReturnS = Return.get();
16033 Conv->getLocation(), Conv->getLocation()));
16034 Conv->markUsed(Context);
16035
16036 // We're done; notify the mutation listener, if any.
16038 L->CompletedImplicitDefinition(Conv);
16039 }
16040}
16041
16042/// Determine whether the given list arguments contains exactly one
16043/// "real" (non-default) argument.
16045 switch (Args.size()) {
16046 case 0:
16047 return false;
16048
16049 default:
16050 if (!Args[1]->isDefaultArgument())
16051 return false;
16052
16053 [[fallthrough]];
16054 case 1:
16055 return !Args[0]->isDefaultArgument();
16056 }
16057
16058 return false;
16059}
16060
16062 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16063 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16064 bool HadMultipleCandidates, bool IsListInitialization,
16065 bool IsStdInitListInitialization, bool RequiresZeroInit,
16066 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16067 bool Elidable = false;
16068
16069 // C++0x [class.copy]p34:
16070 // When certain criteria are met, an implementation is allowed to
16071 // omit the copy/move construction of a class object, even if the
16072 // copy/move constructor and/or destructor for the object have
16073 // side effects. [...]
16074 // - when a temporary class object that has not been bound to a
16075 // reference (12.2) would be copied/moved to a class object
16076 // with the same cv-unqualified type, the copy/move operation
16077 // can be omitted by constructing the temporary object
16078 // directly into the target of the omitted copy/move
16079 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16080 // FIXME: Converting constructors should also be accepted.
16081 // But to fix this, the logic that digs down into a CXXConstructExpr
16082 // to find the source object needs to handle it.
16083 // Right now it assumes the source object is passed directly as the
16084 // first argument.
16085 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16086 Expr *SubExpr = ExprArgs[0];
16087 // FIXME: Per above, this is also incorrect if we want to accept
16088 // converting constructors, as isTemporaryObject will
16089 // reject temporaries with different type from the
16090 // CXXRecord itself.
16091 Elidable = SubExpr->isTemporaryObject(
16092 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16093 }
16094
16095 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16096 FoundDecl, Constructor,
16097 Elidable, ExprArgs, HadMultipleCandidates,
16098 IsListInitialization,
16099 IsStdInitListInitialization, RequiresZeroInit,
16100 ConstructKind, ParenRange);
16101}
16102
16104 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16105 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16106 bool HadMultipleCandidates, bool IsListInitialization,
16107 bool IsStdInitListInitialization, bool RequiresZeroInit,
16108 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16109 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16110 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16111 // The only way to get here is if we did overlaod resolution to find the
16112 // shadow decl, so we don't need to worry about re-checking the trailing
16113 // requires clause.
16114 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16115 return ExprError();
16116 }
16117
16118 return BuildCXXConstructExpr(
16119 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16120 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16121 RequiresZeroInit, ConstructKind, ParenRange);
16122}
16123
16124/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16125/// including handling of its default argument expressions.
16127 SourceLocation ConstructLoc, QualType DeclInitType,
16128 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16129 bool HadMultipleCandidates, bool IsListInitialization,
16130 bool IsStdInitListInitialization, bool RequiresZeroInit,
16131 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16132 assert(declaresSameEntity(
16133 Constructor->getParent(),
16134 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16135 "given constructor for wrong type");
16136 MarkFunctionReferenced(ConstructLoc, Constructor);
16137 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
16138 return ExprError();
16139
16142 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16143 HadMultipleCandidates, IsListInitialization,
16144 IsStdInitListInitialization, RequiresZeroInit,
16145 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16146 Constructor);
16147}
16148
16150 if (VD->isInvalidDecl()) return;
16151 // If initializing the variable failed, don't also diagnose problems with
16152 // the destructor, they're likely related.
16153 if (VD->getInit() && VD->getInit()->containsErrors())
16154 return;
16155
16156 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16157 if (ClassDecl->isInvalidDecl()) return;
16158 if (ClassDecl->hasIrrelevantDestructor()) return;
16159 if (ClassDecl->isDependentContext()) return;
16160
16161 if (VD->isNoDestroy(getASTContext()))
16162 return;
16163
16164 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16165 // The result of `LookupDestructor` might be nullptr if the destructor is
16166 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16167 // will not be selected by `CXXRecordDecl::getDestructor()`.
16168 if (!Destructor)
16169 return;
16170 // If this is an array, we'll require the destructor during initialization, so
16171 // we can skip over this. We still want to emit exit-time destructor warnings
16172 // though.
16173 if (!VD->getType()->isArrayType()) {
16174 MarkFunctionReferenced(VD->getLocation(), Destructor);
16175 CheckDestructorAccess(VD->getLocation(), Destructor,
16176 PDiag(diag::err_access_dtor_var)
16177 << VD->getDeclName() << VD->getType());
16178 DiagnoseUseOfDecl(Destructor, VD->getLocation());
16179 }
16180
16181 if (Destructor->isTrivial()) return;
16182
16183 // If the destructor is constexpr, check whether the variable has constant
16184 // destruction now.
16185 if (Destructor->isConstexpr()) {
16186 bool HasConstantInit = false;
16187 if (VD->getInit() && !VD->getInit()->isValueDependent())
16188 HasConstantInit = VD->evaluateValue();
16190 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16191 HasConstantInit) {
16192 Diag(VD->getLocation(),
16193 diag::err_constexpr_var_requires_const_destruction) << VD;
16194 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16195 Diag(Notes[I].first, Notes[I].second);
16196 }
16197 }
16198
16199 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16200 return;
16201
16202 // Emit warning for non-trivial dtor in global scope (a real global,
16203 // class-static, function-static).
16204 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16205
16206 // TODO: this should be re-enabled for static locals by !CXAAtExit
16207 if (!VD->isStaticLocal())
16208 Diag(VD->getLocation(), diag::warn_global_destructor);
16209}
16210
16211/// Given a constructor and the set of arguments provided for the
16212/// constructor, convert the arguments and add any required default arguments
16213/// to form a proper call to this constructor.
16214///
16215/// \returns true if an error occurred, false otherwise.
16217 QualType DeclInitType, MultiExprArg ArgsPtr,
16218 SourceLocation Loc,
16219 SmallVectorImpl<Expr *> &ConvertedArgs,
16220 bool AllowExplicit,
16221 bool IsListInitialization) {
16222 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16223 unsigned NumArgs = ArgsPtr.size();
16224 Expr **Args = ArgsPtr.data();
16225
16226 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16227 unsigned NumParams = Proto->getNumParams();
16228
16229 // If too few arguments are available, we'll fill in the rest with defaults.
16230 if (NumArgs < NumParams)
16231 ConvertedArgs.reserve(NumParams);
16232 else
16233 ConvertedArgs.reserve(NumArgs);
16234
16235 VariadicCallType CallType =
16236 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16237 SmallVector<Expr *, 8> AllArgs;
16239 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16240 CallType, AllowExplicit, IsListInitialization);
16241 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16242
16243 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16244
16245 CheckConstructorCall(Constructor, DeclInitType,
16246 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16247 Loc);
16248
16249 return Invalid;
16250}
16251
16252static inline bool
16254 const FunctionDecl *FnDecl) {
16255 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16256 if (isa<NamespaceDecl>(DC)) {
16257 return SemaRef.Diag(FnDecl->getLocation(),
16258 diag::err_operator_new_delete_declared_in_namespace)
16259 << FnDecl->getDeclName();
16260 }
16261
16262 if (isa<TranslationUnitDecl>(DC) &&
16263 FnDecl->getStorageClass() == SC_Static) {
16264 return SemaRef.Diag(FnDecl->getLocation(),
16265 diag::err_operator_new_delete_declared_static)
16266 << FnDecl->getDeclName();
16267 }
16268
16269 return false;
16270}
16271
16273 const PointerType *PtrTy) {
16274 auto &Ctx = SemaRef.Context;
16275 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16276 PtrQuals.removeAddressSpace();
16277 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16278 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16279}
16280
16281static inline bool
16283 CanQualType ExpectedResultType,
16284 CanQualType ExpectedFirstParamType,
16285 unsigned DependentParamTypeDiag,
16286 unsigned InvalidParamTypeDiag) {
16287 QualType ResultType =
16288 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16289
16290 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16291 // The operator is valid on any address space for OpenCL.
16292 // Drop address space from actual and expected result types.
16293 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16294 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16295
16296 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16297 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16298 }
16299
16300 // Check that the result type is what we expect.
16301 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16302 // Reject even if the type is dependent; an operator delete function is
16303 // required to have a non-dependent result type.
16304 return SemaRef.Diag(
16305 FnDecl->getLocation(),
16306 ResultType->isDependentType()
16307 ? diag::err_operator_new_delete_dependent_result_type
16308 : diag::err_operator_new_delete_invalid_result_type)
16309 << FnDecl->getDeclName() << ExpectedResultType;
16310 }
16311
16312 // A function template must have at least 2 parameters.
16313 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16314 return SemaRef.Diag(FnDecl->getLocation(),
16315 diag::err_operator_new_delete_template_too_few_parameters)
16316 << FnDecl->getDeclName();
16317
16318 // The function decl must have at least 1 parameter.
16319 if (FnDecl->getNumParams() == 0)
16320 return SemaRef.Diag(FnDecl->getLocation(),
16321 diag::err_operator_new_delete_too_few_parameters)
16322 << FnDecl->getDeclName();
16323
16324 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16325 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16326 // The operator is valid on any address space for OpenCL.
16327 // Drop address space from actual and expected first parameter types.
16328 if (const auto *PtrTy =
16329 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16330 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16331
16332 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16333 ExpectedFirstParamType =
16334 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16335 }
16336
16337 // Check that the first parameter type is what we expect.
16338 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16339 ExpectedFirstParamType) {
16340 // The first parameter type is not allowed to be dependent. As a tentative
16341 // DR resolution, we allow a dependent parameter type if it is the right
16342 // type anyway, to allow destroying operator delete in class templates.
16343 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16344 ? DependentParamTypeDiag
16345 : InvalidParamTypeDiag)
16346 << FnDecl->getDeclName() << ExpectedFirstParamType;
16347 }
16348
16349 return false;
16350}
16351
16352static bool
16354 // C++ [basic.stc.dynamic.allocation]p1:
16355 // A program is ill-formed if an allocation function is declared in a
16356 // namespace scope other than global scope or declared static in global
16357 // scope.
16358 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16359 return true;
16360
16361 CanQualType SizeTy =
16362 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16363
16364 // C++ [basic.stc.dynamic.allocation]p1:
16365 // The return type shall be void*. The first parameter shall have type
16366 // std::size_t.
16367 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16368 SizeTy,
16369 diag::err_operator_new_dependent_param_type,
16370 diag::err_operator_new_param_type))
16371 return true;
16372
16373 // C++ [basic.stc.dynamic.allocation]p1:
16374 // The first parameter shall not have an associated default argument.
16375 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16376 return SemaRef.Diag(FnDecl->getLocation(),
16377 diag::err_operator_new_default_arg)
16378 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16379
16380 return false;
16381}
16382
16383static bool
16385 // C++ [basic.stc.dynamic.deallocation]p1:
16386 // A program is ill-formed if deallocation functions are declared in a
16387 // namespace scope other than global scope or declared static in global
16388 // scope.
16389 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16390 return true;
16391
16392 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16393
16394 // C++ P0722:
16395 // Within a class C, the first parameter of a destroying operator delete
16396 // shall be of type C *. The first parameter of any other deallocation
16397 // function shall be of type void *.
16398 CanQualType ExpectedFirstParamType =
16399 MD && MD->isDestroyingOperatorDelete()
16401 SemaRef.Context.getRecordType(MD->getParent())))
16402 : SemaRef.Context.VoidPtrTy;
16403
16404 // C++ [basic.stc.dynamic.deallocation]p2:
16405 // Each deallocation function shall return void
16407 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16408 diag::err_operator_delete_dependent_param_type,
16409 diag::err_operator_delete_param_type))
16410 return true;
16411
16412 // C++ P0722:
16413 // A destroying operator delete shall be a usual deallocation function.
16414 if (MD && !MD->getParent()->isDependentContext() &&
16416 !SemaRef.isUsualDeallocationFunction(MD)) {
16417 SemaRef.Diag(MD->getLocation(),
16418 diag::err_destroying_operator_delete_not_usual);
16419 return true;
16420 }
16421
16422 return false;
16423}
16424
16425/// CheckOverloadedOperatorDeclaration - Check whether the declaration
16426/// of this overloaded operator is well-formed. If so, returns false;
16427/// otherwise, emits appropriate diagnostics and returns true.
16429 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16430 "Expected an overloaded operator declaration");
16431
16433
16434 // C++ [over.oper]p5:
16435 // The allocation and deallocation functions, operator new,
16436 // operator new[], operator delete and operator delete[], are
16437 // described completely in 3.7.3. The attributes and restrictions
16438 // found in the rest of this subclause do not apply to them unless
16439 // explicitly stated in 3.7.3.
16440 if (Op == OO_Delete || Op == OO_Array_Delete)
16441 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16442
16443 if (Op == OO_New || Op == OO_Array_New)
16444 return CheckOperatorNewDeclaration(*this, FnDecl);
16445
16446 // C++ [over.oper]p7:
16447 // An operator function shall either be a member function or
16448 // be a non-member function and have at least one parameter
16449 // whose type is a class, a reference to a class, an enumeration,
16450 // or a reference to an enumeration.
16451 // Note: Before C++23, a member function could not be static. The only member
16452 // function allowed to be static is the call operator function.
16453 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16454 if (MethodDecl->isStatic()) {
16455 if (Op == OO_Call || Op == OO_Subscript)
16456 Diag(FnDecl->getLocation(),
16457 (LangOpts.CPlusPlus23
16458 ? diag::warn_cxx20_compat_operator_overload_static
16459 : diag::ext_operator_overload_static))
16460 << FnDecl;
16461 else
16462 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16463 << FnDecl;
16464 }
16465 } else {
16466 bool ClassOrEnumParam = false;
16467 for (auto *Param : FnDecl->parameters()) {
16468 QualType ParamType = Param->getType().getNonReferenceType();
16469 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16470 ParamType->isEnumeralType()) {
16471 ClassOrEnumParam = true;
16472 break;
16473 }
16474 }
16475
16476 if (!ClassOrEnumParam)
16477 return Diag(FnDecl->getLocation(),
16478 diag::err_operator_overload_needs_class_or_enum)
16479 << FnDecl->getDeclName();
16480 }
16481
16482 // C++ [over.oper]p8:
16483 // An operator function cannot have default arguments (8.3.6),
16484 // except where explicitly stated below.
16485 //
16486 // Only the function-call operator (C++ [over.call]p1) and the subscript
16487 // operator (CWG2507) allow default arguments.
16488 if (Op != OO_Call) {
16489 ParmVarDecl *FirstDefaultedParam = nullptr;
16490 for (auto *Param : FnDecl->parameters()) {
16491 if (Param->hasDefaultArg()) {
16492 FirstDefaultedParam = Param;
16493 break;
16494 }
16495 }
16496 if (FirstDefaultedParam) {
16497 if (Op == OO_Subscript) {
16498 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16499 ? diag::ext_subscript_overload
16500 : diag::error_subscript_overload)
16501 << FnDecl->getDeclName() << 1
16502 << FirstDefaultedParam->getDefaultArgRange();
16503 } else {
16504 return Diag(FirstDefaultedParam->getLocation(),
16505 diag::err_operator_overload_default_arg)
16506 << FnDecl->getDeclName()
16507 << FirstDefaultedParam->getDefaultArgRange();
16508 }
16509 }
16510 }
16511
16512 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16513 { false, false, false }
16514#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16515 , { Unary, Binary, MemberOnly }
16516#include "clang/Basic/OperatorKinds.def"
16517 };
16518
16519 bool CanBeUnaryOperator = OperatorUses[Op][0];
16520 bool CanBeBinaryOperator = OperatorUses[Op][1];
16521 bool MustBeMemberOperator = OperatorUses[Op][2];
16522
16523 // C++ [over.oper]p8:
16524 // [...] Operator functions cannot have more or fewer parameters
16525 // than the number required for the corresponding operator, as
16526 // described in the rest of this subclause.
16527 unsigned NumParams = FnDecl->getNumParams() +
16528 (isa<CXXMethodDecl>(FnDecl) &&
16530 ? 1
16531 : 0);
16532 if (Op != OO_Call && Op != OO_Subscript &&
16533 ((NumParams == 1 && !CanBeUnaryOperator) ||
16534 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16535 (NumParams > 2))) {
16536 // We have the wrong number of parameters.
16537 unsigned ErrorKind;
16538 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16539 ErrorKind = 2; // 2 -> unary or binary.
16540 } else if (CanBeUnaryOperator) {
16541 ErrorKind = 0; // 0 -> unary
16542 } else {
16543 assert(CanBeBinaryOperator &&
16544 "All non-call overloaded operators are unary or binary!");
16545 ErrorKind = 1; // 1 -> binary
16546 }
16547 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16548 << FnDecl->getDeclName() << NumParams << ErrorKind;
16549 }
16550
16551 if (Op == OO_Subscript && NumParams != 2) {
16552 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16553 ? diag::ext_subscript_overload
16554 : diag::error_subscript_overload)
16555 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16556 }
16557
16558 // Overloaded operators other than operator() and operator[] cannot be
16559 // variadic.
16560 if (Op != OO_Call &&
16561 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16562 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16563 << FnDecl->getDeclName();
16564 }
16565
16566 // Some operators must be member functions.
16567 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16568 return Diag(FnDecl->getLocation(),
16569 diag::err_operator_overload_must_be_member)
16570 << FnDecl->getDeclName();
16571 }
16572
16573 // C++ [over.inc]p1:
16574 // The user-defined function called operator++ implements the
16575 // prefix and postfix ++ operator. If this function is a member
16576 // function with no parameters, or a non-member function with one
16577 // parameter of class or enumeration type, it defines the prefix
16578 // increment operator ++ for objects of that type. If the function
16579 // is a member function with one parameter (which shall be of type
16580 // int) or a non-member function with two parameters (the second
16581 // of which shall be of type int), it defines the postfix
16582 // increment operator ++ for objects of that type.
16583 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16584 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16585 QualType ParamType = LastParam->getType();
16586
16587 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16588 !ParamType->isDependentType())
16589 return Diag(LastParam->getLocation(),
16590 diag::err_operator_overload_post_incdec_must_be_int)
16591 << LastParam->getType() << (Op == OO_MinusMinus);
16592 }
16593
16594 return false;
16595}
16596
16597static bool
16599 FunctionTemplateDecl *TpDecl) {
16600 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16601
16602 // Must have one or two template parameters.
16603 if (TemplateParams->size() == 1) {
16604 NonTypeTemplateParmDecl *PmDecl =
16605 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16606
16607 // The template parameter must be a char parameter pack.
16608 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16609 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16610 return false;
16611
16612 // C++20 [over.literal]p5:
16613 // A string literal operator template is a literal operator template
16614 // whose template-parameter-list comprises a single non-type
16615 // template-parameter of class type.
16616 //
16617 // As a DR resolution, we also allow placeholders for deduced class
16618 // template specializations.
16619 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16620 !PmDecl->isTemplateParameterPack() &&
16621 (PmDecl->getType()->isRecordType() ||
16623 return false;
16624 } else if (TemplateParams->size() == 2) {
16625 TemplateTypeParmDecl *PmType =
16626 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16627 NonTypeTemplateParmDecl *PmArgs =
16628 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16629
16630 // The second template parameter must be a parameter pack with the
16631 // first template parameter as its type.
16632 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16633 PmArgs->isTemplateParameterPack()) {
16634 const TemplateTypeParmType *TArgs =
16635 PmArgs->getType()->getAs<TemplateTypeParmType>();
16636 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16637 TArgs->getIndex() == PmType->getIndex()) {
16638 if (!SemaRef.inTemplateInstantiation())
16639 SemaRef.Diag(TpDecl->getLocation(),
16640 diag::ext_string_literal_operator_template);
16641 return false;
16642 }
16643 }
16644 }
16645
16646 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16647 diag::err_literal_operator_template)
16648 << TpDecl->getTemplateParameters()->getSourceRange();
16649 return true;
16650}
16651
16652/// CheckLiteralOperatorDeclaration - Check whether the declaration
16653/// of this literal operator function is well-formed. If so, returns
16654/// false; otherwise, emits appropriate diagnostics and returns true.
16656 if (isa<CXXMethodDecl>(FnDecl)) {
16657 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16658 << FnDecl->getDeclName();
16659 return true;
16660 }
16661
16662 if (FnDecl->isExternC()) {
16663 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16664 if (const LinkageSpecDecl *LSD =
16665 FnDecl->getDeclContext()->getExternCContext())
16666 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16667 return true;
16668 }
16669
16670 // This might be the definition of a literal operator template.
16672
16673 // This might be a specialization of a literal operator template.
16674 if (!TpDecl)
16675 TpDecl = FnDecl->getPrimaryTemplate();
16676
16677 // template <char...> type operator "" name() and
16678 // template <class T, T...> type operator "" name() are the only valid
16679 // template signatures, and the only valid signatures with no parameters.
16680 //
16681 // C++20 also allows template <SomeClass T> type operator "" name().
16682 if (TpDecl) {
16683 if (FnDecl->param_size() != 0) {
16684 Diag(FnDecl->getLocation(),
16685 diag::err_literal_operator_template_with_params);
16686 return true;
16687 }
16688
16690 return true;
16691
16692 } else if (FnDecl->param_size() == 1) {
16693 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16694
16695 QualType ParamType = Param->getType().getUnqualifiedType();
16696
16697 // Only unsigned long long int, long double, any character type, and const
16698 // char * are allowed as the only parameters.
16699 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16700 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16701 Context.hasSameType(ParamType, Context.CharTy) ||
16702 Context.hasSameType(ParamType, Context.WideCharTy) ||
16703 Context.hasSameType(ParamType, Context.Char8Ty) ||
16704 Context.hasSameType(ParamType, Context.Char16Ty) ||
16705 Context.hasSameType(ParamType, Context.Char32Ty)) {
16706 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16707 QualType InnerType = Ptr->getPointeeType();
16708
16709 // Pointer parameter must be a const char *.
16710 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16711 Context.CharTy) &&
16712 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16713 Diag(Param->getSourceRange().getBegin(),
16714 diag::err_literal_operator_param)
16715 << ParamType << "'const char *'" << Param->getSourceRange();
16716 return true;
16717 }
16718
16719 } else if (ParamType->isRealFloatingType()) {
16720 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16721 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16722 return true;
16723
16724 } else if (ParamType->isIntegerType()) {
16725 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16726 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16727 return true;
16728
16729 } else {
16730 Diag(Param->getSourceRange().getBegin(),
16731 diag::err_literal_operator_invalid_param)
16732 << ParamType << Param->getSourceRange();
16733 return true;
16734 }
16735
16736 } else if (FnDecl->param_size() == 2) {
16737 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16738
16739 // First, verify that the first parameter is correct.
16740
16741 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16742
16743 // Two parameter function must have a pointer to const as a
16744 // first parameter; let's strip those qualifiers.
16745 const PointerType *PT = FirstParamType->getAs<PointerType>();
16746
16747 if (!PT) {
16748 Diag((*Param)->getSourceRange().getBegin(),
16749 diag::err_literal_operator_param)
16750 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16751 return true;
16752 }
16753
16754 QualType PointeeType = PT->getPointeeType();
16755 // First parameter must be const
16756 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16757 Diag((*Param)->getSourceRange().getBegin(),
16758 diag::err_literal_operator_param)
16759 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16760 return true;
16761 }
16762
16763 QualType InnerType = PointeeType.getUnqualifiedType();
16764 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16765 // const char32_t* are allowed as the first parameter to a two-parameter
16766 // function
16767 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16768 Context.hasSameType(InnerType, Context.WideCharTy) ||
16769 Context.hasSameType(InnerType, Context.Char8Ty) ||
16770 Context.hasSameType(InnerType, Context.Char16Ty) ||
16771 Context.hasSameType(InnerType, Context.Char32Ty))) {
16772 Diag((*Param)->getSourceRange().getBegin(),
16773 diag::err_literal_operator_param)
16774 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16775 return true;
16776 }
16777
16778 // Move on to the second and final parameter.
16779 ++Param;
16780
16781 // The second parameter must be a std::size_t.
16782 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16783 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16784 Diag((*Param)->getSourceRange().getBegin(),
16785 diag::err_literal_operator_param)
16786 << SecondParamType << Context.getSizeType()
16787 << (*Param)->getSourceRange();
16788 return true;
16789 }
16790 } else {
16791 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16792 return true;
16793 }
16794
16795 // Parameters are good.
16796
16797 // A parameter-declaration-clause containing a default argument is not
16798 // equivalent to any of the permitted forms.
16799 for (auto *Param : FnDecl->parameters()) {
16800 if (Param->hasDefaultArg()) {
16801 Diag(Param->getDefaultArgRange().getBegin(),
16802 diag::err_literal_operator_default_argument)
16803 << Param->getDefaultArgRange();
16804 break;
16805 }
16806 }
16807
16808 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16811 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16812 // C++23 [usrlit.suffix]p1:
16813 // Literal suffix identifiers that do not start with an underscore are
16814 // reserved for future standardization. Literal suffix identifiers that
16815 // contain a double underscore __ are reserved for use by C++
16816 // implementations.
16817 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16818 << static_cast<int>(Status)
16820 }
16821
16822 return false;
16823}
16824
16825/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16826/// linkage specification, including the language and (if present)
16827/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16828/// language string literal. LBraceLoc, if valid, provides the location of
16829/// the '{' brace. Otherwise, this linkage specification does not
16830/// have any braces.
16832 Expr *LangStr,
16833 SourceLocation LBraceLoc) {
16834 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16835 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16836
16837 StringRef Lang = Lit->getString();
16839 if (Lang == "C")
16841 else if (Lang == "C++")
16843 else {
16844 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16845 << LangStr->getSourceRange();
16846 return nullptr;
16847 }
16848
16849 // FIXME: Add all the various semantics of linkage specifications
16850
16852 LangStr->getExprLoc(), Language,
16853 LBraceLoc.isValid());
16854
16855 /// C++ [module.unit]p7.2.3
16856 /// - Otherwise, if the declaration
16857 /// - ...
16858 /// - ...
16859 /// - appears within a linkage-specification,
16860 /// it is attached to the global module.
16861 ///
16862 /// If the declaration is already in global module fragment, we don't
16863 /// need to attach it again.
16864 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16865 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16866 D->setLocalOwningModule(GlobalModule);
16867 }
16868
16869 CurContext->addDecl(D);
16870 PushDeclContext(S, D);
16871 return D;
16872}
16873
16874/// ActOnFinishLinkageSpecification - Complete the definition of
16875/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16876/// valid, it's the position of the closing '}' brace in a linkage
16877/// specification that uses braces.
16879 Decl *LinkageSpec,
16880 SourceLocation RBraceLoc) {
16881 if (RBraceLoc.isValid()) {
16882 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16883 LSDecl->setRBraceLoc(RBraceLoc);
16884 }
16885
16886 // If the current module doesn't has Parent, it implies that the
16887 // LinkageSpec isn't in the module created by itself. So we don't
16888 // need to pop it.
16889 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16890 getCurrentModule()->isImplicitGlobalModule() &&
16892 PopImplicitGlobalModuleFragment();
16893
16895 return LinkageSpec;
16896}
16897
16899 const ParsedAttributesView &AttrList,
16900 SourceLocation SemiLoc) {
16901 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16902 // Attribute declarations appertain to empty declaration so we handle
16903 // them here.
16904 ProcessDeclAttributeList(S, ED, AttrList);
16905
16906 CurContext->addDecl(ED);
16907 return ED;
16908}
16909
16910/// Perform semantic analysis for the variable declaration that
16911/// occurs within a C++ catch clause, returning the newly-created
16912/// variable.
16914 TypeSourceInfo *TInfo,
16915 SourceLocation StartLoc,
16916 SourceLocation Loc,
16917 IdentifierInfo *Name) {
16918 bool Invalid = false;
16919 QualType ExDeclType = TInfo->getType();
16920
16921 // Arrays and functions decay.
16922 if (ExDeclType->isArrayType())
16923 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16924 else if (ExDeclType->isFunctionType())
16925 ExDeclType = Context.getPointerType(ExDeclType);
16926
16927 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16928 // The exception-declaration shall not denote a pointer or reference to an
16929 // incomplete type, other than [cv] void*.
16930 // N2844 forbids rvalue references.
16931 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16932 Diag(Loc, diag::err_catch_rvalue_ref);
16933 Invalid = true;
16934 }
16935
16936 if (ExDeclType->isVariablyModifiedType()) {
16937 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16938 Invalid = true;
16939 }
16940
16941 QualType BaseType = ExDeclType;
16942 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16943 unsigned DK = diag::err_catch_incomplete;
16944 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16945 BaseType = Ptr->getPointeeType();
16946 Mode = 1;
16947 DK = diag::err_catch_incomplete_ptr;
16948 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16949 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16950 BaseType = Ref->getPointeeType();
16951 Mode = 2;
16952 DK = diag::err_catch_incomplete_ref;
16953 }
16954 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16955 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16956 Invalid = true;
16957
16958 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16959 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16960 Invalid = true;
16961 }
16962
16963 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16964 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16965 Invalid = true;
16966 }
16967
16968 if (!Invalid && !ExDeclType->isDependentType() &&
16969 RequireNonAbstractType(Loc, ExDeclType,
16970 diag::err_abstract_type_in_decl,
16972 Invalid = true;
16973
16974 // Only the non-fragile NeXT runtime currently supports C++ catches
16975 // of ObjC types, and no runtime supports catching ObjC types by value.
16976 if (!Invalid && getLangOpts().ObjC) {
16977 QualType T = ExDeclType;
16978 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16979 T = RT->getPointeeType();
16980
16981 if (T->isObjCObjectType()) {
16982 Diag(Loc, diag::err_objc_object_catch);
16983 Invalid = true;
16984 } else if (T->isObjCObjectPointerType()) {
16985 // FIXME: should this be a test for macosx-fragile specifically?
16987 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16988 }
16989 }
16990
16991 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16992 ExDeclType, TInfo, SC_None);
16993 ExDecl->setExceptionVariable(true);
16994
16995 // In ARC, infer 'retaining' for variables of retainable type.
16996 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16997 Invalid = true;
16998
16999 if (!Invalid && !ExDeclType->isDependentType()) {
17000 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17001 // Insulate this from anything else we might currently be parsing.
17004
17005 // C++ [except.handle]p16:
17006 // The object declared in an exception-declaration or, if the
17007 // exception-declaration does not specify a name, a temporary (12.2) is
17008 // copy-initialized (8.5) from the exception object. [...]
17009 // The object is destroyed when the handler exits, after the destruction
17010 // of any automatic objects initialized within the handler.
17011 //
17012 // We just pretend to initialize the object with itself, then make sure
17013 // it can be destroyed later.
17014 QualType initType = Context.getExceptionObjectType(ExDeclType);
17015
17016 InitializedEntity entity =
17018 InitializationKind initKind =
17020
17021 Expr *opaqueValue =
17022 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17023 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17024 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17025 if (result.isInvalid())
17026 Invalid = true;
17027 else {
17028 // If the constructor used was non-trivial, set this as the
17029 // "initializer".
17030 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17031 if (!construct->getConstructor()->isTrivial()) {
17032 Expr *init = MaybeCreateExprWithCleanups(construct);
17033 ExDecl->setInit(init);
17034 }
17035
17036 // And make sure it's destructable.
17038 }
17039 }
17040 }
17041
17042 if (Invalid)
17043 ExDecl->setInvalidDecl();
17044
17045 return ExDecl;
17046}
17047
17048/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17049/// handler.
17052 bool Invalid = D.isInvalidType();
17053
17054 // Check for unexpanded parameter packs.
17058 D.getIdentifierLoc());
17059 Invalid = true;
17060 }
17061
17062 IdentifierInfo *II = D.getIdentifier();
17063 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
17066 // The scope should be freshly made just for us. There is just no way
17067 // it contains any previous declaration, except for function parameters in
17068 // a function-try-block's catch statement.
17069 assert(!S->isDeclScope(PrevDecl));
17070 if (isDeclInScope(PrevDecl, CurContext, S)) {
17071 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17072 << D.getIdentifier();
17073 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17074 Invalid = true;
17075 } else if (PrevDecl->isTemplateParameter())
17076 // Maybe we will complain about the shadowed template parameter.
17078 }
17079
17080 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17081 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17082 << D.getCXXScopeSpec().getRange();
17083 Invalid = true;
17084 }
17085
17087 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17088 if (Invalid)
17089 ExDecl->setInvalidDecl();
17090
17091 // Add the exception declaration into this scope.
17092 if (II)
17093 PushOnScopeChains(ExDecl, S);
17094 else
17095 CurContext->addDecl(ExDecl);
17096
17097 ProcessDeclAttributes(S, ExDecl, D);
17098 return ExDecl;
17099}
17100
17102 Expr *AssertExpr,
17103 Expr *AssertMessageExpr,
17104 SourceLocation RParenLoc) {
17106 return nullptr;
17107
17108 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17109 AssertMessageExpr, RParenLoc, false);
17110}
17111
17112static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17113 switch (BTK) {
17114 case BuiltinType::Char_S:
17115 case BuiltinType::Char_U:
17116 break;
17117 case BuiltinType::Char8:
17118 OS << "u8";
17119 break;
17120 case BuiltinType::Char16:
17121 OS << 'u';
17122 break;
17123 case BuiltinType::Char32:
17124 OS << 'U';
17125 break;
17126 case BuiltinType::WChar_S:
17127 case BuiltinType::WChar_U:
17128 OS << 'L';
17129 break;
17130 default:
17131 llvm_unreachable("Non-character type");
17132 }
17133}
17134
17135/// Convert character's value, interpreted as a code unit, to a string.
17136/// The value needs to be zero-extended to 32-bits.
17137/// FIXME: This assumes Unicode literal encodings
17138static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17139 unsigned TyWidth,
17140 SmallVectorImpl<char> &Str) {
17141 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17142 char *Ptr = Arr;
17143 BuiltinType::Kind K = BTy->getKind();
17144 llvm::raw_svector_ostream OS(Str);
17145
17146 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17147 // other types.
17148 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17149 K == BuiltinType::Char8 || Value <= 0x7F) {
17150 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17151 if (!Escaped.empty())
17152 EscapeStringForDiagnostic(Escaped, Str);
17153 else
17154 OS << static_cast<char>(Value);
17155 return;
17156 }
17157
17158 switch (K) {
17159 case BuiltinType::Char16:
17160 case BuiltinType::Char32:
17161 case BuiltinType::WChar_S:
17162 case BuiltinType::WChar_U: {
17163 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17164 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17165 else
17166 OS << "\\x"
17167 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17168 break;
17169 }
17170 default:
17171 llvm_unreachable("Non-character type is passed");
17172 }
17173}
17174
17175/// Convert \V to a string we can present to the user in a diagnostic
17176/// \T is the type of the expression that has been evaluated into \V
17180 if (!V.hasValue())
17181 return false;
17182
17183 switch (V.getKind()) {
17185 if (T->isBooleanType()) {
17186 // Bools are reduced to ints during evaluation, but for
17187 // diagnostic purposes we want to print them as
17188 // true or false.
17189 int64_t BoolValue = V.getInt().getExtValue();
17190 assert((BoolValue == 0 || BoolValue == 1) &&
17191 "Bool type, but value is not 0 or 1");
17192 llvm::raw_svector_ostream OS(Str);
17193 OS << (BoolValue ? "true" : "false");
17194 } else {
17195 llvm::raw_svector_ostream OS(Str);
17196 // Same is true for chars.
17197 // We want to print the character representation for textual types
17198 const auto *BTy = T->getAs<BuiltinType>();
17199 if (BTy) {
17200 switch (BTy->getKind()) {
17201 case BuiltinType::Char_S:
17202 case BuiltinType::Char_U:
17203 case BuiltinType::Char8:
17204 case BuiltinType::Char16:
17205 case BuiltinType::Char32:
17206 case BuiltinType::WChar_S:
17207 case BuiltinType::WChar_U: {
17208 unsigned TyWidth = Context.getIntWidth(T);
17209 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17210 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17211 WriteCharTypePrefix(BTy->getKind(), OS);
17212 OS << '\'';
17213 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17214 OS << "' (0x"
17215 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17216 /*Upper=*/true)
17217 << ", " << V.getInt() << ')';
17218 return true;
17219 }
17220 default:
17221 break;
17222 }
17223 }
17224 V.getInt().toString(Str);
17225 }
17226
17227 break;
17228
17230 V.getFloat().toString(Str);
17231 break;
17232
17234 if (V.isNullPointer()) {
17235 llvm::raw_svector_ostream OS(Str);
17236 OS << "nullptr";
17237 } else
17238 return false;
17239 break;
17240
17242 llvm::raw_svector_ostream OS(Str);
17243 OS << '(';
17244 V.getComplexFloatReal().toString(Str);
17245 OS << " + ";
17246 V.getComplexFloatImag().toString(Str);
17247 OS << "i)";
17248 } break;
17249
17251 llvm::raw_svector_ostream OS(Str);
17252 OS << '(';
17253 V.getComplexIntReal().toString(Str);
17254 OS << " + ";
17255 V.getComplexIntImag().toString(Str);
17256 OS << "i)";
17257 } break;
17258
17259 default:
17260 return false;
17261 }
17262
17263 return true;
17264}
17265
17266/// Some Expression types are not useful to print notes about,
17267/// e.g. literals and values that have already been expanded
17268/// before such as int-valued template parameters.
17269static bool UsefulToPrintExpr(const Expr *E) {
17270 E = E->IgnoreParenImpCasts();
17271 // Literals are pretty easy for humans to understand.
17274 return false;
17275
17276 // These have been substituted from template parameters
17277 // and appear as literals in the static assert error.
17278 if (isa<SubstNonTypeTemplateParmExpr>(E))
17279 return false;
17280
17281 // -5 is also simple to understand.
17282 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17283 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17284
17285 // Only print nested arithmetic operators.
17286 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17287 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17288 BO->isBitwiseOp());
17289
17290 return true;
17291}
17292
17293/// Try to print more useful information about a failed static_assert
17294/// with expression \E
17296 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17297 Op && Op->getOpcode() != BO_LOr) {
17298 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17299 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17300
17301 // Ignore comparisons of boolean expressions with a boolean literal.
17302 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17303 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17304 return;
17305
17306 // Don't print obvious expressions.
17307 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17308 return;
17309
17310 struct {
17311 const clang::Expr *Cond;
17313 SmallString<12> ValueString;
17314 bool Print;
17315 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17316 {RHS, Expr::EvalResult(), {}, false}};
17317 for (unsigned I = 0; I < 2; I++) {
17318 const Expr *Side = DiagSide[I].Cond;
17319
17320 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17321
17322 DiagSide[I].Print =
17323 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17324 DiagSide[I].ValueString, Context);
17325 }
17326 if (DiagSide[0].Print && DiagSide[1].Print) {
17327 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17328 << DiagSide[0].ValueString << Op->getOpcodeStr()
17329 << DiagSide[1].ValueString << Op->getSourceRange();
17330 }
17331 }
17332}
17333
17335 std::string &Result,
17336 ASTContext &Ctx,
17337 bool ErrorOnInvalidMessage) {
17338 assert(Message);
17339 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17340 "can't evaluate a dependant static assert message");
17341
17342 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17343 assert(SL->isUnevaluated() && "expected an unevaluated string");
17344 Result.assign(SL->getString().begin(), SL->getString().end());
17345 return true;
17346 }
17347
17348 SourceLocation Loc = Message->getBeginLoc();
17349 QualType T = Message->getType().getNonReferenceType();
17350 auto *RD = T->getAsCXXRecordDecl();
17351 if (!RD) {
17352 Diag(Loc, diag::err_static_assert_invalid_message);
17353 return false;
17354 }
17355
17356 auto FindMember = [&](StringRef Member, bool &Empty,
17357 bool Diag = false) -> std::optional<LookupResult> {
17359 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17360 LookupQualifiedName(MemberLookup, RD);
17361 Empty = MemberLookup.empty();
17362 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17364 if (MemberLookup.empty())
17365 return std::nullopt;
17366 return std::move(MemberLookup);
17367 };
17368
17369 bool SizeNotFound, DataNotFound;
17370 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17371 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17372 if (SizeNotFound || DataNotFound) {
17373 Diag(Loc, diag::err_static_assert_missing_member_function)
17374 << ((SizeNotFound && DataNotFound) ? 2
17375 : SizeNotFound ? 0
17376 : 1);
17377 return false;
17378 }
17379
17380 if (!SizeMember || !DataMember) {
17381 if (!SizeMember)
17382 FindMember("size", SizeNotFound, /*Diag=*/true);
17383 if (!DataMember)
17384 FindMember("data", DataNotFound, /*Diag=*/true);
17385 return false;
17386 }
17387
17388 auto BuildExpr = [&](LookupResult &LR) {
17390 Message, Message->getType(), Message->getBeginLoc(), false,
17391 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17392 if (Res.isInvalid())
17393 return ExprError();
17394 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17395 false, true);
17396 if (Res.isInvalid())
17397 return ExprError();
17398 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17399 return ExprError();
17401 };
17402
17403 ExprResult SizeE = BuildExpr(*SizeMember);
17404 ExprResult DataE = BuildExpr(*DataMember);
17405
17406 QualType SizeT = Context.getSizeType();
17407 QualType ConstCharPtr =
17409
17410 ExprResult EvaluatedSize =
17411 SizeE.isInvalid() ? ExprError()
17413 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17414 if (EvaluatedSize.isInvalid()) {
17415 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17416 return false;
17417 }
17418
17419 ExprResult EvaluatedData =
17420 DataE.isInvalid()
17421 ? ExprError()
17422 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17424 if (EvaluatedData.isInvalid()) {
17425 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17426 return false;
17427 }
17428
17429 if (!ErrorOnInvalidMessage &&
17430 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17431 return true;
17432
17433 Expr::EvalResult Status;
17435 Status.Diag = &Notes;
17436 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17437 EvaluatedData.get(), Ctx, Status) ||
17438 !Notes.empty()) {
17439 Diag(Message->getBeginLoc(),
17440 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17441 : diag::warn_static_assert_message_constexpr);
17442 for (const auto &Note : Notes)
17443 Diag(Note.first, Note.second);
17444 return !ErrorOnInvalidMessage;
17445 }
17446 return true;
17447}
17448
17450 Expr *AssertExpr, Expr *AssertMessage,
17451 SourceLocation RParenLoc,
17452 bool Failed) {
17453 assert(AssertExpr != nullptr && "Expected non-null condition");
17454 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17455 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17456 !AssertMessage->isValueDependent())) &&
17457 !Failed) {
17458 // In a static_assert-declaration, the constant-expression shall be a
17459 // constant expression that can be contextually converted to bool.
17460 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17461 if (Converted.isInvalid())
17462 Failed = true;
17463
17464 ExprResult FullAssertExpr =
17465 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17466 /*DiscardedValue*/ false,
17467 /*IsConstexpr*/ true);
17468 if (FullAssertExpr.isInvalid())
17469 Failed = true;
17470 else
17471 AssertExpr = FullAssertExpr.get();
17472
17473 llvm::APSInt Cond;
17474 Expr *BaseExpr = AssertExpr;
17475 AllowFoldKind FoldKind = NoFold;
17476
17477 if (!getLangOpts().CPlusPlus) {
17478 // In C mode, allow folding as an extension for better compatibility with
17479 // C++ in terms of expressions like static_assert("test") or
17480 // static_assert(nullptr).
17481 FoldKind = AllowFold;
17482 }
17483
17484 if (!Failed && VerifyIntegerConstantExpression(
17485 BaseExpr, &Cond,
17486 diag::err_static_assert_expression_is_not_constant,
17487 FoldKind).isInvalid())
17488 Failed = true;
17489
17490 // If the static_assert passes, only verify that
17491 // the message is grammatically valid without evaluating it.
17492 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17493 std::string Str;
17494 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17495 /*ErrorOnInvalidMessage=*/false);
17496 }
17497
17498 // CWG2518
17499 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17500 // template definition, the declaration has no effect.
17501 bool InTemplateDefinition =
17502 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17503
17504 if (!Failed && !Cond && !InTemplateDefinition) {
17505 SmallString<256> MsgBuffer;
17506 llvm::raw_svector_ostream Msg(MsgBuffer);
17507 bool HasMessage = AssertMessage;
17508 if (AssertMessage) {
17509 std::string Str;
17510 HasMessage =
17512 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17513 !Str.empty();
17514 Msg << Str;
17515 }
17516 Expr *InnerCond = nullptr;
17517 std::string InnerCondDescription;
17518 std::tie(InnerCond, InnerCondDescription) =
17519 findFailedBooleanCondition(Converted.get());
17520 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17521 // Drill down into concept specialization expressions to see why they
17522 // weren't satisfied.
17523 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17524 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17525 ConstraintSatisfaction Satisfaction;
17526 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17527 DiagnoseUnsatisfiedConstraint(Satisfaction);
17528 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17529 && !isa<IntegerLiteral>(InnerCond)) {
17530 Diag(InnerCond->getBeginLoc(),
17531 diag::err_static_assert_requirement_failed)
17532 << InnerCondDescription << !HasMessage << Msg.str()
17533 << InnerCond->getSourceRange();
17534 DiagnoseStaticAssertDetails(InnerCond);
17535 } else {
17536 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17537 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17539 }
17540 Failed = true;
17541 }
17542 } else {
17543 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17544 /*DiscardedValue*/false,
17545 /*IsConstexpr*/true);
17546 if (FullAssertExpr.isInvalid())
17547 Failed = true;
17548 else
17549 AssertExpr = FullAssertExpr.get();
17550 }
17551
17553 AssertExpr, AssertMessage, RParenLoc,
17554 Failed);
17555
17557 return Decl;
17558}
17559
17560/// Handle a friend tag declaration where the scope specifier was
17561/// templated.
17563 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17564 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17565 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17567
17568 bool IsMemberSpecialization = false;
17569 bool Invalid = false;
17570
17571 if (TemplateParameterList *TemplateParams =
17573 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17574 IsMemberSpecialization, Invalid)) {
17575 if (TemplateParams->size() > 0) {
17576 // This is a declaration of a class template.
17577 if (Invalid)
17578 return true;
17579
17580 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17581 NameLoc, Attr, TemplateParams, AS_public,
17582 /*ModulePrivateLoc=*/SourceLocation(),
17583 FriendLoc, TempParamLists.size() - 1,
17584 TempParamLists.data()).get();
17585 } else {
17586 // The "template<>" header is extraneous.
17587 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17588 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17589 IsMemberSpecialization = true;
17590 }
17591 }
17592
17593 if (Invalid) return true;
17594
17595 bool isAllExplicitSpecializations = true;
17596 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17597 if (TempParamLists[I]->size()) {
17598 isAllExplicitSpecializations = false;
17599 break;
17600 }
17601 }
17602
17603 // FIXME: don't ignore attributes.
17604
17605 // If it's explicit specializations all the way down, just forget
17606 // about the template header and build an appropriate non-templated
17607 // friend. TODO: for source fidelity, remember the headers.
17608 if (isAllExplicitSpecializations) {
17609 if (SS.isEmpty()) {
17610 bool Owned = false;
17611 bool IsDependent = false;
17612 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17613 AS_public,
17614 /*ModulePrivateLoc=*/SourceLocation(),
17615 MultiTemplateParamsArg(), Owned, IsDependent,
17616 /*ScopedEnumKWLoc=*/SourceLocation(),
17617 /*ScopedEnumUsesClassTag=*/false,
17618 /*UnderlyingType=*/TypeResult(),
17619 /*IsTypeSpecifier=*/false,
17620 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17621 }
17622
17624 ElaboratedTypeKeyword Keyword
17626 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17627 *Name, NameLoc);
17628 if (T.isNull())
17629 return true;
17630
17632 if (isa<DependentNameType>(T)) {
17635 TL.setElaboratedKeywordLoc(TagLoc);
17636 TL.setQualifierLoc(QualifierLoc);
17637 TL.setNameLoc(NameLoc);
17638 } else {
17640 TL.setElaboratedKeywordLoc(TagLoc);
17641 TL.setQualifierLoc(QualifierLoc);
17642 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17643 }
17644
17645 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17646 TSI, FriendLoc, TempParamLists);
17647 Friend->setAccess(AS_public);
17648 CurContext->addDecl(Friend);
17649 return Friend;
17650 }
17651
17652 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17653
17654
17655
17656 // Handle the case of a templated-scope friend class. e.g.
17657 // template <class T> class A<T>::B;
17658 // FIXME: we don't support these right now.
17659 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17660 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17662 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17665 TL.setElaboratedKeywordLoc(TagLoc);
17667 TL.setNameLoc(NameLoc);
17668
17669 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17670 TSI, FriendLoc, TempParamLists);
17671 Friend->setAccess(AS_public);
17672 Friend->setUnsupportedFriend(true);
17673 CurContext->addDecl(Friend);
17674 return Friend;
17675}
17676
17677/// Handle a friend type declaration. This works in tandem with
17678/// ActOnTag.
17679///
17680/// Notes on friend class templates:
17681///
17682/// We generally treat friend class declarations as if they were
17683/// declaring a class. So, for example, the elaborated type specifier
17684/// in a friend declaration is required to obey the restrictions of a
17685/// class-head (i.e. no typedefs in the scope chain), template
17686/// parameters are required to match up with simple template-ids, &c.
17687/// However, unlike when declaring a template specialization, it's
17688/// okay to refer to a template specialization without an empty
17689/// template parameter declaration, e.g.
17690/// friend class A<T>::B<unsigned>;
17691/// We permit this as a special case; if there are any template
17692/// parameters present at all, require proper matching, i.e.
17693/// template <> template <class T> friend class A<int>::B;
17695 MultiTemplateParamsArg TempParams) {
17696 SourceLocation Loc = DS.getBeginLoc();
17697 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17698
17699 assert(DS.isFriendSpecified());
17701
17702 // C++ [class.friend]p3:
17703 // A friend declaration that does not declare a function shall have one of
17704 // the following forms:
17705 // friend elaborated-type-specifier ;
17706 // friend simple-type-specifier ;
17707 // friend typename-specifier ;
17708 //
17709 // If the friend keyword isn't first, or if the declarations has any type
17710 // qualifiers, then the declaration doesn't have that form.
17712 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17713 if (DS.getTypeQualifiers()) {
17715 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17717 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17719 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17721 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17723 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17724 }
17725
17726 // Try to convert the decl specifier to a type. This works for
17727 // friend templates because ActOnTag never produces a ClassTemplateDecl
17728 // for a TUK_Friend.
17729 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17731 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17732 QualType T = TSI->getType();
17733 if (TheDeclarator.isInvalidType())
17734 return nullptr;
17735
17737 return nullptr;
17738
17739 if (!T->isElaboratedTypeSpecifier()) {
17740 if (TempParams.size()) {
17741 // C++23 [dcl.pre]p5:
17742 // In a simple-declaration, the optional init-declarator-list can be
17743 // omitted only when declaring a class or enumeration, that is, when
17744 // the decl-specifier-seq contains either a class-specifier, an
17745 // elaborated-type-specifier with a class-key, or an enum-specifier.
17746 //
17747 // The declaration of a template-declaration or explicit-specialization
17748 // is never a member-declaration, so this must be a simple-declaration
17749 // with no init-declarator-list. Therefore, this is ill-formed.
17750 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17751 return nullptr;
17752 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17753 SmallString<16> InsertionText(" ");
17754 InsertionText += RD->getKindName();
17755
17757 ? diag::warn_cxx98_compat_unelaborated_friend_type
17758 : diag::ext_unelaborated_friend_type)
17759 << (unsigned)RD->getTagKind() << T
17761 InsertionText);
17762 } else {
17763 Diag(FriendLoc, getLangOpts().CPlusPlus11
17764 ? diag::warn_cxx98_compat_nonclass_type_friend
17765 : diag::ext_nonclass_type_friend)
17766 << T << DS.getSourceRange();
17767 }
17768 }
17769
17770 // C++98 [class.friend]p1: A friend of a class is a function
17771 // or class that is not a member of the class . . .
17772 // This is fixed in DR77, which just barely didn't make the C++03
17773 // deadline. It's also a very silly restriction that seriously
17774 // affects inner classes and which nobody else seems to implement;
17775 // thus we never diagnose it, not even in -pedantic.
17776 //
17777 // But note that we could warn about it: it's always useless to
17778 // friend one of your own members (it's not, however, worthless to
17779 // friend a member of an arbitrary specialization of your template).
17780
17781 Decl *D;
17782 if (!TempParams.empty())
17783 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17784 FriendLoc);
17785 else
17787 TSI, FriendLoc);
17788
17789 if (!D)
17790 return nullptr;
17791
17792 D->setAccess(AS_public);
17793 CurContext->addDecl(D);
17794
17795 return D;
17796}
17797
17799 MultiTemplateParamsArg TemplateParams) {
17800 const DeclSpec &DS = D.getDeclSpec();
17801
17802 assert(DS.isFriendSpecified());
17804
17807
17808 // C++ [class.friend]p1
17809 // A friend of a class is a function or class....
17810 // Note that this sees through typedefs, which is intended.
17811 // It *doesn't* see through dependent types, which is correct
17812 // according to [temp.arg.type]p3:
17813 // If a declaration acquires a function type through a
17814 // type dependent on a template-parameter and this causes
17815 // a declaration that does not use the syntactic form of a
17816 // function declarator to have a function type, the program
17817 // is ill-formed.
17818 if (!TInfo->getType()->isFunctionType()) {
17819 Diag(Loc, diag::err_unexpected_friend);
17820
17821 // It might be worthwhile to try to recover by creating an
17822 // appropriate declaration.
17823 return nullptr;
17824 }
17825
17826 // C++ [namespace.memdef]p3
17827 // - If a friend declaration in a non-local class first declares a
17828 // class or function, the friend class or function is a member
17829 // of the innermost enclosing namespace.
17830 // - The name of the friend is not found by simple name lookup
17831 // until a matching declaration is provided in that namespace
17832 // scope (either before or after the class declaration granting
17833 // friendship).
17834 // - If a friend function is called, its name may be found by the
17835 // name lookup that considers functions from namespaces and
17836 // classes associated with the types of the function arguments.
17837 // - When looking for a prior declaration of a class or a function
17838 // declared as a friend, scopes outside the innermost enclosing
17839 // namespace scope are not considered.
17840
17841 CXXScopeSpec &SS = D.getCXXScopeSpec();
17843 assert(NameInfo.getName());
17844
17845 // Check for unexpanded parameter packs.
17849 return nullptr;
17850
17851 // The context we found the declaration in, or in which we should
17852 // create the declaration.
17853 DeclContext *DC;
17854 Scope *DCScope = S;
17855 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17857
17858 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17859
17860 // There are five cases here.
17861 // - There's no scope specifier and we're in a local class. Only look
17862 // for functions declared in the immediately-enclosing block scope.
17863 // We recover from invalid scope qualifiers as if they just weren't there.
17864 FunctionDecl *FunctionContainingLocalClass = nullptr;
17865 if ((SS.isInvalid() || !SS.isSet()) &&
17866 (FunctionContainingLocalClass =
17867 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17868 // C++11 [class.friend]p11:
17869 // If a friend declaration appears in a local class and the name
17870 // specified is an unqualified name, a prior declaration is
17871 // looked up without considering scopes that are outside the
17872 // innermost enclosing non-class scope. For a friend function
17873 // declaration, if there is no prior declaration, the program is
17874 // ill-formed.
17875
17876 // Find the innermost enclosing non-class scope. This is the block
17877 // scope containing the local class definition (or for a nested class,
17878 // the outer local class).
17879 DCScope = S->getFnParent();
17880
17881 // Look up the function name in the scope.
17883 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17884
17885 if (!Previous.empty()) {
17886 // All possible previous declarations must have the same context:
17887 // either they were declared at block scope or they are members of
17888 // one of the enclosing local classes.
17889 DC = Previous.getRepresentativeDecl()->getDeclContext();
17890 } else {
17891 // This is ill-formed, but provide the context that we would have
17892 // declared the function in, if we were permitted to, for error recovery.
17893 DC = FunctionContainingLocalClass;
17894 }
17896
17897 // - There's no scope specifier, in which case we just go to the
17898 // appropriate scope and look for a function or function template
17899 // there as appropriate.
17900 } else if (SS.isInvalid() || !SS.isSet()) {
17901 // C++11 [namespace.memdef]p3:
17902 // If the name in a friend declaration is neither qualified nor
17903 // a template-id and the declaration is a function or an
17904 // elaborated-type-specifier, the lookup to determine whether
17905 // the entity has been previously declared shall not consider
17906 // any scopes outside the innermost enclosing namespace.
17907
17908 // Find the appropriate context according to the above.
17909 DC = CurContext;
17910
17911 // Skip class contexts. If someone can cite chapter and verse
17912 // for this behavior, that would be nice --- it's what GCC and
17913 // EDG do, and it seems like a reasonable intent, but the spec
17914 // really only says that checks for unqualified existing
17915 // declarations should stop at the nearest enclosing namespace,
17916 // not that they should only consider the nearest enclosing
17917 // namespace.
17918 while (DC->isRecord())
17919 DC = DC->getParent();
17920
17921 DeclContext *LookupDC = DC->getNonTransparentContext();
17922 while (true) {
17923 LookupQualifiedName(Previous, LookupDC);
17924
17925 if (!Previous.empty()) {
17926 DC = LookupDC;
17927 break;
17928 }
17929
17930 if (isTemplateId) {
17931 if (isa<TranslationUnitDecl>(LookupDC)) break;
17932 } else {
17933 if (LookupDC->isFileContext()) break;
17934 }
17935 LookupDC = LookupDC->getParent();
17936 }
17937
17938 DCScope = getScopeForDeclContext(S, DC);
17939
17940 // - There's a non-dependent scope specifier, in which case we
17941 // compute it and do a previous lookup there for a function
17942 // or function template.
17943 } else if (!SS.getScopeRep()->isDependent()) {
17944 DC = computeDeclContext(SS);
17945 if (!DC) return nullptr;
17946
17947 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17948
17950
17951 // C++ [class.friend]p1: A friend of a class is a function or
17952 // class that is not a member of the class . . .
17953 if (DC->Equals(CurContext))
17956 diag::warn_cxx98_compat_friend_is_member :
17957 diag::err_friend_is_member);
17958
17959 // - There's a scope specifier that does not match any template
17960 // parameter lists, in which case we use some arbitrary context,
17961 // create a method or method template, and wait for instantiation.
17962 // - There's a scope specifier that does match some template
17963 // parameter lists, which we don't handle right now.
17964 } else {
17965 DC = CurContext;
17966 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17967 }
17968
17969 if (!DC->isRecord()) {
17970 int DiagArg = -1;
17971 switch (D.getName().getKind()) {
17974 DiagArg = 0;
17975 break;
17977 DiagArg = 1;
17978 break;
17980 DiagArg = 2;
17981 break;
17983 DiagArg = 3;
17984 break;
17990 break;
17991 }
17992 // This implies that it has to be an operator or function.
17993 if (DiagArg >= 0) {
17994 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17995 return nullptr;
17996 }
17997 }
17998
17999 // FIXME: This is an egregious hack to cope with cases where the scope stack
18000 // does not contain the declaration context, i.e., in an out-of-line
18001 // definition of a class.
18002 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18003 if (!DCScope) {
18004 FakeDCScope.setEntity(DC);
18005 DCScope = &FakeDCScope;
18006 }
18007
18008 bool AddToScope = true;
18009 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18010 TemplateParams, AddToScope);
18011 if (!ND) return nullptr;
18012
18013 assert(ND->getLexicalDeclContext() == CurContext);
18014
18015 // If we performed typo correction, we might have added a scope specifier
18016 // and changed the decl context.
18017 DC = ND->getDeclContext();
18018
18019 // Add the function declaration to the appropriate lookup tables,
18020 // adjusting the redeclarations list as necessary. We don't
18021 // want to do this yet if the friending class is dependent.
18022 //
18023 // Also update the scope-based lookup if the target context's
18024 // lookup context is in lexical scope.
18026 DC = DC->getRedeclContext();
18028 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18029 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18030 }
18031
18033 D.getIdentifierLoc(), ND,
18034 DS.getFriendSpecLoc());
18035 FrD->setAccess(AS_public);
18036 CurContext->addDecl(FrD);
18037
18038 if (ND->isInvalidDecl()) {
18039 FrD->setInvalidDecl();
18040 } else {
18041 if (DC->isRecord()) CheckFriendAccess(ND);
18042
18043 FunctionDecl *FD;
18044 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18045 FD = FTD->getTemplatedDecl();
18046 else
18047 FD = cast<FunctionDecl>(ND);
18048
18049 // C++ [class.friend]p6:
18050 // A function may be defined in a friend declaration of a class if and
18051 // only if the class is a non-local class, and the function name is
18052 // unqualified.
18053 if (D.isFunctionDefinition()) {
18054 // Qualified friend function definition.
18055 if (SS.isNotEmpty()) {
18056 // FIXME: We should only do this if the scope specifier names the
18057 // innermost enclosing namespace; otherwise the fixit changes the
18058 // meaning of the code.
18060 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18061
18062 DB << SS.getScopeRep();
18063 if (DC->isFileContext())
18065
18066 // Friend function defined in a local class.
18067 } else if (FunctionContainingLocalClass) {
18068 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18069
18070 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18071 // a template-id, the function name is not unqualified because these is
18072 // no name. While the wording requires some reading in-between the
18073 // lines, GCC, MSVC, and EDG all consider a friend function
18074 // specialization definitions // to be de facto explicit specialization
18075 // and diagnose them as such.
18076 } else if (isTemplateId) {
18077 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18078 }
18079 }
18080
18081 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18082 // default argument expression, that declaration shall be a definition
18083 // and shall be the only declaration of the function or function
18084 // template in the translation unit.
18086 // We can't look at FD->getPreviousDecl() because it may not have been set
18087 // if we're in a dependent context. If the function is known to be a
18088 // redeclaration, we will have narrowed Previous down to the right decl.
18089 if (D.isRedeclaration()) {
18090 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18091 Diag(Previous.getRepresentativeDecl()->getLocation(),
18092 diag::note_previous_declaration);
18093 } else if (!D.isFunctionDefinition())
18094 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18095 }
18096
18097 // Mark templated-scope function declarations as unsupported.
18098 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18099 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18100 << SS.getScopeRep() << SS.getRange()
18101 << cast<CXXRecordDecl>(CurContext);
18102 FrD->setUnsupportedFriend(true);
18103 }
18104 }
18105
18107
18108 return ND;
18109}
18110
18113
18114 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18115 if (!Fn) {
18116 Diag(DelLoc, diag::err_deleted_non_function);
18117 return;
18118 }
18119
18120 // Deleted function does not have a body.
18121 Fn->setWillHaveBody(false);
18122
18123 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18124 // Don't consider the implicit declaration we generate for explicit
18125 // specializations. FIXME: Do not generate these implicit declarations.
18126 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18127 Prev->getPreviousDecl()) &&
18128 !Prev->isDefined()) {
18129 Diag(DelLoc, diag::err_deleted_decl_not_first);
18130 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18131 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18132 : diag::note_previous_declaration);
18133 // We can't recover from this; the declaration might have already
18134 // been used.
18135 Fn->setInvalidDecl();
18136 return;
18137 }
18138
18139 // To maintain the invariant that functions are only deleted on their first
18140 // declaration, mark the implicitly-instantiated declaration of the
18141 // explicitly-specialized function as deleted instead of marking the
18142 // instantiated redeclaration.
18143 Fn = Fn->getCanonicalDecl();
18144 }
18145
18146 // dllimport/dllexport cannot be deleted.
18147 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18148 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18149 Fn->setInvalidDecl();
18150 }
18151
18152 // C++11 [basic.start.main]p3:
18153 // A program that defines main as deleted [...] is ill-formed.
18154 if (Fn->isMain())
18155 Diag(DelLoc, diag::err_deleted_main);
18156
18157 // C++11 [dcl.fct.def.delete]p4:
18158 // A deleted function is implicitly inline.
18159 Fn->setImplicitlyInline();
18160 Fn->setDeletedAsWritten();
18161}
18162
18164 if (!Dcl || Dcl->isInvalidDecl())
18165 return;
18166
18167 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18168 if (!FD) {
18169 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18170 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18171 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18172 return;
18173 }
18174 }
18175
18176 Diag(DefaultLoc, diag::err_default_special_members)
18177 << getLangOpts().CPlusPlus20;
18178 return;
18179 }
18180
18181 // Reject if this can't possibly be a defaultable function.
18183 if (!DefKind &&
18184 // A dependent function that doesn't locally look defaultable can
18185 // still instantiate to a defaultable function if it's a constructor
18186 // or assignment operator.
18187 (!FD->isDependentContext() ||
18188 (!isa<CXXConstructorDecl>(FD) &&
18189 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18190 Diag(DefaultLoc, diag::err_default_special_members)
18191 << getLangOpts().CPlusPlus20;
18192 return;
18193 }
18194
18195 // Issue compatibility warning. We already warned if the operator is
18196 // 'operator<=>' when parsing the '<=>' token.
18197 if (DefKind.isComparison() &&
18199 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18200 ? diag::warn_cxx17_compat_defaulted_comparison
18201 : diag::ext_defaulted_comparison);
18202 }
18203
18204 FD->setDefaulted();
18205 FD->setExplicitlyDefaulted();
18206 FD->setDefaultLoc(DefaultLoc);
18207
18208 // Defer checking functions that are defaulted in a dependent context.
18209 if (FD->isDependentContext())
18210 return;
18211
18212 // Unset that we will have a body for this function. We might not,
18213 // if it turns out to be trivial, and we don't need this marking now
18214 // that we've marked it as defaulted.
18215 FD->setWillHaveBody(false);
18216
18217 if (DefKind.isComparison()) {
18218 // If this comparison's defaulting occurs within the definition of its
18219 // lexical class context, we have to do the checking when complete.
18220 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18221 if (!RD->isCompleteDefinition())
18222 return;
18223 }
18224
18225 // If this member fn was defaulted on its first declaration, we will have
18226 // already performed the checking in CheckCompletedCXXClass. Such a
18227 // declaration doesn't trigger an implicit definition.
18228 if (isa<CXXMethodDecl>(FD)) {
18229 const FunctionDecl *Primary = FD;
18230 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18231 // Ask the template instantiation pattern that actually had the
18232 // '= default' on it.
18233 Primary = Pattern;
18234 if (Primary->getCanonicalDecl()->isDefaulted())
18235 return;
18236 }
18237
18238 if (DefKind.isComparison()) {
18239 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18240 FD->setInvalidDecl();
18241 else
18242 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18243 } else {
18244 auto *MD = cast<CXXMethodDecl>(FD);
18245
18247 DefaultLoc))
18248 MD->setInvalidDecl();
18249 else
18250 DefineDefaultedFunction(*this, MD, DefaultLoc);
18251 }
18252}
18253
18255 for (Stmt *SubStmt : S->children()) {
18256 if (!SubStmt)
18257 continue;
18258 if (isa<ReturnStmt>(SubStmt))
18259 Self.Diag(SubStmt->getBeginLoc(),
18260 diag::err_return_in_constructor_handler);
18261 if (!isa<Expr>(SubStmt))
18262 SearchForReturnInStmt(Self, SubStmt);
18263 }
18264}
18265
18267 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18268 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18269 SearchForReturnInStmt(*this, Handler);
18270 }
18271}
18272
18274 FnBodyKind BodyKind) {
18275 switch (BodyKind) {
18276 case FnBodyKind::Delete:
18277 SetDeclDeleted(D, Loc);
18278 break;
18280 SetDeclDefaulted(D, Loc);
18281 break;
18282 case FnBodyKind::Other:
18283 llvm_unreachable(
18284 "Parsed function body should be '= delete;' or '= default;'");
18285 }
18286}
18287
18289 const CXXMethodDecl *Old) {
18290 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18291 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18292
18293 if (OldFT->hasExtParameterInfos()) {
18294 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18295 // A parameter of the overriding method should be annotated with noescape
18296 // if the corresponding parameter of the overridden method is annotated.
18297 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18298 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18299 Diag(New->getParamDecl(I)->getLocation(),
18300 diag::warn_overriding_method_missing_noescape);
18301 Diag(Old->getParamDecl(I)->getLocation(),
18302 diag::note_overridden_marked_noescape);
18303 }
18304 }
18305
18306 // SME attributes must match when overriding a function declaration.
18307 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18308 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18309 << New << New->getType() << Old->getType();
18310 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18311 return true;
18312 }
18313
18314 // Virtual overrides must have the same code_seg.
18315 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18316 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18317 if ((NewCSA || OldCSA) &&
18318 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18319 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18320 Diag(Old->getLocation(), diag::note_previous_declaration);
18321 return true;
18322 }
18323
18324 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18325
18326 // If the calling conventions match, everything is fine
18327 if (NewCC == OldCC)
18328 return false;
18329
18330 // If the calling conventions mismatch because the new function is static,
18331 // suppress the calling convention mismatch error; the error about static
18332 // function override (err_static_overrides_virtual from
18333 // Sema::CheckFunctionDeclaration) is more clear.
18334 if (New->getStorageClass() == SC_Static)
18335 return false;
18336
18337 Diag(New->getLocation(),
18338 diag::err_conflicting_overriding_cc_attributes)
18339 << New->getDeclName() << New->getType() << Old->getType();
18340 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18341 return true;
18342}
18343
18345 const CXXMethodDecl *Old) {
18346 // CWG2553
18347 // A virtual function shall not be an explicit object member function.
18349 return true;
18350 Diag(New->getParamDecl(0)->getBeginLoc(),
18351 diag::err_explicit_object_parameter_nonmember)
18352 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18353 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18354 New->setInvalidDecl();
18355 return false;
18356}
18357
18359 const CXXMethodDecl *Old) {
18360 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18361 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18362
18363 if (Context.hasSameType(NewTy, OldTy) ||
18364 NewTy->isDependentType() || OldTy->isDependentType())
18365 return false;
18366
18367 // Check if the return types are covariant
18368 QualType NewClassTy, OldClassTy;
18369
18370 /// Both types must be pointers or references to classes.
18371 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18372 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18373 NewClassTy = NewPT->getPointeeType();
18374 OldClassTy = OldPT->getPointeeType();
18375 }
18376 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18377 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18378 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18379 NewClassTy = NewRT->getPointeeType();
18380 OldClassTy = OldRT->getPointeeType();
18381 }
18382 }
18383 }
18384
18385 // The return types aren't either both pointers or references to a class type.
18386 if (NewClassTy.isNull()) {
18387 Diag(New->getLocation(),
18388 diag::err_different_return_type_for_overriding_virtual_function)
18389 << New->getDeclName() << NewTy << OldTy
18390 << New->getReturnTypeSourceRange();
18391 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18392 << Old->getReturnTypeSourceRange();
18393
18394 return true;
18395 }
18396
18397 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18398 // C++14 [class.virtual]p8:
18399 // If the class type in the covariant return type of D::f differs from
18400 // that of B::f, the class type in the return type of D::f shall be
18401 // complete at the point of declaration of D::f or shall be the class
18402 // type D.
18403 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18404 if (!RT->isBeingDefined() &&
18405 RequireCompleteType(New->getLocation(), NewClassTy,
18406 diag::err_covariant_return_incomplete,
18407 New->getDeclName()))
18408 return true;
18409 }
18410
18411 // Check if the new class derives from the old class.
18412 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18413 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18414 << New->getDeclName() << NewTy << OldTy
18415 << New->getReturnTypeSourceRange();
18416 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18417 << Old->getReturnTypeSourceRange();
18418 return true;
18419 }
18420
18421 // Check if we the conversion from derived to base is valid.
18423 NewClassTy, OldClassTy,
18424 diag::err_covariant_return_inaccessible_base,
18425 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18427 New->getDeclName(), nullptr)) {
18428 // FIXME: this note won't trigger for delayed access control
18429 // diagnostics, and it's impossible to get an undelayed error
18430 // here from access control during the original parse because
18431 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18432 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18433 << Old->getReturnTypeSourceRange();
18434 return true;
18435 }
18436 }
18437
18438 // The qualifiers of the return types must be the same.
18439 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18440 Diag(New->getLocation(),
18441 diag::err_covariant_return_type_different_qualifications)
18442 << New->getDeclName() << NewTy << OldTy
18443 << New->getReturnTypeSourceRange();
18444 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18445 << Old->getReturnTypeSourceRange();
18446 return true;
18447 }
18448
18449
18450 // The new class type must have the same or less qualifiers as the old type.
18451 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18452 Diag(New->getLocation(),
18453 diag::err_covariant_return_type_class_type_more_qualified)
18454 << New->getDeclName() << NewTy << OldTy
18455 << New->getReturnTypeSourceRange();
18456 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18457 << Old->getReturnTypeSourceRange();
18458 return true;
18459 }
18460
18461 return false;
18462}
18463
18464/// Mark the given method pure.
18465///
18466/// \param Method the method to be marked pure.
18467///
18468/// \param InitRange the source range that covers the "0" initializer.
18470 SourceLocation EndLoc = InitRange.getEnd();
18471 if (EndLoc.isValid())
18472 Method->setRangeEnd(EndLoc);
18473
18474 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18475 Method->setIsPureVirtual();
18476 return false;
18477 }
18478
18479 if (!Method->isInvalidDecl())
18480 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18481 << Method->getDeclName() << InitRange;
18482 return true;
18483}
18484
18486 if (D->getFriendObjectKind())
18487 Diag(D->getLocation(), diag::err_pure_friend);
18488 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18489 CheckPureMethod(M, ZeroLoc);
18490 else
18491 Diag(D->getLocation(), diag::err_illegal_initializer);
18492}
18493
18494/// Determine whether the given declaration is a global variable or
18495/// static data member.
18496static bool isNonlocalVariable(const Decl *D) {
18497 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18498 return Var->hasGlobalStorage();
18499
18500 return false;
18501}
18502
18503/// Invoked when we are about to parse an initializer for the declaration
18504/// 'Dcl'.
18505///
18506/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18507/// static data member of class X, names should be looked up in the scope of
18508/// class X. If the declaration had a scope specifier, a scope will have
18509/// been created and passed in for this purpose. Otherwise, S will be null.
18511 // If there is no declaration, there was an error parsing it.
18512 if (!D || D->isInvalidDecl())
18513 return;
18514
18515 // We will always have a nested name specifier here, but this declaration
18516 // might not be out of line if the specifier names the current namespace:
18517 // extern int n;
18518 // int ::n = 0;
18519 if (S && D->isOutOfLine())
18521
18522 // If we are parsing the initializer for a static data member, push a
18523 // new expression evaluation context that is associated with this static
18524 // data member.
18525 if (isNonlocalVariable(D))
18528}
18529
18530/// Invoked after we are finished parsing an initializer for the declaration D.
18532 // If there is no declaration, there was an error parsing it.
18533 if (!D || D->isInvalidDecl())
18534 return;
18535
18536 if (isNonlocalVariable(D))
18538
18539 if (S && D->isOutOfLine())
18541}
18542
18543/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18544/// C++ if/switch/while/for statement.
18545/// e.g: "if (int x = f()) {...}"
18547 // C++ 6.4p2:
18548 // The declarator shall not specify a function or an array.
18549 // The type-specifier-seq shall not contain typedef and shall not declare a
18550 // new class or enumeration.
18552 "Parser allowed 'typedef' as storage class of condition decl.");
18553
18554 Decl *Dcl = ActOnDeclarator(S, D);
18555 if (!Dcl)
18556 return true;
18557
18558 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18559 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18560 << D.getSourceRange();
18561 return true;
18562 }
18563
18564 return Dcl;
18565}
18566
18568 if (!ExternalSource)
18569 return;
18570
18572 ExternalSource->ReadUsedVTables(VTables);
18574 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18575 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18576 = VTablesUsed.find(VTables[I].Record);
18577 // Even if a definition wasn't required before, it may be required now.
18578 if (Pos != VTablesUsed.end()) {
18579 if (!Pos->second && VTables[I].DefinitionRequired)
18580 Pos->second = true;
18581 continue;
18582 }
18583
18584 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18585 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18586 }
18587
18588 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18589}
18590
18592 bool DefinitionRequired) {
18593 // Ignore any vtable uses in unevaluated operands or for classes that do
18594 // not have a vtable.
18595 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18597 return;
18598 // Do not mark as used if compiling for the device outside of the target
18599 // region.
18600 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18603 if (!DefinitionRequired)
18605 return;
18606 }
18607
18608 // Try to insert this class into the map.
18610 Class = Class->getCanonicalDecl();
18611 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18612 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18613 if (!Pos.second) {
18614 // If we already had an entry, check to see if we are promoting this vtable
18615 // to require a definition. If so, we need to reappend to the VTableUses
18616 // list, since we may have already processed the first entry.
18617 if (DefinitionRequired && !Pos.first->second) {
18618 Pos.first->second = true;
18619 } else {
18620 // Otherwise, we can early exit.
18621 return;
18622 }
18623 } else {
18624 // The Microsoft ABI requires that we perform the destructor body
18625 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18626 // the deleting destructor is emitted with the vtable, not with the
18627 // destructor definition as in the Itanium ABI.
18629 CXXDestructorDecl *DD = Class->getDestructor();
18630 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18631 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18632 // If this is an out-of-line declaration, marking it referenced will
18633 // not do anything. Manually call CheckDestructor to look up operator
18634 // delete().
18635 ContextRAII SavedContext(*this, DD);
18636 CheckDestructor(DD);
18637 } else {
18638 MarkFunctionReferenced(Loc, Class->getDestructor());
18639 }
18640 }
18641 }
18642 }
18643
18644 // Local classes need to have their virtual members marked
18645 // immediately. For all other classes, we mark their virtual members
18646 // at the end of the translation unit.
18647 if (Class->isLocalClass())
18648 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18649 else
18650 VTableUses.push_back(std::make_pair(Class, Loc));
18651}
18652
18655 if (VTableUses.empty())
18656 return false;
18657
18658 // Note: The VTableUses vector could grow as a result of marking
18659 // the members of a class as "used", so we check the size each
18660 // time through the loop and prefer indices (which are stable) to
18661 // iterators (which are not).
18662 bool DefinedAnything = false;
18663 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18664 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18665 if (!Class)
18666 continue;
18668 Class->getTemplateSpecializationKind();
18669
18670 SourceLocation Loc = VTableUses[I].second;
18671
18672 bool DefineVTable = true;
18673
18674 // If this class has a key function, but that key function is
18675 // defined in another translation unit, we don't need to emit the
18676 // vtable even though we're using it.
18677 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18678 if (KeyFunction && !KeyFunction->hasBody()) {
18679 // The key function is in another translation unit.
18680 DefineVTable = false;
18682 KeyFunction->getTemplateSpecializationKind();
18685 "Instantiations don't have key functions");
18686 (void)TSK;
18687 } else if (!KeyFunction) {
18688 // If we have a class with no key function that is the subject
18689 // of an explicit instantiation declaration, suppress the
18690 // vtable; it will live with the explicit instantiation
18691 // definition.
18692 bool IsExplicitInstantiationDeclaration =
18694 for (auto *R : Class->redecls()) {
18696 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18698 IsExplicitInstantiationDeclaration = true;
18699 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18700 IsExplicitInstantiationDeclaration = false;
18701 break;
18702 }
18703 }
18704
18705 if (IsExplicitInstantiationDeclaration)
18706 DefineVTable = false;
18707 }
18708
18709 // The exception specifications for all virtual members may be needed even
18710 // if we are not providing an authoritative form of the vtable in this TU.
18711 // We may choose to emit it available_externally anyway.
18712 if (!DefineVTable) {
18714 continue;
18715 }
18716
18717 // Mark all of the virtual members of this class as referenced, so
18718 // that we can build a vtable. Then, tell the AST consumer that a
18719 // vtable for this class is required.
18720 DefinedAnything = true;
18722 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18723 if (VTablesUsed[Canonical])
18725
18726 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18727 // no key function or the key function is inlined. Don't warn in C++ ABIs
18728 // that lack key functions, since the user won't be able to make one.
18730 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18732 const FunctionDecl *KeyFunctionDef = nullptr;
18733 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18734 KeyFunctionDef->isInlined()))
18735 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18736 }
18737 }
18738 VTableUses.clear();
18739
18740 return DefinedAnything;
18741}
18742
18744 const CXXRecordDecl *RD) {
18745 for (const auto *I : RD->methods())
18746 if (I->isVirtual() && !I->isPureVirtual())
18747 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18748}
18749
18751 const CXXRecordDecl *RD,
18752 bool ConstexprOnly) {
18753 // Mark all functions which will appear in RD's vtable as used.
18754 CXXFinalOverriderMap FinalOverriders;
18755 RD->getFinalOverriders(FinalOverriders);
18756 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18757 E = FinalOverriders.end();
18758 I != E; ++I) {
18759 for (OverridingMethods::const_iterator OI = I->second.begin(),
18760 OE = I->second.end();
18761 OI != OE; ++OI) {
18762 assert(OI->second.size() > 0 && "no final overrider");
18763 CXXMethodDecl *Overrider = OI->second.front().Method;
18764
18765 // C++ [basic.def.odr]p2:
18766 // [...] A virtual member function is used if it is not pure. [...]
18767 if (!Overrider->isPureVirtual() &&
18768 (!ConstexprOnly || Overrider->isConstexpr()))
18769 MarkFunctionReferenced(Loc, Overrider);
18770 }
18771 }
18772
18773 // Only classes that have virtual bases need a VTT.
18774 if (RD->getNumVBases() == 0)
18775 return;
18776
18777 for (const auto &I : RD->bases()) {
18778 const auto *Base =
18779 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18780 if (Base->getNumVBases() == 0)
18781 continue;
18783 }
18784}
18785
18786/// SetIvarInitializers - This routine builds initialization ASTs for the
18787/// Objective-C implementation whose ivars need be initialized.
18789 if (!getLangOpts().CPlusPlus)
18790 return;
18791 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18794 if (ivars.empty())
18795 return;
18797 for (unsigned i = 0; i < ivars.size(); i++) {
18798 FieldDecl *Field = ivars[i];
18799 if (Field->isInvalidDecl())
18800 continue;
18801
18804 InitializationKind InitKind =
18805 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18806
18807 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18808 ExprResult MemberInit =
18809 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18810 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18811 // Note, MemberInit could actually come back empty if no initialization
18812 // is required (e.g., because it would call a trivial default constructor)
18813 if (!MemberInit.get() || MemberInit.isInvalid())
18814 continue;
18815
18816 Member =
18819 MemberInit.getAs<Expr>(),
18820 SourceLocation());
18821 AllToInit.push_back(Member);
18822
18823 // Be sure that the destructor is accessible and is marked as referenced.
18824 if (const RecordType *RecordTy =
18825 Context.getBaseElementType(Field->getType())
18826 ->getAs<RecordType>()) {
18827 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18828 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18829 MarkFunctionReferenced(Field->getLocation(), Destructor);
18830 CheckDestructorAccess(Field->getLocation(), Destructor,
18831 PDiag(diag::err_access_dtor_ivar)
18832 << Context.getBaseElementType(Field->getType()));
18833 }
18834 }
18835 }
18836 ObjCImplementation->setIvarInitializers(Context,
18837 AllToInit.data(), AllToInit.size());
18838 }
18839}
18840
18841static
18846 Sema &S) {
18847 if (Ctor->isInvalidDecl())
18848 return;
18849
18851
18852 // Target may not be determinable yet, for instance if this is a dependent
18853 // call in an uninstantiated template.
18854 if (Target) {
18855 const FunctionDecl *FNTarget = nullptr;
18856 (void)Target->hasBody(FNTarget);
18857 Target = const_cast<CXXConstructorDecl*>(
18858 cast_or_null<CXXConstructorDecl>(FNTarget));
18859 }
18860
18861 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18862 // Avoid dereferencing a null pointer here.
18863 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18864
18865 if (!Current.insert(Canonical).second)
18866 return;
18867
18868 // We know that beyond here, we aren't chaining into a cycle.
18869 if (!Target || !Target->isDelegatingConstructor() ||
18870 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18871 Valid.insert(Current.begin(), Current.end());
18872 Current.clear();
18873 // We've hit a cycle.
18874 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18875 Current.count(TCanonical)) {
18876 // If we haven't diagnosed this cycle yet, do so now.
18877 if (!Invalid.count(TCanonical)) {
18878 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18879 diag::warn_delegating_ctor_cycle)
18880 << Ctor;
18881
18882 // Don't add a note for a function delegating directly to itself.
18883 if (TCanonical != Canonical)
18884 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18885
18887 while (C->getCanonicalDecl() != Canonical) {
18888 const FunctionDecl *FNTarget = nullptr;
18889 (void)C->getTargetConstructor()->hasBody(FNTarget);
18890 assert(FNTarget && "Ctor cycle through bodiless function");
18891
18892 C = const_cast<CXXConstructorDecl*>(
18893 cast<CXXConstructorDecl>(FNTarget));
18894 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18895 }
18896 }
18897
18898 Invalid.insert(Current.begin(), Current.end());
18899 Current.clear();
18900 } else {
18901 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18902 }
18903}
18904
18905
18908
18909 for (DelegatingCtorDeclsType::iterator
18912 I != E; ++I)
18913 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18914
18915 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18916 (*CI)->setInvalidDecl();
18917}
18918
18919namespace {
18920 /// AST visitor that finds references to the 'this' expression.
18921 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18922 Sema &S;
18923
18924 public:
18925 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18926
18927 bool VisitCXXThisExpr(CXXThisExpr *E) {
18928 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18929 << E->isImplicit();
18930 return false;
18931 }
18932 };
18933}
18934
18936 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18937 if (!TSInfo)
18938 return false;
18939
18940 TypeLoc TL = TSInfo->getTypeLoc();
18942 if (!ProtoTL)
18943 return false;
18944
18945 // C++11 [expr.prim.general]p3:
18946 // [The expression this] shall not appear before the optional
18947 // cv-qualifier-seq and it shall not appear within the declaration of a
18948 // static member function (although its type and value category are defined
18949 // within a static member function as they are within a non-static member
18950 // function). [ Note: this is because declaration matching does not occur
18951 // until the complete declarator is known. - end note ]
18952 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18953 FindCXXThisExpr Finder(*this);
18954
18955 // If the return type came after the cv-qualifier-seq, check it now.
18956 if (Proto->hasTrailingReturn() &&
18957 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18958 return true;
18959
18960 // Check the exception specification.
18962 return true;
18963
18964 // Check the trailing requires clause
18965 if (Expr *E = Method->getTrailingRequiresClause())
18966 if (!Finder.TraverseStmt(E))
18967 return true;
18968
18970}
18971
18973 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18974 if (!TSInfo)
18975 return false;
18976
18977 TypeLoc TL = TSInfo->getTypeLoc();
18979 if (!ProtoTL)
18980 return false;
18981
18982 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18983 FindCXXThisExpr Finder(*this);
18984
18985 switch (Proto->getExceptionSpecType()) {
18986 case EST_Unparsed:
18987 case EST_Uninstantiated:
18988 case EST_Unevaluated:
18989 case EST_BasicNoexcept:
18990 case EST_NoThrow:
18991 case EST_DynamicNone:
18992 case EST_MSAny:
18993 case EST_None:
18994 break;
18995
18997 case EST_NoexceptFalse:
18998 case EST_NoexceptTrue:
18999 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19000 return true;
19001 [[fallthrough]];
19002
19003 case EST_Dynamic:
19004 for (const auto &E : Proto->exceptions()) {
19005 if (!Finder.TraverseType(E))
19006 return true;
19007 }
19008 break;
19009 }
19010
19011 return false;
19012}
19013
19015 FindCXXThisExpr Finder(*this);
19016
19017 // Check attributes.
19018 for (const auto *A : Method->attrs()) {
19019 // FIXME: This should be emitted by tblgen.
19020 Expr *Arg = nullptr;
19021 ArrayRef<Expr *> Args;
19022 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19023 Arg = G->getArg();
19024 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19025 Arg = G->getArg();
19026 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19027 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19028 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19029 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19030 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19031 Arg = ETLF->getSuccessValue();
19032 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19033 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19034 Arg = STLF->getSuccessValue();
19035 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19036 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19037 Arg = LR->getArg();
19038 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19039 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19040 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19041 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19042 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19043 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19044 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19045 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19046 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19047 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19048
19049 if (Arg && !Finder.TraverseStmt(Arg))
19050 return true;
19051
19052 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19053 if (!Finder.TraverseStmt(Args[I]))
19054 return true;
19055 }
19056 }
19057
19058 return false;
19059}
19060
19062 bool IsTopLevel, ExceptionSpecificationType EST,
19063 ArrayRef<ParsedType> DynamicExceptions,
19064 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19065 SmallVectorImpl<QualType> &Exceptions,
19067 Exceptions.clear();
19068 ESI.Type = EST;
19069 if (EST == EST_Dynamic) {
19070 Exceptions.reserve(DynamicExceptions.size());
19071 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19072 // FIXME: Preserve type source info.
19073 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19074
19075 if (IsTopLevel) {
19077 collectUnexpandedParameterPacks(ET, Unexpanded);
19078 if (!Unexpanded.empty()) {
19080 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19081 Unexpanded);
19082 continue;
19083 }
19084 }
19085
19086 // Check that the type is valid for an exception spec, and
19087 // drop it if not.
19088 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19089 Exceptions.push_back(ET);
19090 }
19091 ESI.Exceptions = Exceptions;
19092 return;
19093 }
19094
19095 if (isComputedNoexcept(EST)) {
19096 assert((NoexceptExpr->isTypeDependent() ||
19097 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19098 Context.BoolTy) &&
19099 "Parser should have made sure that the expression is boolean");
19100 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19101 ESI.Type = EST_BasicNoexcept;
19102 return;
19103 }
19104
19105 ESI.NoexceptExpr = NoexceptExpr;
19106 return;
19107 }
19108}
19109
19112 SourceRange SpecificationRange,
19113 ArrayRef<ParsedType> DynamicExceptions,
19114 ArrayRef<SourceRange> DynamicExceptionRanges,
19115 Expr *NoexceptExpr) {
19116 if (!MethodD)
19117 return;
19118
19119 // Dig out the method we're referring to.
19120 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
19121 MethodD = FunTmpl->getTemplatedDecl();
19122
19123 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
19124 if (!Method)
19125 return;
19126
19127 // Check the exception specification.
19130 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19131 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19132 ESI);
19133
19134 // Update the exception specification on the function type.
19135 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19136
19137 if (Method->isStatic())
19139
19140 if (Method->isVirtual()) {
19141 // Check overrides, which we previously had to delay.
19142 for (const CXXMethodDecl *O : Method->overridden_methods())
19144 }
19145}
19146
19147/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19148///
19150 SourceLocation DeclStart, Declarator &D,
19151 Expr *BitWidth,
19152 InClassInitStyle InitStyle,
19153 AccessSpecifier AS,
19154 const ParsedAttr &MSPropertyAttr) {
19155 IdentifierInfo *II = D.getIdentifier();
19156 if (!II) {
19157 Diag(DeclStart, diag::err_anonymous_property);
19158 return nullptr;
19159 }
19161
19163 QualType T = TInfo->getType();
19164 if (getLangOpts().CPlusPlus) {
19166
19169 D.setInvalidType();
19170 T = Context.IntTy;
19171 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19172 }
19173 }
19174
19176
19178 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19179 << getLangOpts().CPlusPlus17;
19182 diag::err_invalid_thread)
19184
19185 // Check to see if this name was declared as a member previously
19186 NamedDecl *PrevDecl = nullptr;
19187 LookupResult Previous(*this, II, Loc, LookupMemberName,
19189 LookupName(Previous, S);
19190 switch (Previous.getResultKind()) {
19193 PrevDecl = Previous.getAsSingle<NamedDecl>();
19194 break;
19195
19197 PrevDecl = Previous.getRepresentativeDecl();
19198 break;
19199
19203 break;
19204 }
19205
19206 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19207 // Maybe we will complain about the shadowed template parameter.
19209 // Just pretend that we didn't see the previous declaration.
19210 PrevDecl = nullptr;
19211 }
19212
19213 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19214 PrevDecl = nullptr;
19215
19216 SourceLocation TSSL = D.getBeginLoc();
19217 MSPropertyDecl *NewPD =
19218 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19219 MSPropertyAttr.getPropertyDataGetter(),
19220 MSPropertyAttr.getPropertyDataSetter());
19221 ProcessDeclAttributes(TUScope, NewPD, D);
19222 NewPD->setAccess(AS);
19223
19224 if (NewPD->isInvalidDecl())
19225 Record->setInvalidDecl();
19226
19228 NewPD->setModulePrivate();
19229
19230 if (NewPD->isInvalidDecl() && PrevDecl) {
19231 // Don't introduce NewFD into scope; there's already something
19232 // with the same name in the same scope.
19233 } else if (II) {
19234 PushOnScopeChains(NewPD, S);
19235 } else
19236 Record->addDecl(NewPD);
19237
19238 return NewPD;
19239}
19240
19242 Declarator &Declarator, unsigned TemplateParameterDepth) {
19243 auto &Info = InventedParameterInfos.emplace_back();
19244 TemplateParameterList *ExplicitParams = nullptr;
19245 ArrayRef<TemplateParameterList *> ExplicitLists =
19247 if (!ExplicitLists.empty()) {
19248 bool IsMemberSpecialization, IsInvalid;
19251 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19252 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19253 /*SuppressDiagnostic=*/true);
19254 }
19255 // C++23 [dcl.fct]p23:
19256 // An abbreviated function template can have a template-head. The invented
19257 // template-parameters are appended to the template-parameter-list after
19258 // the explicitly declared template-parameters.
19259 //
19260 // A template-head must have one or more template-parameters (read:
19261 // 'template<>' is *not* a template-head). Only append the invented
19262 // template parameters if we matched the nested-name-specifier to a non-empty
19263 // TemplateParameterList.
19264 if (ExplicitParams && !ExplicitParams->empty()) {
19265 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19266 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19267 Info.NumExplicitTemplateParams = ExplicitParams->size();
19268 } else {
19269 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19270 Info.NumExplicitTemplateParams = 0;
19271 }
19272}
19273
19275 auto &FSI = InventedParameterInfos.back();
19276 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19277 if (FSI.NumExplicitTemplateParams != 0) {
19278 TemplateParameterList *ExplicitParams =
19282 Context, ExplicitParams->getTemplateLoc(),
19283 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19284 ExplicitParams->getRAngleLoc(),
19285 ExplicitParams->getRequiresClause()));
19286 } else {
19289 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19290 SourceLocation(), /*RequiresClause=*/nullptr));
19291 }
19292 }
19293 InventedParameterInfos.pop_back();
19294}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3259
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
int Category
Definition: Format.cpp:2955
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:40
llvm::MachO::Record Record
Definition: MachO.h:28
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, Sema::InheritedConstructorInfo *ICI)
static bool RefersToRValueRef(Expr *MemRef)
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
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 Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
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 void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool 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 findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, Sema::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 bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember 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 checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:123
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1068
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:643
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3209
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3223
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
CanQualType LongDoubleTy
Definition: ASTContext.h:1098
CanQualType Char16Ty
Definition: ASTContext.h:1093
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1113
void Deallocate(void *Ptr) const
Definition: ASTContext.h:719
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1114
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
CanQualType WideCharTy
Definition: ASTContext.h:1090
IdentifierTable & Idents
Definition: ASTContext.h:639
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1292
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2246
QualType AutoDeductTy
Definition: ASTContext.h:1142
CanQualType BoolTy
Definition: ASTContext.h:1087
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3188
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1088
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3202
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3195
CanQualType IntTy
Definition: ASTContext.h:1095
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3219
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:692
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
CanQualType BuiltinFnTy
Definition: ASTContext.h:1115
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3184
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3216
CanQualType VoidTy
Definition: ASTContext.h:1086
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3198
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1097
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1553
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3000
CanQualType Char32Ty
Definition: ASTContext.h:1094
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3191
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1182
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3205
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1092
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3212
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:117
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for arrays.
Definition: TypeLoc.h:1535
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1565
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
QualType getElementType() const
Definition: Type.h:3159
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:95
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5524
AutoTypeKeyword getKeyword() const
Definition: Type.h:5555
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3410
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3488
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3139
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3480
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3148
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4235
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3834
Expr * getLHS() const
Definition: Expr.h:3883
Expr * getRHS() const
Definition: Expr.h:3885
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:4767
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3974
Opcode getOpcode() const
Definition: Expr.h:3878
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2129
A binding in a decomposition declaration.
Definition: DeclCXX.h:4100
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3330
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6167
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1288
This class is used for builtin types like 'int'.
Definition: Type.h:2740
Kind getKind() const
Definition: Type.h:2782
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...
std::list< CXXBasePath >::iterator paths_iterator
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1530
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:1110
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1673
bool isImmediateEscalating() const
Definition: ExprCXX.h:1688
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1593
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2770
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:2765
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2599
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2624
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2742
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:2760
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2751
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2765
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2721
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2895
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2293
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2465
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2670
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2657
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2439
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1361
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2855
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:1721
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
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:2453
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2460
bool isVirtual() const
Definition: DeclCXX.h:2108
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2207
bool isVolatile() const
Definition: DeclCXX.h:2106
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2156
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2532
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2526
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2229
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2516
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2179
bool isInstance() const
Definition: DeclCXX.h:2080
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2273
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2203
bool isStatic() const
Definition: DeclCXX.cpp:2185
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2464
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2149
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1270
friend_range friends() const
Definition: DeclFriend.h:246
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:575
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:1563
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:1004
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:830
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:724
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:716
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1389
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:964
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:618
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:568
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1021
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:776
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:895
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:913
method_range methods() const
Definition: DeclCXX.h:660
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:934
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1722
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:976
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:563
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:612
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:707
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:691
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1904
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:635
base_class_iterator vbases_begin()
Definition: DeclCXX.h:642
ctor_range ctors() const
Definition: DeclCXX.h:680
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:877
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:868
bool isDynamicClass() const
Definition: DeclCXX.h:584
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1151
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:809
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:1207
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:803
bool hasDefinition() const
Definition: DeclCXX.h:571
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:919
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1010
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1896
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:905
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:997
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1974
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:1016
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:1605
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:815
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:856
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:986
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2003
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:928
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:1593
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:633
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:949
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:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
Represents the this expression in C++.
Definition: ExprCXX.h:1148
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1167
bool isImplicit() const
Definition: ExprCXX.h:1170
SourceLocation getLocation() const
Definition: ExprCXX.h:1164
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:2819
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3010
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2989
bool isCallToStdMove() const
Definition: Expr.cpp:3496
Expr * getCallee()
Definition: Expr.h:2969
arg_range arguments()
Definition: Expr.h:3058
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3533
Expr * getSubExpr()
Definition: Expr.h:3539
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition: Type.h:2845
QualType getElementType() const
Definition: Type.h:2855
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1604
body_range body()
Definition: Stmt.h:1662
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4173
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3186
const llvm::APInt & getSize() const
Definition: Type.h:3207
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3591
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3655
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3121
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:1379
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2352
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
bool isFileContext() const
Definition: DeclBase.h:2147
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1976
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1265
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2092
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
bool isTranslationUnit() const
Definition: DeclBase.h:2152
bool isRecord() const
Definition: DeclBase.h:2156
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1618
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1699
decl_iterator decls_end() const
Definition: DeclBase.h:2334
bool isStdNamespace() const
Definition: DeclBase.cpp:1249
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2332
bool isFunctionOrMethod() const
Definition: DeclBase.h:2128
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1320
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1335
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1673
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2069
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1346
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1555
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
ValueDecl * getDecl()
Definition: Expr.h:1328
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
bool isImmediateEscalating() const
Definition: Expr.h:1462
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:687
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:641
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:556
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:823
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:821
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:619
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
void ClearConstexprSpec()
Definition: DeclSpec.h:837
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:558
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
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:453
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_auto
Definition: DeclSpec.h:317
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1495
decl_range decls()
Definition: Stmt.h:1543
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1521
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:440
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:578
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:88
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1214
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
@ 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:227
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2749
bool isInvalidDecl() const
Definition: DeclBase.h:593
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:507
SourceLocation getLocation() const
Definition: DeclBase.h:444
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:143
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:830
void setImplicit(bool I=true)
Definition: DeclBase.h:599
void setReferenced(bool R=true)
Definition: DeclBase.h:628
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:453
attr_range attrs() const
Definition: DeclBase.h:540
AccessSpecifier getAccess() const
Definition: DeclBase.h:512
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
void dropAttr()
Definition: DeclBase.h:561
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:582
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.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:881
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:432
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:858
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2455
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2338
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition: DeclSpec.cpp:325
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2397
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2046
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2509
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2335
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2410
bool hasGroupingParens() const
Definition: DeclSpec.h:2718
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2712
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2393
bool isRedeclaration() const
Definition: DeclSpec.h:2764
DeclaratorContext getContext() const
Definition: DeclSpec.h:2071
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2067
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
bool isFunctionDefinition() const
Definition: DeclSpec.h:2736
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2065
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2061
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2648
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2655
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2329
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2210
bool isInvalidType() const
Definition: DeclSpec.h:2713
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2081
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2325
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2053
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2486
A decomposition declaration.
Definition: DeclCXX.h:4159
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4191
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1789
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1827
SourceRange getSourceRange() const
Definition: DeclSpec.h:1835
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1833
Represents a C++17 deduced template specialization type.
Definition: Type.h:5572
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2392
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2372
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2381
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:770
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2292
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2330
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2306
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5585
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:3265
Represents an enum.
Definition: Decl.h:3832
enumerator_range enumerators() const
Definition: Decl.h:3965
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5118
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1892
const Expr * getExpr() const
Definition: DeclCXX.h:1901
void setExpr(Expr *E)
Definition: DeclCXX.h:1926
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1925
This represents one expression.
Definition: Expr.h:110
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3045
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3033
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3041
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3179
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:870
Represents a member of a struct/union/class.
Definition: Decl.h:3025
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4537
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3186
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4611
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4527
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3180
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3209
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4547
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3238
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3249
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:110
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:176
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups)
Definition: Decl.cpp:3096
Represents a function declaration or definition.
Definition: Decl.h:1959
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3201
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2746
bool isTrivialForCall() const
Definition: Decl.h:2317
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2413
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3678
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4019
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3220
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2258
bool isImmediateFunction() const
Definition: Decl.cpp:3253
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3838
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3439
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3696
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2798
SourceLocation getDefaultLoc() const
Definition: Decl.h:2335
QualType getReturnType() const
Definition: Decl.h:2722
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2326
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2314
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4127
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2659
void setWillHaveBody(bool V=true)
Definition: Decl.h:2571
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3582
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3832
param_iterator param_begin()
Definition: Decl.h:2663
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2700
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2270
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2423
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4143
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4071
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2765
bool isStatic() const
Definition: Decl.h:2806
void setTrivial(bool IT)
Definition: Decl.h:2315
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3958
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2297
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3457
bool isImmediateEscalating() const
Definition: Decl.cpp:3233
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3271
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2793
void setTrivialForCall(bool IT)
Definition: Decl.h:2318
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3145
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2164
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2322
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4362
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2810
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3944
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2410
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4233
void setDefaulted(bool D=true)
Definition: Decl.h:2323
bool isConsteval() const
Definition: Decl.h:2419
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2347
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:2739
DefaultedFunctionInfo * getDefaultedFunctionInfo() const
Definition: Decl.cpp:3117
void setBody(Stmt *B)
Definition: Decl.cpp:3213
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2288
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3710
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3657
size_t param_size() const
Definition: Decl.h:2667
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2157
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2485
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3121
void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info)
Definition: Decl.cpp:3108
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:3168
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2776
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2682
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2570
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4644
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4458
unsigned getNumParams() const
Definition: Type.h:4432
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4571
QualType getParamType(unsigned i) const
Definition: Type.h:4434
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4443
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4516
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4439
ArrayRef< QualType > exceptions() const
Definition: Type.h:4601
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:4616
Declaration of a template function.
Definition: DeclTemplate.h:958
Wrapper for source info for functions.
Definition: TypeLoc.h:1402
unsigned getNumParams() const
Definition: TypeLoc.h:1474
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1480
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1481
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1483
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4025
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3799
CallingConv getCallConv() const
Definition: Type.h:4127
QualType getReturnType() const
Definition: Type.h:4116
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2136
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3649
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2060
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5594
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3309
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3330
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2499
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2511
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4841
unsigned getNumInits() const
Definition: Expr.h:4871
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4887
child_range children()
Definition: Expr.h:5033
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8578
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3465
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:957
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1938
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1290
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1303
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:582
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
Represents a linkage specification.
Definition: DeclCXX.h:2927
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2918
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2969
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:670
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:716
bool hasNext() const
Definition: Lookup.h:701
NamedDecl * next()
Definition: Lookup.h:705
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:600
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:466
DeclClass * getAsSingle() const
Definition: Lookup.h:553
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:472
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:268
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:359
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:483
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:659
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:744
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:563
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:308
bool isAmbiguous() const
Definition: Lookup.h:321
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:405
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:328
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:273
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:570
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
iterator end() const
Definition: Lookup.h:356
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:355
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:253
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4228
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3395
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3182
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3261
Expr * getBase() const
Definition: Expr.h:3255
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3373
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1306
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:675
bool isExplicitGlobalModule() const
Definition: Module.h:203
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:696
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represents a C++ namespace alias.
Definition: DeclCXX.h:3113
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3035
Represent a C++ namespace.
Definition: Decl.h:547
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:610
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2980
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:665
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:688
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2319
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:977
@ CSK_Normal
Normal lookup.
Definition: Overload.h:981
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:988
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1150
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4709
Represents a parameter to a function.
Definition: Decl.h:1749
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2980
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1845
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1890
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1878
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2985
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3005
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1782
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1882
bool hasInheritedDefaultArg() const
Definition: Decl.h:1894
bool isExplicitObjectParameter() const
Definition: Decl.h:1837
Expr * getDefaultArg()
Definition: Decl.cpp:2968
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3010
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1898
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:477
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:471
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:831
const ParsedAttr * getMSPropertyAttr() const
Definition: ParsedAttr.h:917
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:911
Wrapper for source info for pointers.
Definition: TypeLoc.h:1275
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6299
ArrayRef< Expr * > semantics()
Definition: Expr.h:6378
A (possibly-)qualified type.
Definition: Type.h:737
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6985
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2665
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
QualType withConst() const
Definition: Type.h:951
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1017
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:948
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7102
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2777
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:889
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7073
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6974
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6948
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1124
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1233
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2510
The collection of all-type qualifiers we support.
Definition: Type.h:147
void addAddressSpace(LangAS space)
Definition: Type.h:404
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
void removeConst()
Definition: Type.h:266
void removeAddressSpace()
Definition: Type.h:403
void addConst()
Definition: Type.h:267
void removeVolatile()
Definition: Type.h:276
LangAS getAddressSpace() const
Definition: Type.h:378
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
Represents a struct/union/class.
Definition: Decl.h:4133
bool hasFlexibleArrayMember() const
Definition: Decl.h:4166
field_iterator field_end() const
Definition: Decl.h:4342
field_range fields() const
Definition: Decl.h:4339
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5001
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4185
bool field_empty() const
Definition: Decl.h:4347
field_iterator field_begin() const
Definition: Decl.cpp:5035
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4959
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
QualType getPointeeType() const
Definition: Type.h:3027
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3017
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:386
void AddDecl(Decl *D)
Definition: Scope.h:339
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:264
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A RAII object to enter scope of a compound statement.
Definition: Sema.h:1037
bool isInvalid() const
Definition: Sema.h:6096
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4851
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4878
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:4875
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:4181
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:598
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:7559
CXXMethodDecl * getMethod() const
Definition: Sema.h:7571
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:10423
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5994
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11095
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6810
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4810
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, ASTContext &Ctx, bool ErrorOnInvalidMessage)
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10034
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9848
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
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:4996
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1575
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3859
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16292
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7634
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7642
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:7630
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7615
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:417
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6746
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMember > SpecialMemberDecl
Definition: Sema.h:4991
VariadicCallType
Definition: Sema.h:2145
@ VariadicDoesNotApply
Definition: Sema.h:2150
@ VariadicConstructor
Definition: Sema.h:2149
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6215
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void PrintContextStack()
Definition: Sema.h:10563
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:4801
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6182
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:997
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:4973
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:4954
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1097
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:18205
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
@ AR_dependent
Definition: Sema.h:1211
@ AR_accessible
Definition: Sema.h:1209
@ AR_inaccessible
Definition: Sema.h:1210
@ AR_delayed
Definition: Sema.h:1212
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:2260
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2122
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
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 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)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6344
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17996
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4891
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
@ Other
C++ [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bloc...
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.
Definition: SemaDecl.cpp:18546
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1556
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.
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.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CCK_ImplicitConversion)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
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:1030
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5883
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
ExprResult ActOnCXXThis(SourceLocation loc)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation IdentLoc, IdentifierInfo &II, CXXScopeSpec *SS=nullptr)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5001
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:6008
@ AllowFold
Definition: Sema.h:6010
@ NoFold
Definition: Sema.h:6009
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1517
ASTContext & getASTContext() const
Definition: Sema.h:501
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:4980
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:20680
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:5058
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18631
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
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:4655
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
@ None
This is not a defaultable comparison operator.
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9635
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
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:947
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2199
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=std::nullopt)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9516
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1508
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6707
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1961
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2141
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:496
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:21174
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
@ UPPC_RequiresClause
Definition: Sema.h:11098
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:11053
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:11071
@ UPPC_Initializer
An initializer.
Definition: Sema.h:11062
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:11032
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:11056
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:11065
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:11035
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:11038
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:11044
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:494
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...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
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:4545
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1407
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 CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:860
Preprocessor & PP
Definition: Sema.h:1029
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:7195
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8323
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:11484
const LangOptions & LangOpts
Definition: Sema.h:1028
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:18327
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8541
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4958
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11970
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)
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
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:4551
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:4034
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:4951
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20815
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:3854
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:5050
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4984
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9733
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, SourceLocation DefaultLoc)
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1394
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:13706
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
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...
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2264
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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)
ActOnBaseSpecifier - Parsed a base specifier.
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
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:10046
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:4541
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:645
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3423
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11968
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:7993
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15594
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:5394
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:4965
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15521
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:7694
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
Definition: Sema.h:7698
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15065
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5889
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:4838
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:4840
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:4843
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6505
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20762
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2161
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:10722
SourceManager & getSourceManager() const
Definition: Sema.h:499
@ AA_Passing
Definition: Sema.h:5381
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)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1359
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:7587
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9860
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:7701
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.
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1368
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.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:224
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8357
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)
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:360
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:4017
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11943
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_ErrorRecovery
Definition: Sema.h:7859
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14425
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4976
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind)
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
@ CCEK_StaticAssertMessageSize
Call to size() in a static assert message.
Definition: Sema.h:8282
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8280
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:8284
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3179
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:286
bool isInOpenMPTargetExecutionDirective() const
Return true inside OpenMP target region.
ASTConsumer & Consumer
Definition: Sema.h:1031
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:3561
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:8188
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:8180
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:8184
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:117
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5898
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.
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6964
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9828
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6102
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17286
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9249
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1002
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19273
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Definition: SemaAttr.cpp:1377
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:8123
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18709
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1324
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:1033
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 ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition: Sema.h:1032
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:6066
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
@ TUK_Friend
Definition: Sema.h:3322
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7381
@ TPC_TypeAliasTemplate
Definition: Sema.h:9260
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6850
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:6331
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1331
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:3333
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4988
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1597
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9813
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1580
@ OOK_Outside
Definition: Sema.h:3327
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13503
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:301
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:4800
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18892
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6681
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21957
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6151
AbstractDiagSelID
Definition: Sema.h:4755
@ AbstractVariableType
Definition: Sema.h:4759
@ AbstractReturnType
Definition: Sema.h:4757
@ AbstractNone
Definition: Sema.h:4756
@ AbstractFieldType
Definition: Sema.h:4760
@ AbstractArrayType
Definition: Sema.h:4763
@ AbstractParamType
Definition: Sema.h:4758
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:905
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1720
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6711
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:15604
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition: Sema.h:4898
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:4270
@ CXXCopyConstructor
Definition: Sema.h:4272
@ CXXMoveConstructor
Definition: Sema.h:4273
@ CXXDestructor
Definition: Sema.h:4276
@ CXXDefaultConstructor
Definition: Sema.h:4271
@ CXXInvalid
Definition: Sema.h:4277
@ CXXMoveAssignment
Definition: Sema.h:4275
@ CXXCopyAssignment
Definition: Sema.h:4274
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3213
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:411
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:2664
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6138
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7549
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:6126
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:541
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6967
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3303
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isUnevaluated() const
Definition: Expr.h:1902
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3549
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3672
StringRef getKindName() const
Definition: Decl.h:3740
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3652
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4693
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4687
bool isUnion() const
Definition: Decl.h:3755
TagKind getTagKind() const
Definition: Decl.h:3744
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3703
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:206
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:582
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1258
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ Template
A single template declaration.
Definition: TemplateName.h:219
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1664
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
unsigned getIndex() const
Definition: Type.h:5322
unsigned getDepth() const
Definition: Type.h:5321
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3521
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3539
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5512
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:3357
const Type * getTypeForDecl() const
Definition: Decl.h:3381
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1199
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:116
bool isNull() const
Definition: TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2653
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:6873
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6884
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3088
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5895
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3070
The base class of the type hierarchy.
Definition: Type.h:1606
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2403
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isVoidType() const
Definition: Type.h:7443
bool isBooleanType() const
Definition: Type.h:7567
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2829
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isUndeducedAutoType() const
Definition: Type.h:7299
bool isRValueReferenceType() const
Definition: Type.h:7174
bool isArrayType() const
Definition: Type.h:7220
bool isPointerType() const
Definition: Type.h:7154
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7479
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
bool isEnumeralType() const
Definition: Type.h:7248
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3195
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isLValueReferenceType() const
Definition: Type.h:7170
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7412
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2094
QualType getCanonicalTypeInternal() const
Definition: Type.h:2703
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2414
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7607
bool isFunctionProtoType() const
Definition: Type.h:2263
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:7580
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2438
bool isObjCObjectType() const
Definition: Type.h:7286
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7573
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2203
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isRecordType() const
Definition: Type.h:7244
bool isUnionType() const
Definition: Type.cpp:621
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1827
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1823
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3399
QualType getUnderlyingType() const
Definition: Decl.h:3454
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2182
Expr * getSubExpr() const
Definition: Expr.h:2227
Opcode getOpcode() const
Definition: Expr.h:2222
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2282
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:4824
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:1060
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1236
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:1068
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:1071
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:373
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4033
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3283
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3952
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3263
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3855
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3235
Represents a C++ using-declaration.
Definition: DeclCXX.h:3505
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3554
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3546
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3170
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3542
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3532
Represents C++ using-directive.
Definition: DeclCXX.h:3008
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2935
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3706
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3191
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3213
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3313
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3349
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3377
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3110
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1546
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2257
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2813
bool isInlineSpecified() const
Definition: Decl.h:1531
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2551
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1267
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1210
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:1192
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2820
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1161
const Expr * getInit() const
Definition: Decl.h:1352
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:944
void setInit(Expr *I)
Definition: Decl.cpp:2454
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1152
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:2505
void setExceptionVariable(bool EV)
Definition: Decl.h:1474
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3512
unsigned getNumElements() const
Definition: Type.h:3527
QualType getElementType() const
Definition: Type.h:3526
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2779
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2799
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2811
bool isOverrideSpecified() const
Definition: DeclSpec.h:2798
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2803
bool isFinalSpecified() const
Definition: DeclSpec.h:2801
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2802
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition: ScopeInfo.h:179
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:60
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:589
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1809
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:708
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:155
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ CPlusPlus23
Definition: LangStandard.h:59
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:56
@ CPlusPlus26
Definition: LangStandard.h:60
@ CPlusPlus17
Definition: LangStandard.h:57
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2919
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:268
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1555
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1561
@ 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:1522
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:805
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:5842
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanPassInRegs
The argument of this type can be passed directly in registers.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:988
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5817
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:123
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
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:1365
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1425
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1374
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1428
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1526
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1555
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1558
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1464
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1551
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1339
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
enum clang::DeclaratorChunk::@216 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1639
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Holds information about the various types of exception specification.
Definition: Type.h:4250
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:4262
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4252
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4255
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4258
Extra information about a function prototype.
Definition: Type.h:4278
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4285
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4279
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1003
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:10051
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:10165
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:10145
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:10142
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:10095
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:10109
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:10113
CXXSpecialMember SpecialMember
The special member being declared or defined.
Definition: Sema.h:10194
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:10168
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6610
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:104