Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
35233 views
//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for C++ declarations.9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/ASTConsumer.h"13#include "clang/AST/ASTContext.h"14#include "clang/AST/ASTLambda.h"15#include "clang/AST/ASTMutationListener.h"16#include "clang/AST/CXXInheritance.h"17#include "clang/AST/CharUnits.h"18#include "clang/AST/ComparisonCategories.h"19#include "clang/AST/DeclCXX.h"20#include "clang/AST/DeclTemplate.h"21#include "clang/AST/EvaluatedExprVisitor.h"22#include "clang/AST/Expr.h"23#include "clang/AST/ExprCXX.h"24#include "clang/AST/RecordLayout.h"25#include "clang/AST/RecursiveASTVisitor.h"26#include "clang/AST/StmtVisitor.h"27#include "clang/AST/TypeLoc.h"28#include "clang/AST/TypeOrdering.h"29#include "clang/Basic/AttributeCommonInfo.h"30#include "clang/Basic/PartialDiagnostic.h"31#include "clang/Basic/Specifiers.h"32#include "clang/Basic/TargetInfo.h"33#include "clang/Lex/LiteralSupport.h"34#include "clang/Lex/Preprocessor.h"35#include "clang/Sema/CXXFieldCollector.h"36#include "clang/Sema/DeclSpec.h"37#include "clang/Sema/EnterExpressionEvaluationContext.h"38#include "clang/Sema/Initialization.h"39#include "clang/Sema/Lookup.h"40#include "clang/Sema/Ownership.h"41#include "clang/Sema/ParsedTemplate.h"42#include "clang/Sema/Scope.h"43#include "clang/Sema/ScopeInfo.h"44#include "clang/Sema/SemaCUDA.h"45#include "clang/Sema/SemaInternal.h"46#include "clang/Sema/SemaObjC.h"47#include "clang/Sema/SemaOpenMP.h"48#include "clang/Sema/Template.h"49#include "llvm/ADT/ArrayRef.h"50#include "llvm/ADT/STLExtras.h"51#include "llvm/ADT/STLForwardCompat.h"52#include "llvm/ADT/ScopeExit.h"53#include "llvm/ADT/SmallString.h"54#include "llvm/ADT/StringExtras.h"55#include "llvm/Support/ConvertUTF.h"56#include "llvm/Support/SaveAndRestore.h"57#include <map>58#include <optional>59#include <set>6061using namespace clang;6263//===----------------------------------------------------------------------===//64// CheckDefaultArgumentVisitor65//===----------------------------------------------------------------------===//6667namespace {68/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses69/// the default argument of a parameter to determine whether it70/// contains any ill-formed subexpressions. For example, this will71/// diagnose the use of local variables or parameters within the72/// default argument expression.73class CheckDefaultArgumentVisitor74: public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {75Sema &S;76const Expr *DefaultArg;7778public:79CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)80: S(S), DefaultArg(DefaultArg) {}8182bool VisitExpr(const Expr *Node);83bool VisitDeclRefExpr(const DeclRefExpr *DRE);84bool VisitCXXThisExpr(const CXXThisExpr *ThisE);85bool VisitLambdaExpr(const LambdaExpr *Lambda);86bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);87};8889/// VisitExpr - Visit all of the children of this expression.90bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {91bool IsInvalid = false;92for (const Stmt *SubStmt : Node->children())93if (SubStmt)94IsInvalid |= Visit(SubStmt);95return IsInvalid;96}9798/// VisitDeclRefExpr - Visit a reference to a declaration, to99/// determine whether this declaration can be used in the default100/// argument expression.101bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {102const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());103104if (!isa<VarDecl, BindingDecl>(Decl))105return false;106107if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {108// C++ [dcl.fct.default]p9:109// [...] parameters of a function shall not be used in default110// argument expressions, even if they are not evaluated. [...]111//112// C++17 [dcl.fct.default]p9 (by CWG 2082):113// [...] A parameter shall not appear as a potentially-evaluated114// expression in a default argument. [...]115//116if (DRE->isNonOdrUse() != NOUR_Unevaluated)117return S.Diag(DRE->getBeginLoc(),118diag::err_param_default_argument_references_param)119<< Param->getDeclName() << DefaultArg->getSourceRange();120} else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {121// C++ [dcl.fct.default]p7:122// Local variables shall not be used in default argument123// expressions.124//125// C++17 [dcl.fct.default]p7 (by CWG 2082):126// A local variable shall not appear as a potentially-evaluated127// expression in a default argument.128//129// C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):130// Note: A local variable cannot be odr-used (6.3) in a default131// argument.132//133if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())134return S.Diag(DRE->getBeginLoc(),135diag::err_param_default_argument_references_local)136<< Decl << DefaultArg->getSourceRange();137}138return false;139}140141/// VisitCXXThisExpr - Visit a C++ "this" expression.142bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {143// C++ [dcl.fct.default]p8:144// The keyword this shall not be used in a default argument of a145// member function.146return S.Diag(ThisE->getBeginLoc(),147diag::err_param_default_argument_references_this)148<< ThisE->getSourceRange();149}150151bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(152const PseudoObjectExpr *POE) {153bool Invalid = false;154for (const Expr *E : POE->semantics()) {155// Look through bindings.156if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {157E = OVE->getSourceExpr();158assert(E && "pseudo-object binding without source expression?");159}160161Invalid |= Visit(E);162}163return Invalid;164}165166bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {167// [expr.prim.lambda.capture]p9168// a lambda-expression appearing in a default argument cannot implicitly or169// explicitly capture any local entity. Such a lambda-expression can still170// have an init-capture if any full-expression in its initializer satisfies171// the constraints of an expression appearing in a default argument.172bool Invalid = false;173for (const LambdaCapture &LC : Lambda->captures()) {174if (!Lambda->isInitCapture(&LC))175return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);176// Init captures are always VarDecl.177auto *D = cast<VarDecl>(LC.getCapturedVar());178Invalid |= Visit(D->getInit());179}180return Invalid;181}182} // namespace183184void185Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,186const CXXMethodDecl *Method) {187// If we have an MSAny spec already, don't bother.188if (!Method || ComputedEST == EST_MSAny)189return;190191const FunctionProtoType *Proto192= Method->getType()->getAs<FunctionProtoType>();193Proto = Self->ResolveExceptionSpec(CallLoc, Proto);194if (!Proto)195return;196197ExceptionSpecificationType EST = Proto->getExceptionSpecType();198199// If we have a throw-all spec at this point, ignore the function.200if (ComputedEST == EST_None)201return;202203if (EST == EST_None && Method->hasAttr<NoThrowAttr>())204EST = EST_BasicNoexcept;205206switch (EST) {207case EST_Unparsed:208case EST_Uninstantiated:209case EST_Unevaluated:210llvm_unreachable("should not see unresolved exception specs here");211212// If this function can throw any exceptions, make a note of that.213case EST_MSAny:214case EST_None:215// FIXME: Whichever we see last of MSAny and None determines our result.216// We should make a consistent, order-independent choice here.217ClearExceptions();218ComputedEST = EST;219return;220case EST_NoexceptFalse:221ClearExceptions();222ComputedEST = EST_None;223return;224// FIXME: If the call to this decl is using any of its default arguments, we225// need to search them for potentially-throwing calls.226// If this function has a basic noexcept, it doesn't affect the outcome.227case EST_BasicNoexcept:228case EST_NoexceptTrue:229case EST_NoThrow:230return;231// If we're still at noexcept(true) and there's a throw() callee,232// change to that specification.233case EST_DynamicNone:234if (ComputedEST == EST_BasicNoexcept)235ComputedEST = EST_DynamicNone;236return;237case EST_DependentNoexcept:238llvm_unreachable(239"should not generate implicit declarations for dependent cases");240case EST_Dynamic:241break;242}243assert(EST == EST_Dynamic && "EST case not considered earlier.");244assert(ComputedEST != EST_None &&245"Shouldn't collect exceptions when throw-all is guaranteed.");246ComputedEST = EST_Dynamic;247// Record the exceptions in this function's exception specification.248for (const auto &E : Proto->exceptions())249if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)250Exceptions.push_back(E);251}252253void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {254if (!S || ComputedEST == EST_MSAny)255return;256257// FIXME:258//259// C++0x [except.spec]p14:260// [An] implicit exception-specification specifies the type-id T if and261// only if T is allowed by the exception-specification of a function directly262// invoked by f's implicit definition; f shall allow all exceptions if any263// function it directly invokes allows all exceptions, and f shall allow no264// exceptions if every function it directly invokes allows no exceptions.265//266// Note in particular that if an implicit exception-specification is generated267// for a function containing a throw-expression, that specification can still268// be noexcept(true).269//270// Note also that 'directly invoked' is not defined in the standard, and there271// is no indication that we should only consider potentially-evaluated calls.272//273// Ultimately we should implement the intent of the standard: the exception274// specification should be the set of exceptions which can be thrown by the275// implicit definition. For now, we assume that any non-nothrow expression can276// throw any exception.277278if (Self->canThrow(S))279ComputedEST = EST_None;280}281282ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,283SourceLocation EqualLoc) {284if (RequireCompleteType(Param->getLocation(), Param->getType(),285diag::err_typecheck_decl_incomplete_type))286return true;287288// C++ [dcl.fct.default]p5289// A default argument expression is implicitly converted (clause290// 4) to the parameter type. The default argument expression has291// the same semantic constraints as the initializer expression in292// a declaration of a variable of the parameter type, using the293// copy-initialization semantics (8.5).294InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,295Param);296InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),297EqualLoc);298InitializationSequence InitSeq(*this, Entity, Kind, Arg);299ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);300if (Result.isInvalid())301return true;302Arg = Result.getAs<Expr>();303304CheckCompletedExpr(Arg, EqualLoc);305Arg = MaybeCreateExprWithCleanups(Arg);306307return Arg;308}309310void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,311SourceLocation EqualLoc) {312// Add the default argument to the parameter313Param->setDefaultArg(Arg);314315// We have already instantiated this parameter; provide each of the316// instantiations with the uninstantiated default argument.317UnparsedDefaultArgInstantiationsMap::iterator InstPos318= UnparsedDefaultArgInstantiations.find(Param);319if (InstPos != UnparsedDefaultArgInstantiations.end()) {320for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)321InstPos->second[I]->setUninstantiatedDefaultArg(Arg);322323// We're done tracking this parameter's instantiations.324UnparsedDefaultArgInstantiations.erase(InstPos);325}326}327328void329Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,330Expr *DefaultArg) {331if (!param || !DefaultArg)332return;333334ParmVarDecl *Param = cast<ParmVarDecl>(param);335UnparsedDefaultArgLocs.erase(Param);336337// Default arguments are only permitted in C++338if (!getLangOpts().CPlusPlus) {339Diag(EqualLoc, diag::err_param_default_argument)340<< DefaultArg->getSourceRange();341return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);342}343344// Check for unexpanded parameter packs.345if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))346return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);347348// C++11 [dcl.fct.default]p3349// A default argument expression [...] shall not be specified for a350// parameter pack.351if (Param->isParameterPack()) {352Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)353<< DefaultArg->getSourceRange();354// Recover by discarding the default argument.355Param->setDefaultArg(nullptr);356return;357}358359ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);360if (Result.isInvalid())361return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);362363DefaultArg = Result.getAs<Expr>();364365// Check that the default argument is well-formed366CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);367if (DefaultArgChecker.Visit(DefaultArg))368return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);369370SetParamDefaultArgument(Param, DefaultArg, EqualLoc);371}372373void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,374SourceLocation EqualLoc,375SourceLocation ArgLoc) {376if (!param)377return;378379ParmVarDecl *Param = cast<ParmVarDecl>(param);380Param->setUnparsedDefaultArg();381UnparsedDefaultArgLocs[Param] = ArgLoc;382}383384void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,385Expr *DefaultArg) {386if (!param)387return;388389ParmVarDecl *Param = cast<ParmVarDecl>(param);390Param->setInvalidDecl();391UnparsedDefaultArgLocs.erase(Param);392ExprResult RE;393if (DefaultArg) {394RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},395Param->getType().getNonReferenceType());396} else {397RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},398Param->getType().getNonReferenceType());399}400Param->setDefaultArg(RE.get());401}402403void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {404// C++ [dcl.fct.default]p3405// A default argument expression shall be specified only in the406// parameter-declaration-clause of a function declaration or in a407// template-parameter (14.1). It shall not be specified for a408// parameter pack. If it is specified in a409// parameter-declaration-clause, it shall not occur within a410// declarator or abstract-declarator of a parameter-declaration.411bool MightBeFunction = D.isFunctionDeclarationContext();412for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {413DeclaratorChunk &chunk = D.getTypeObject(i);414if (chunk.Kind == DeclaratorChunk::Function) {415if (MightBeFunction) {416// This is a function declaration. It can have default arguments, but417// keep looking in case its return type is a function type with default418// arguments.419MightBeFunction = false;420continue;421}422for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;423++argIdx) {424ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);425if (Param->hasUnparsedDefaultArg()) {426std::unique_ptr<CachedTokens> Toks =427std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);428SourceRange SR;429if (Toks->size() > 1)430SR = SourceRange((*Toks)[1].getLocation(),431Toks->back().getLocation());432else433SR = UnparsedDefaultArgLocs[Param];434Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)435<< SR;436} else if (Param->getDefaultArg()) {437Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)438<< Param->getDefaultArg()->getSourceRange();439Param->setDefaultArg(nullptr);440}441}442} else if (chunk.Kind != DeclaratorChunk::Paren) {443MightBeFunction = false;444}445}446}447448static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {449return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {450return P->hasDefaultArg() && !P->hasInheritedDefaultArg();451});452}453454bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,455Scope *S) {456bool Invalid = false;457458// The declaration context corresponding to the scope is the semantic459// parent, unless this is a local function declaration, in which case460// it is that surrounding function.461DeclContext *ScopeDC = New->isLocalExternDecl()462? New->getLexicalDeclContext()463: New->getDeclContext();464465// Find the previous declaration for the purpose of default arguments.466FunctionDecl *PrevForDefaultArgs = Old;467for (/**/; PrevForDefaultArgs;468// Don't bother looking back past the latest decl if this is a local469// extern declaration; nothing else could work.470PrevForDefaultArgs = New->isLocalExternDecl()471? nullptr472: PrevForDefaultArgs->getPreviousDecl()) {473// Ignore hidden declarations.474if (!LookupResult::isVisible(*this, PrevForDefaultArgs))475continue;476477if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&478!New->isCXXClassMember()) {479// Ignore default arguments of old decl if they are not in480// the same scope and this is not an out-of-line definition of481// a member function.482continue;483}484485if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {486// If only one of these is a local function declaration, then they are487// declared in different scopes, even though isDeclInScope may think488// they're in the same scope. (If both are local, the scope check is489// sufficient, and if neither is local, then they are in the same scope.)490continue;491}492493// We found the right previous declaration.494break;495}496497// C++ [dcl.fct.default]p4:498// For non-template functions, default arguments can be added in499// later declarations of a function in the same500// scope. Declarations in different scopes have completely501// distinct sets of default arguments. That is, declarations in502// inner scopes do not acquire default arguments from503// declarations in outer scopes, and vice versa. In a given504// function declaration, all parameters subsequent to a505// parameter with a default argument shall have default506// arguments supplied in this or previous declarations. A507// default argument shall not be redefined by a later508// declaration (not even to the same value).509//510// C++ [dcl.fct.default]p6:511// Except for member functions of class templates, the default arguments512// in a member function definition that appears outside of the class513// definition are added to the set of default arguments provided by the514// member function declaration in the class definition.515for (unsigned p = 0, NumParams = PrevForDefaultArgs516? PrevForDefaultArgs->getNumParams()517: 0;518p < NumParams; ++p) {519ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);520ParmVarDecl *NewParam = New->getParamDecl(p);521522bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;523bool NewParamHasDfl = NewParam->hasDefaultArg();524525if (OldParamHasDfl && NewParamHasDfl) {526unsigned DiagDefaultParamID =527diag::err_param_default_argument_redefinition;528529// MSVC accepts that default parameters be redefined for member functions530// of template class. The new default parameter's value is ignored.531Invalid = true;532if (getLangOpts().MicrosoftExt) {533CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);534if (MD && MD->getParent()->getDescribedClassTemplate()) {535// Merge the old default argument into the new parameter.536NewParam->setHasInheritedDefaultArg();537if (OldParam->hasUninstantiatedDefaultArg())538NewParam->setUninstantiatedDefaultArg(539OldParam->getUninstantiatedDefaultArg());540else541NewParam->setDefaultArg(OldParam->getInit());542DiagDefaultParamID = diag::ext_param_default_argument_redefinition;543Invalid = false;544}545}546547// FIXME: If we knew where the '=' was, we could easily provide a fix-it548// hint here. Alternatively, we could walk the type-source information549// for NewParam to find the last source location in the type... but it550// isn't worth the effort right now. This is the kind of test case that551// is hard to get right:552// int f(int);553// void g(int (*fp)(int) = f);554// void g(int (*fp)(int) = &f);555Diag(NewParam->getLocation(), DiagDefaultParamID)556<< NewParam->getDefaultArgRange();557558// Look for the function declaration where the default argument was559// actually written, which may be a declaration prior to Old.560for (auto Older = PrevForDefaultArgs;561OldParam->hasInheritedDefaultArg(); /**/) {562Older = Older->getPreviousDecl();563OldParam = Older->getParamDecl(p);564}565566Diag(OldParam->getLocation(), diag::note_previous_definition)567<< OldParam->getDefaultArgRange();568} else if (OldParamHasDfl) {569// Merge the old default argument into the new parameter unless the new570// function is a friend declaration in a template class. In the latter571// case the default arguments will be inherited when the friend572// declaration will be instantiated.573if (New->getFriendObjectKind() == Decl::FOK_None ||574!New->getLexicalDeclContext()->isDependentContext()) {575// It's important to use getInit() here; getDefaultArg()576// strips off any top-level ExprWithCleanups.577NewParam->setHasInheritedDefaultArg();578if (OldParam->hasUnparsedDefaultArg())579NewParam->setUnparsedDefaultArg();580else if (OldParam->hasUninstantiatedDefaultArg())581NewParam->setUninstantiatedDefaultArg(582OldParam->getUninstantiatedDefaultArg());583else584NewParam->setDefaultArg(OldParam->getInit());585}586} else if (NewParamHasDfl) {587if (New->getDescribedFunctionTemplate()) {588// Paragraph 4, quoted above, only applies to non-template functions.589Diag(NewParam->getLocation(),590diag::err_param_default_argument_template_redecl)591<< NewParam->getDefaultArgRange();592Diag(PrevForDefaultArgs->getLocation(),593diag::note_template_prev_declaration)594<< false;595} else if (New->getTemplateSpecializationKind()596!= TSK_ImplicitInstantiation &&597New->getTemplateSpecializationKind() != TSK_Undeclared) {598// C++ [temp.expr.spec]p21:599// Default function arguments shall not be specified in a declaration600// or a definition for one of the following explicit specializations:601// - the explicit specialization of a function template;602// - the explicit specialization of a member function template;603// - the explicit specialization of a member function of a class604// template where the class template specialization to which the605// member function specialization belongs is implicitly606// instantiated.607Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)608<< (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)609<< New->getDeclName()610<< NewParam->getDefaultArgRange();611} else if (New->getDeclContext()->isDependentContext()) {612// C++ [dcl.fct.default]p6 (DR217):613// Default arguments for a member function of a class template shall614// be specified on the initial declaration of the member function615// within the class template.616//617// Reading the tea leaves a bit in DR217 and its reference to DR205618// leads me to the conclusion that one cannot add default function619// arguments for an out-of-line definition of a member function of a620// dependent type.621int WhichKind = 2;622if (CXXRecordDecl *Record623= dyn_cast<CXXRecordDecl>(New->getDeclContext())) {624if (Record->getDescribedClassTemplate())625WhichKind = 0;626else if (isa<ClassTemplatePartialSpecializationDecl>(Record))627WhichKind = 1;628else629WhichKind = 2;630}631632Diag(NewParam->getLocation(),633diag::err_param_default_argument_member_template_redecl)634<< WhichKind635<< NewParam->getDefaultArgRange();636}637}638}639640// DR1344: If a default argument is added outside a class definition and that641// default argument makes the function a special member function, the program642// is ill-formed. This can only happen for constructors.643if (isa<CXXConstructorDecl>(New) &&644New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {645CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),646OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));647if (NewSM != OldSM) {648ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());649assert(NewParam->hasDefaultArg());650Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)651<< NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);652Diag(Old->getLocation(), diag::note_previous_declaration);653}654}655656const FunctionDecl *Def;657// C++11 [dcl.constexpr]p1: If any declaration of a function or function658// template has a constexpr specifier then all its declarations shall659// contain the constexpr specifier.660if (New->getConstexprKind() != Old->getConstexprKind()) {661Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)662<< New << static_cast<int>(New->getConstexprKind())663<< static_cast<int>(Old->getConstexprKind());664Diag(Old->getLocation(), diag::note_previous_declaration);665Invalid = true;666} else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&667Old->isDefined(Def) &&668// If a friend function is inlined but does not have 'inline'669// specifier, it is a definition. Do not report attribute conflict670// in this case, redefinition will be diagnosed later.671(New->isInlineSpecified() ||672New->getFriendObjectKind() == Decl::FOK_None)) {673// C++11 [dcl.fcn.spec]p4:674// If the definition of a function appears in a translation unit before its675// first declaration as inline, the program is ill-formed.676Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;677Diag(Def->getLocation(), diag::note_previous_definition);678Invalid = true;679}680681// C++17 [temp.deduct.guide]p3:682// Two deduction guide declarations in the same translation unit683// for the same class template shall not have equivalent684// parameter-declaration-clauses.685if (isa<CXXDeductionGuideDecl>(New) &&686!New->isFunctionTemplateSpecialization() && isVisible(Old)) {687Diag(New->getLocation(), diag::err_deduction_guide_redeclared);688Diag(Old->getLocation(), diag::note_previous_declaration);689}690691// C++11 [dcl.fct.default]p4: If a friend declaration specifies a default692// argument expression, that declaration shall be a definition and shall be693// the only declaration of the function or function template in the694// translation unit.695if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&696functionDeclHasDefaultArgument(Old)) {697Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);698Diag(Old->getLocation(), diag::note_previous_declaration);699Invalid = true;700}701702// C++11 [temp.friend]p4 (DR329):703// When a function is defined in a friend function declaration in a class704// template, the function is instantiated when the function is odr-used.705// The same restrictions on multiple declarations and definitions that706// apply to non-template function declarations and definitions also apply707// to these implicit definitions.708const FunctionDecl *OldDefinition = nullptr;709if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&710Old->isDefined(OldDefinition, true))711CheckForFunctionRedefinition(New, OldDefinition);712713return Invalid;714}715716void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {717Diag(Loc, getLangOpts().CPlusPlus26718? diag::warn_cxx23_placeholder_var_definition719: diag::ext_placeholder_var_definition);720}721722NamedDecl *723Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,724MultiTemplateParamsArg TemplateParamLists) {725assert(D.isDecompositionDeclarator());726const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();727728// The syntax only allows a decomposition declarator as a simple-declaration,729// a for-range-declaration, or a condition in Clang, but we parse it in more730// cases than that.731if (!D.mayHaveDecompositionDeclarator()) {732Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)733<< Decomp.getSourceRange();734return nullptr;735}736737if (!TemplateParamLists.empty()) {738// FIXME: There's no rule against this, but there are also no rules that739// would actually make it usable, so we reject it for now.740Diag(TemplateParamLists.front()->getTemplateLoc(),741diag::err_decomp_decl_template);742return nullptr;743}744745Diag(Decomp.getLSquareLoc(),746!getLangOpts().CPlusPlus17747? diag::ext_decomp_decl748: D.getContext() == DeclaratorContext::Condition749? diag::ext_decomp_decl_cond750: diag::warn_cxx14_compat_decomp_decl)751<< Decomp.getSourceRange();752753// The semantic context is always just the current context.754DeclContext *const DC = CurContext;755756// C++17 [dcl.dcl]/8:757// The decl-specifier-seq shall contain only the type-specifier auto758// and cv-qualifiers.759// C++20 [dcl.dcl]/8:760// If decl-specifier-seq contains any decl-specifier other than static,761// thread_local, auto, or cv-qualifiers, the program is ill-formed.762// C++23 [dcl.pre]/6:763// Each decl-specifier in the decl-specifier-seq shall be static,764// thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.765auto &DS = D.getDeclSpec();766{767// Note: While constrained-auto needs to be checked, we do so separately so768// we can emit a better diagnostic.769SmallVector<StringRef, 8> BadSpecifiers;770SmallVector<SourceLocation, 8> BadSpecifierLocs;771SmallVector<StringRef, 8> CPlusPlus20Specifiers;772SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;773if (auto SCS = DS.getStorageClassSpec()) {774if (SCS == DeclSpec::SCS_static) {775CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));776CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());777} else {778BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));779BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());780}781}782if (auto TSCS = DS.getThreadStorageClassSpec()) {783CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));784CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());785}786if (DS.hasConstexprSpecifier()) {787BadSpecifiers.push_back(788DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));789BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());790}791if (DS.isInlineSpecified()) {792BadSpecifiers.push_back("inline");793BadSpecifierLocs.push_back(DS.getInlineSpecLoc());794}795796if (!BadSpecifiers.empty()) {797auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);798Err << (int)BadSpecifiers.size()799<< llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");800// Don't add FixItHints to remove the specifiers; we do still respect801// them when building the underlying variable.802for (auto Loc : BadSpecifierLocs)803Err << SourceRange(Loc, Loc);804} else if (!CPlusPlus20Specifiers.empty()) {805auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),806getLangOpts().CPlusPlus20807? diag::warn_cxx17_compat_decomp_decl_spec808: diag::ext_decomp_decl_spec);809Warn << (int)CPlusPlus20Specifiers.size()810<< llvm::join(CPlusPlus20Specifiers.begin(),811CPlusPlus20Specifiers.end(), " ");812for (auto Loc : CPlusPlus20SpecifierLocs)813Warn << SourceRange(Loc, Loc);814}815// We can't recover from it being declared as a typedef.816if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)817return nullptr;818}819820// C++2a [dcl.struct.bind]p1:821// A cv that includes volatile is deprecated822if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&823getLangOpts().CPlusPlus20)824Diag(DS.getVolatileSpecLoc(),825diag::warn_deprecated_volatile_structured_binding);826827TypeSourceInfo *TInfo = GetTypeForDeclarator(D);828QualType R = TInfo->getType();829830if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,831UPPC_DeclarationType))832D.setInvalidType();833834// The syntax only allows a single ref-qualifier prior to the decomposition835// declarator. No other declarator chunks are permitted. Also check the type836// specifier here.837if (DS.getTypeSpecType() != DeclSpec::TST_auto ||838D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||839(D.getNumTypeObjects() == 1 &&840D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {841Diag(Decomp.getLSquareLoc(),842(D.hasGroupingParens() ||843(D.getNumTypeObjects() &&844D.getTypeObject(0).Kind == DeclaratorChunk::Paren))845? diag::err_decomp_decl_parens846: diag::err_decomp_decl_type)847<< R;848849// In most cases, there's no actual problem with an explicitly-specified850// type, but a function type won't work here, and ActOnVariableDeclarator851// shouldn't be called for such a type.852if (R->isFunctionType())853D.setInvalidType();854}855856// Constrained auto is prohibited by [decl.pre]p6, so check that here.857if (DS.isConstrainedAuto()) {858TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();859assert(TemplRep->Kind == TNK_Concept_template &&860"No other template kind should be possible for a constrained auto");861862SourceRange TemplRange{TemplRep->TemplateNameLoc,863TemplRep->RAngleLoc.isValid()864? TemplRep->RAngleLoc865: TemplRep->TemplateNameLoc};866Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)867<< TemplRange << FixItHint::CreateRemoval(TemplRange);868}869870// Build the BindingDecls.871SmallVector<BindingDecl*, 8> Bindings;872873// Build the BindingDecls.874for (auto &B : D.getDecompositionDeclarator().bindings()) {875// Check for name conflicts.876DeclarationNameInfo NameInfo(B.Name, B.NameLoc);877IdentifierInfo *VarName = B.Name;878assert(VarName && "Cannot have an unnamed binding declaration");879880LookupResult Previous(*this, NameInfo, LookupOrdinaryName,881RedeclarationKind::ForVisibleRedeclaration);882LookupName(Previous, S,883/*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());884885// It's not permitted to shadow a template parameter name.886if (Previous.isSingleResult() &&887Previous.getFoundDecl()->isTemplateParameter()) {888DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),889Previous.getFoundDecl());890Previous.clear();891}892893auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);894895ProcessDeclAttributeList(S, BD, *B.Attrs);896897// Find the shadowed declaration before filtering for scope.898NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()899? getShadowedDeclaration(BD, Previous)900: nullptr;901902bool ConsiderLinkage = DC->isFunctionOrMethod() &&903DS.getStorageClassSpec() == DeclSpec::SCS_extern;904FilterLookupForScope(Previous, DC, S, ConsiderLinkage,905/*AllowInlineNamespace*/false);906907bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&908DC->isFunctionOrMethod() && VarName->isPlaceholder();909if (!Previous.empty()) {910if (IsPlaceholder) {911bool sameDC = (Previous.end() - 1)912->getDeclContext()913->getRedeclContext()914->Equals(DC->getRedeclContext());915if (sameDC &&916isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {917Previous.clear();918DiagPlaceholderVariableDefinition(B.NameLoc);919}920} else {921auto *Old = Previous.getRepresentativeDecl();922Diag(B.NameLoc, diag::err_redefinition) << B.Name;923Diag(Old->getLocation(), diag::note_previous_definition);924}925} else if (ShadowedDecl && !D.isRedeclaration()) {926CheckShadow(BD, ShadowedDecl, Previous);927}928PushOnScopeChains(BD, S, true);929Bindings.push_back(BD);930ParsingInitForAutoVars.insert(BD);931}932933// There are no prior lookup results for the variable itself, because it934// is unnamed.935DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,936Decomp.getLSquareLoc());937LookupResult Previous(*this, NameInfo, LookupOrdinaryName,938RedeclarationKind::ForVisibleRedeclaration);939940// Build the variable that holds the non-decomposed object.941bool AddToScope = true;942NamedDecl *New =943ActOnVariableDeclarator(S, D, DC, TInfo, Previous,944MultiTemplateParamsArg(), AddToScope, Bindings);945if (AddToScope) {946S->AddDecl(New);947CurContext->addHiddenDecl(New);948}949950if (OpenMP().isInOpenMPDeclareTargetContext())951OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);952953return New;954}955956static bool checkSimpleDecomposition(957Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,958QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,959llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {960if ((int64_t)Bindings.size() != NumElems) {961S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)962<< DecompType << (unsigned)Bindings.size()963<< (unsigned)NumElems.getLimitedValue(UINT_MAX)964<< toString(NumElems, 10) << (NumElems < Bindings.size());965return true;966}967968unsigned I = 0;969for (auto *B : Bindings) {970SourceLocation Loc = B->getLocation();971ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);972if (E.isInvalid())973return true;974E = GetInit(Loc, E.get(), I++);975if (E.isInvalid())976return true;977B->setBinding(ElemType, E.get());978}979980return false;981}982983static bool checkArrayLikeDecomposition(Sema &S,984ArrayRef<BindingDecl *> Bindings,985ValueDecl *Src, QualType DecompType,986const llvm::APSInt &NumElems,987QualType ElemType) {988return checkSimpleDecomposition(989S, Bindings, Src, DecompType, NumElems, ElemType,990[&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {991ExprResult E = S.ActOnIntegerConstant(Loc, I);992if (E.isInvalid())993return ExprError();994return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);995});996}997998static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,999ValueDecl *Src, QualType DecompType,1000const ConstantArrayType *CAT) {1001return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,1002llvm::APSInt(CAT->getSize()),1003CAT->getElementType());1004}10051006static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,1007ValueDecl *Src, QualType DecompType,1008const VectorType *VT) {1009return checkArrayLikeDecomposition(1010S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),1011S.Context.getQualifiedType(VT->getElementType(),1012DecompType.getQualifiers()));1013}10141015static bool checkComplexDecomposition(Sema &S,1016ArrayRef<BindingDecl *> Bindings,1017ValueDecl *Src, QualType DecompType,1018const ComplexType *CT) {1019return checkSimpleDecomposition(1020S, Bindings, Src, DecompType, llvm::APSInt::get(2),1021S.Context.getQualifiedType(CT->getElementType(),1022DecompType.getQualifiers()),1023[&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {1024return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);1025});1026}10271028static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,1029TemplateArgumentListInfo &Args,1030const TemplateParameterList *Params) {1031SmallString<128> SS;1032llvm::raw_svector_ostream OS(SS);1033bool First = true;1034unsigned I = 0;1035for (auto &Arg : Args.arguments()) {1036if (!First)1037OS << ", ";1038Arg.getArgument().print(PrintingPolicy, OS,1039TemplateParameterList::shouldIncludeTypeForArgument(1040PrintingPolicy, Params, I));1041First = false;1042I++;1043}1044return std::string(OS.str());1045}10461047static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,1048SourceLocation Loc, StringRef Trait,1049TemplateArgumentListInfo &Args,1050unsigned DiagID) {1051auto DiagnoseMissing = [&] {1052if (DiagID)1053S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),1054Args, /*Params*/ nullptr);1055return true;1056};10571058// FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.1059NamespaceDecl *Std = S.getStdNamespace();1060if (!Std)1061return DiagnoseMissing();10621063// Look up the trait itself, within namespace std. We can diagnose various1064// problems with this lookup even if we've been asked to not diagnose a1065// missing specialization, because this can only fail if the user has been1066// declaring their own names in namespace std or we don't support the1067// standard library implementation in use.1068LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),1069Loc, Sema::LookupOrdinaryName);1070if (!S.LookupQualifiedName(Result, Std))1071return DiagnoseMissing();1072if (Result.isAmbiguous())1073return true;10741075ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();1076if (!TraitTD) {1077Result.suppressDiagnostics();1078NamedDecl *Found = *Result.begin();1079S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;1080S.Diag(Found->getLocation(), diag::note_declared_at);1081return true;1082}10831084// Build the template-id.1085QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);1086if (TraitTy.isNull())1087return true;1088if (!S.isCompleteType(Loc, TraitTy)) {1089if (DiagID)1090S.RequireCompleteType(1091Loc, TraitTy, DiagID,1092printTemplateArgs(S.Context.getPrintingPolicy(), Args,1093TraitTD->getTemplateParameters()));1094return true;1095}10961097CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();1098assert(RD && "specialization of class template is not a class?");10991100// Look up the member of the trait type.1101S.LookupQualifiedName(TraitMemberLookup, RD);1102return TraitMemberLookup.isAmbiguous();1103}11041105static TemplateArgumentLoc1106getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,1107uint64_t I) {1108TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);1109return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);1110}11111112static TemplateArgumentLoc1113getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {1114return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);1115}11161117namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }11181119static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,1120llvm::APSInt &Size) {1121EnterExpressionEvaluationContext ContextRAII(1122S, Sema::ExpressionEvaluationContext::ConstantEvaluated);11231124DeclarationName Value = S.PP.getIdentifierInfo("value");1125LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);11261127// Form template argument list for tuple_size<T>.1128TemplateArgumentListInfo Args(Loc, Loc);1129Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));11301131// If there's no tuple_size specialization or the lookup of 'value' is empty,1132// it's not tuple-like.1133if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||1134R.empty())1135return IsTupleLike::NotTupleLike;11361137// If we get this far, we've committed to the tuple interpretation, but1138// we can still fail if there actually isn't a usable ::value.11391140struct ICEDiagnoser : Sema::VerifyICEDiagnoser {1141LookupResult &R;1142TemplateArgumentListInfo &Args;1143ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)1144: R(R), Args(Args) {}1145Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,1146SourceLocation Loc) override {1147return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)1148<< printTemplateArgs(S.Context.getPrintingPolicy(), Args,1149/*Params*/ nullptr);1150}1151} Diagnoser(R, Args);11521153ExprResult E =1154S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);1155if (E.isInvalid())1156return IsTupleLike::Error;11571158E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);1159if (E.isInvalid())1160return IsTupleLike::Error;11611162return IsTupleLike::TupleLike;1163}11641165/// \return std::tuple_element<I, T>::type.1166static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,1167unsigned I, QualType T) {1168// Form template argument list for tuple_element<I, T>.1169TemplateArgumentListInfo Args(Loc, Loc);1170Args.addArgument(1171getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));1172Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));11731174DeclarationName TypeDN = S.PP.getIdentifierInfo("type");1175LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);1176if (lookupStdTypeTraitMember(1177S, R, Loc, "tuple_element", Args,1178diag::err_decomp_decl_std_tuple_element_not_specialized))1179return QualType();11801181auto *TD = R.getAsSingle<TypeDecl>();1182if (!TD) {1183R.suppressDiagnostics();1184S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)1185<< printTemplateArgs(S.Context.getPrintingPolicy(), Args,1186/*Params*/ nullptr);1187if (!R.empty())1188S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);1189return QualType();1190}11911192return S.Context.getTypeDeclType(TD);1193}11941195namespace {1196struct InitializingBinding {1197Sema &S;1198InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {1199Sema::CodeSynthesisContext Ctx;1200Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;1201Ctx.PointOfInstantiation = BD->getLocation();1202Ctx.Entity = BD;1203S.pushCodeSynthesisContext(Ctx);1204}1205~InitializingBinding() {1206S.popCodeSynthesisContext();1207}1208};1209}12101211static bool checkTupleLikeDecomposition(Sema &S,1212ArrayRef<BindingDecl *> Bindings,1213VarDecl *Src, QualType DecompType,1214const llvm::APSInt &TupleSize) {1215if ((int64_t)Bindings.size() != TupleSize) {1216S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)1217<< DecompType << (unsigned)Bindings.size()1218<< (unsigned)TupleSize.getLimitedValue(UINT_MAX)1219<< toString(TupleSize, 10) << (TupleSize < Bindings.size());1220return true;1221}12221223if (Bindings.empty())1224return false;12251226DeclarationName GetDN = S.PP.getIdentifierInfo("get");12271228// [dcl.decomp]p3:1229// The unqualified-id get is looked up in the scope of E by class member1230// access lookup ...1231LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);1232bool UseMemberGet = false;1233if (S.isCompleteType(Src->getLocation(), DecompType)) {1234if (auto *RD = DecompType->getAsCXXRecordDecl())1235S.LookupQualifiedName(MemberGet, RD);1236if (MemberGet.isAmbiguous())1237return true;1238// ... and if that finds at least one declaration that is a function1239// template whose first template parameter is a non-type parameter ...1240for (NamedDecl *D : MemberGet) {1241if (FunctionTemplateDecl *FTD =1242dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {1243TemplateParameterList *TPL = FTD->getTemplateParameters();1244if (TPL->size() != 0 &&1245isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {1246// ... the initializer is e.get<i>().1247UseMemberGet = true;1248break;1249}1250}1251}1252}12531254unsigned I = 0;1255for (auto *B : Bindings) {1256InitializingBinding InitContext(S, B);1257SourceLocation Loc = B->getLocation();12581259ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);1260if (E.isInvalid())1261return true;12621263// e is an lvalue if the type of the entity is an lvalue reference and1264// an xvalue otherwise1265if (!Src->getType()->isLValueReferenceType())1266E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,1267E.get(), nullptr, VK_XValue,1268FPOptionsOverride());12691270TemplateArgumentListInfo Args(Loc, Loc);1271Args.addArgument(1272getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));12731274if (UseMemberGet) {1275// if [lookup of member get] finds at least one declaration, the1276// initializer is e.get<i-1>().1277E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,1278CXXScopeSpec(), SourceLocation(), nullptr,1279MemberGet, &Args, nullptr);1280if (E.isInvalid())1281return true;12821283E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);1284} else {1285// Otherwise, the initializer is get<i-1>(e), where get is looked up1286// in the associated namespaces.1287Expr *Get = UnresolvedLookupExpr::Create(1288S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),1289DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,1290UnresolvedSetIterator(), UnresolvedSetIterator(),1291/*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);12921293Expr *Arg = E.get();1294E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);1295}1296if (E.isInvalid())1297return true;1298Expr *Init = E.get();12991300// Given the type T designated by std::tuple_element<i - 1, E>::type,1301QualType T = getTupleLikeElementType(S, Loc, I, DecompType);1302if (T.isNull())1303return true;13041305// each vi is a variable of type "reference to T" initialized with the1306// initializer, where the reference is an lvalue reference if the1307// initializer is an lvalue and an rvalue reference otherwise1308QualType RefType =1309S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());1310if (RefType.isNull())1311return true;1312auto *RefVD = VarDecl::Create(1313S.Context, Src->getDeclContext(), Loc, Loc,1314B->getDeclName().getAsIdentifierInfo(), RefType,1315S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());1316RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());1317RefVD->setTSCSpec(Src->getTSCSpec());1318RefVD->setImplicit();1319if (Src->isInlineSpecified())1320RefVD->setInlineSpecified();1321RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);13221323InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);1324InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);1325InitializationSequence Seq(S, Entity, Kind, Init);1326E = Seq.Perform(S, Entity, Kind, Init);1327if (E.isInvalid())1328return true;1329E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);1330if (E.isInvalid())1331return true;1332RefVD->setInit(E.get());1333S.CheckCompleteVariableDeclaration(RefVD);13341335E = S.BuildDeclarationNameExpr(CXXScopeSpec(),1336DeclarationNameInfo(B->getDeclName(), Loc),1337RefVD);1338if (E.isInvalid())1339return true;13401341B->setBinding(T, E.get());1342I++;1343}13441345return false;1346}13471348/// Find the base class to decompose in a built-in decomposition of a class type.1349/// This base class search is, unfortunately, not quite like any other that we1350/// perform anywhere else in C++.1351static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,1352const CXXRecordDecl *RD,1353CXXCastPath &BasePath) {1354auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,1355CXXBasePath &Path) {1356return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();1357};13581359const CXXRecordDecl *ClassWithFields = nullptr;1360AccessSpecifier AS = AS_public;1361if (RD->hasDirectFields())1362// [dcl.decomp]p4:1363// Otherwise, all of E's non-static data members shall be public direct1364// members of E ...1365ClassWithFields = RD;1366else {1367// ... or of ...1368CXXBasePaths Paths;1369Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));1370if (!RD->lookupInBases(BaseHasFields, Paths)) {1371// If no classes have fields, just decompose RD itself. (This will work1372// if and only if zero bindings were provided.)1373return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);1374}13751376CXXBasePath *BestPath = nullptr;1377for (auto &P : Paths) {1378if (!BestPath)1379BestPath = &P;1380else if (!S.Context.hasSameType(P.back().Base->getType(),1381BestPath->back().Base->getType())) {1382// ... the same ...1383S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)1384<< false << RD << BestPath->back().Base->getType()1385<< P.back().Base->getType();1386return DeclAccessPair();1387} else if (P.Access < BestPath->Access) {1388BestPath = &P;1389}1390}13911392// ... unambiguous ...1393QualType BaseType = BestPath->back().Base->getType();1394if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {1395S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)1396<< RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);1397return DeclAccessPair();1398}13991400// ... [accessible, implied by other rules] base class of E.1401S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),1402*BestPath, diag::err_decomp_decl_inaccessible_base);1403AS = BestPath->Access;14041405ClassWithFields = BaseType->getAsCXXRecordDecl();1406S.BuildBasePathArray(Paths, BasePath);1407}14081409// The above search did not check whether the selected class itself has base1410// classes with fields, so check that now.1411CXXBasePaths Paths;1412if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {1413S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)1414<< (ClassWithFields == RD) << RD << ClassWithFields1415<< Paths.front().back().Base->getType();1416return DeclAccessPair();1417}14181419return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);1420}14211422static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,1423ValueDecl *Src, QualType DecompType,1424const CXXRecordDecl *OrigRD) {1425if (S.RequireCompleteType(Src->getLocation(), DecompType,1426diag::err_incomplete_type))1427return true;14281429CXXCastPath BasePath;1430DeclAccessPair BasePair =1431findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);1432const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());1433if (!RD)1434return true;1435QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),1436DecompType.getQualifiers());14371438auto DiagnoseBadNumberOfBindings = [&]() -> bool {1439unsigned NumFields = llvm::count_if(1440RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });1441assert(Bindings.size() != NumFields);1442S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)1443<< DecompType << (unsigned)Bindings.size() << NumFields << NumFields1444<< (NumFields < Bindings.size());1445return true;1446};14471448// all of E's non-static data members shall be [...] well-formed1449// when named as e.name in the context of the structured binding,1450// E shall not have an anonymous union member, ...1451unsigned I = 0;1452for (auto *FD : RD->fields()) {1453if (FD->isUnnamedBitField())1454continue;14551456// All the non-static data members are required to be nameable, so they1457// must all have names.1458if (!FD->getDeclName()) {1459if (RD->isLambda()) {1460S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);1461S.Diag(RD->getLocation(), diag::note_lambda_decl);1462return true;1463}14641465if (FD->isAnonymousStructOrUnion()) {1466S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)1467<< DecompType << FD->getType()->isUnionType();1468S.Diag(FD->getLocation(), diag::note_declared_at);1469return true;1470}14711472// FIXME: Are there any other ways we could have an anonymous member?1473}14741475// We have a real field to bind.1476if (I >= Bindings.size())1477return DiagnoseBadNumberOfBindings();1478auto *B = Bindings[I++];1479SourceLocation Loc = B->getLocation();14801481// The field must be accessible in the context of the structured binding.1482// We already checked that the base class is accessible.1483// FIXME: Add 'const' to AccessedEntity's classes so we can remove the1484// const_cast here.1485S.CheckStructuredBindingMemberAccess(1486Loc, const_cast<CXXRecordDecl *>(OrigRD),1487DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(1488BasePair.getAccess(), FD->getAccess())));14891490// Initialize the binding to Src.FD.1491ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);1492if (E.isInvalid())1493return true;1494E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,1495VK_LValue, &BasePath);1496if (E.isInvalid())1497return true;1498E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,1499CXXScopeSpec(), FD,1500DeclAccessPair::make(FD, FD->getAccess()),1501DeclarationNameInfo(FD->getDeclName(), Loc));1502if (E.isInvalid())1503return true;15041505// If the type of the member is T, the referenced type is cv T, where cv is1506// the cv-qualification of the decomposition expression.1507//1508// FIXME: We resolve a defect here: if the field is mutable, we do not add1509// 'const' to the type of the field.1510Qualifiers Q = DecompType.getQualifiers();1511if (FD->isMutable())1512Q.removeConst();1513B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());1514}15151516if (I != Bindings.size())1517return DiagnoseBadNumberOfBindings();15181519return false;1520}15211522void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {1523QualType DecompType = DD->getType();15241525// If the type of the decomposition is dependent, then so is the type of1526// each binding.1527if (DecompType->isDependentType()) {1528for (auto *B : DD->bindings())1529B->setType(Context.DependentTy);1530return;1531}15321533DecompType = DecompType.getNonReferenceType();1534ArrayRef<BindingDecl*> Bindings = DD->bindings();15351536// C++1z [dcl.decomp]/2:1537// If E is an array type [...]1538// As an extension, we also support decomposition of built-in complex and1539// vector types.1540if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {1541if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))1542DD->setInvalidDecl();1543return;1544}1545if (auto *VT = DecompType->getAs<VectorType>()) {1546if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))1547DD->setInvalidDecl();1548return;1549}1550if (auto *CT = DecompType->getAs<ComplexType>()) {1551if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))1552DD->setInvalidDecl();1553return;1554}15551556// C++1z [dcl.decomp]/3:1557// if the expression std::tuple_size<E>::value is a well-formed integral1558// constant expression, [...]1559llvm::APSInt TupleSize(32);1560switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {1561case IsTupleLike::Error:1562DD->setInvalidDecl();1563return;15641565case IsTupleLike::TupleLike:1566if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))1567DD->setInvalidDecl();1568return;15691570case IsTupleLike::NotTupleLike:1571break;1572}15731574// C++1z [dcl.dcl]/8:1575// [E shall be of array or non-union class type]1576CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();1577if (!RD || RD->isUnion()) {1578Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)1579<< DD << !RD << DecompType;1580DD->setInvalidDecl();1581return;1582}15831584// C++1z [dcl.decomp]/4:1585// all of E's non-static data members shall be [...] direct members of1586// E or of the same unambiguous public base class of E, ...1587if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))1588DD->setInvalidDecl();1589}15901591void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {1592// Shortcut if exceptions are disabled.1593if (!getLangOpts().CXXExceptions)1594return;15951596assert(Context.hasSameType(New->getType(), Old->getType()) &&1597"Should only be called if types are otherwise the same.");15981599QualType NewType = New->getType();1600QualType OldType = Old->getType();16011602// We're only interested in pointers and references to functions, as well1603// as pointers to member functions.1604if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {1605NewType = R->getPointeeType();1606OldType = OldType->castAs<ReferenceType>()->getPointeeType();1607} else if (const PointerType *P = NewType->getAs<PointerType>()) {1608NewType = P->getPointeeType();1609OldType = OldType->castAs<PointerType>()->getPointeeType();1610} else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {1611NewType = M->getPointeeType();1612OldType = OldType->castAs<MemberPointerType>()->getPointeeType();1613}16141615if (!NewType->isFunctionProtoType())1616return;16171618// There's lots of special cases for functions. For function pointers, system1619// libraries are hopefully not as broken so that we don't need these1620// workarounds.1621if (CheckEquivalentExceptionSpec(1622OldType->getAs<FunctionProtoType>(), Old->getLocation(),1623NewType->getAs<FunctionProtoType>(), New->getLocation())) {1624New->setInvalidDecl();1625}1626}16271628/// CheckCXXDefaultArguments - Verify that the default arguments for a1629/// function declaration are well-formed according to C++1630/// [dcl.fct.default].1631void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {1632// This checking doesn't make sense for explicit specializations; their1633// default arguments are determined by the declaration we're specializing,1634// not by FD.1635if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)1636return;1637if (auto *FTD = FD->getDescribedFunctionTemplate())1638if (FTD->isMemberSpecialization())1639return;16401641unsigned NumParams = FD->getNumParams();1642unsigned ParamIdx = 0;16431644// Find first parameter with a default argument1645for (; ParamIdx < NumParams; ++ParamIdx) {1646ParmVarDecl *Param = FD->getParamDecl(ParamIdx);1647if (Param->hasDefaultArg())1648break;1649}16501651// C++20 [dcl.fct.default]p4:1652// In a given function declaration, each parameter subsequent to a parameter1653// with a default argument shall have a default argument supplied in this or1654// a previous declaration, unless the parameter was expanded from a1655// parameter pack, or shall be a function parameter pack.1656for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {1657ParmVarDecl *Param = FD->getParamDecl(ParamIdx);1658if (Param->hasDefaultArg() || Param->isParameterPack() ||1659(CurrentInstantiationScope &&1660CurrentInstantiationScope->isLocalPackExpansion(Param)))1661continue;1662if (Param->isInvalidDecl())1663/* We already complained about this parameter. */;1664else if (Param->getIdentifier())1665Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)1666<< Param->getIdentifier();1667else1668Diag(Param->getLocation(), diag::err_param_default_argument_missing);1669}1670}16711672/// Check that the given type is a literal type. Issue a diagnostic if not,1673/// if Kind is Diagnose.1674/// \return \c true if a problem has been found (and optionally diagnosed).1675template <typename... Ts>1676static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,1677SourceLocation Loc, QualType T, unsigned DiagID,1678Ts &&...DiagArgs) {1679if (T->isDependentType())1680return false;16811682switch (Kind) {1683case Sema::CheckConstexprKind::Diagnose:1684return SemaRef.RequireLiteralType(Loc, T, DiagID,1685std::forward<Ts>(DiagArgs)...);16861687case Sema::CheckConstexprKind::CheckValid:1688return !T->isLiteralType(SemaRef.Context);1689}16901691llvm_unreachable("unknown CheckConstexprKind");1692}16931694/// Determine whether a destructor cannot be constexpr due to1695static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,1696const CXXDestructorDecl *DD,1697Sema::CheckConstexprKind Kind) {1698assert(!SemaRef.getLangOpts().CPlusPlus23 &&1699"this check is obsolete for C++23");1700auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {1701const CXXRecordDecl *RD =1702T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();1703if (!RD || RD->hasConstexprDestructor())1704return true;17051706if (Kind == Sema::CheckConstexprKind::Diagnose) {1707SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)1708<< static_cast<int>(DD->getConstexprKind()) << !FD1709<< (FD ? FD->getDeclName() : DeclarationName()) << T;1710SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)1711<< !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;1712}1713return false;1714};17151716const CXXRecordDecl *RD = DD->getParent();1717for (const CXXBaseSpecifier &B : RD->bases())1718if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))1719return false;1720for (const FieldDecl *FD : RD->fields())1721if (!Check(FD->getLocation(), FD->getType(), FD))1722return false;1723return true;1724}17251726/// Check whether a function's parameter types are all literal types. If so,1727/// return true. If not, produce a suitable diagnostic and return false.1728static bool CheckConstexprParameterTypes(Sema &SemaRef,1729const FunctionDecl *FD,1730Sema::CheckConstexprKind Kind) {1731assert(!SemaRef.getLangOpts().CPlusPlus23 &&1732"this check is obsolete for C++23");1733unsigned ArgIndex = 0;1734const auto *FT = FD->getType()->castAs<FunctionProtoType>();1735for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),1736e = FT->param_type_end();1737i != e; ++i, ++ArgIndex) {1738const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);1739assert(PD && "null in a parameter list");1740SourceLocation ParamLoc = PD->getLocation();1741if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,1742diag::err_constexpr_non_literal_param, ArgIndex + 1,1743PD->getSourceRange(), isa<CXXConstructorDecl>(FD),1744FD->isConsteval()))1745return false;1746}1747return true;1748}17491750/// Check whether a function's return type is a literal type. If so, return1751/// true. If not, produce a suitable diagnostic and return false.1752static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,1753Sema::CheckConstexprKind Kind) {1754assert(!SemaRef.getLangOpts().CPlusPlus23 &&1755"this check is obsolete for C++23");1756if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),1757diag::err_constexpr_non_literal_return,1758FD->isConsteval()))1759return false;1760return true;1761}17621763/// Get diagnostic %select index for tag kind for1764/// record diagnostic message.1765/// WARNING: Indexes apply to particular diagnostics only!1766///1767/// \returns diagnostic %select index.1768static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {1769switch (Tag) {1770case TagTypeKind::Struct:1771return 0;1772case TagTypeKind::Interface:1773return 1;1774case TagTypeKind::Class:1775return 2;1776default: llvm_unreachable("Invalid tag kind for record diagnostic!");1777}1778}17791780static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,1781Stmt *Body,1782Sema::CheckConstexprKind Kind);1783static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);17841785bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,1786CheckConstexprKind Kind) {1787const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);1788if (MD && MD->isInstance()) {1789// C++11 [dcl.constexpr]p4:1790// The definition of a constexpr constructor shall satisfy the following1791// constraints:1792// - the class shall not have any virtual base classes;1793//1794// FIXME: This only applies to constructors and destructors, not arbitrary1795// member functions.1796const CXXRecordDecl *RD = MD->getParent();1797if (RD->getNumVBases()) {1798if (Kind == CheckConstexprKind::CheckValid)1799return false;18001801Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)1802<< isa<CXXConstructorDecl>(NewFD)1803<< getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();1804for (const auto &I : RD->vbases())1805Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)1806<< I.getSourceRange();1807return false;1808}1809}18101811if (!isa<CXXConstructorDecl>(NewFD)) {1812// C++11 [dcl.constexpr]p3:1813// The definition of a constexpr function shall satisfy the following1814// constraints:1815// - it shall not be virtual; (removed in C++20)1816const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);1817if (Method && Method->isVirtual()) {1818if (getLangOpts().CPlusPlus20) {1819if (Kind == CheckConstexprKind::Diagnose)1820Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);1821} else {1822if (Kind == CheckConstexprKind::CheckValid)1823return false;18241825Method = Method->getCanonicalDecl();1826Diag(Method->getLocation(), diag::err_constexpr_virtual);18271828// If it's not obvious why this function is virtual, find an overridden1829// function which uses the 'virtual' keyword.1830const CXXMethodDecl *WrittenVirtual = Method;1831while (!WrittenVirtual->isVirtualAsWritten())1832WrittenVirtual = *WrittenVirtual->begin_overridden_methods();1833if (WrittenVirtual != Method)1834Diag(WrittenVirtual->getLocation(),1835diag::note_overridden_virtual_function);1836return false;1837}1838}18391840// - its return type shall be a literal type; (removed in C++23)1841if (!getLangOpts().CPlusPlus23 &&1842!CheckConstexprReturnType(*this, NewFD, Kind))1843return false;1844}18451846if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {1847// A destructor can be constexpr only if the defaulted destructor could be;1848// we don't need to check the members and bases if we already know they all1849// have constexpr destructors. (removed in C++23)1850if (!getLangOpts().CPlusPlus23 &&1851!Dtor->getParent()->defaultedDestructorIsConstexpr()) {1852if (Kind == CheckConstexprKind::CheckValid)1853return false;1854if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))1855return false;1856}1857}18581859// - each of its parameter types shall be a literal type; (removed in C++23)1860if (!getLangOpts().CPlusPlus23 &&1861!CheckConstexprParameterTypes(*this, NewFD, Kind))1862return false;18631864Stmt *Body = NewFD->getBody();1865assert(Body &&1866"CheckConstexprFunctionDefinition called on function with no body");1867return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);1868}18691870/// Check the given declaration statement is legal within a constexpr function1871/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.1872///1873/// \return true if the body is OK (maybe only as an extension), false if we1874/// have diagnosed a problem.1875static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,1876DeclStmt *DS, SourceLocation &Cxx1yLoc,1877Sema::CheckConstexprKind Kind) {1878// C++11 [dcl.constexpr]p3 and p4:1879// The definition of a constexpr function(p3) or constructor(p4) [...] shall1880// contain only1881for (const auto *DclIt : DS->decls()) {1882switch (DclIt->getKind()) {1883case Decl::StaticAssert:1884case Decl::Using:1885case Decl::UsingShadow:1886case Decl::UsingDirective:1887case Decl::UnresolvedUsingTypename:1888case Decl::UnresolvedUsingValue:1889case Decl::UsingEnum:1890// - static_assert-declarations1891// - using-declarations,1892// - using-directives,1893// - using-enum-declaration1894continue;18951896case Decl::Typedef:1897case Decl::TypeAlias: {1898// - typedef declarations and alias-declarations that do not define1899// classes or enumerations,1900const auto *TN = cast<TypedefNameDecl>(DclIt);1901if (TN->getUnderlyingType()->isVariablyModifiedType()) {1902// Don't allow variably-modified types in constexpr functions.1903if (Kind == Sema::CheckConstexprKind::Diagnose) {1904TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();1905SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)1906<< TL.getSourceRange() << TL.getType()1907<< isa<CXXConstructorDecl>(Dcl);1908}1909return false;1910}1911continue;1912}19131914case Decl::Enum:1915case Decl::CXXRecord:1916// C++1y allows types to be defined, not just declared.1917if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {1918if (Kind == Sema::CheckConstexprKind::Diagnose) {1919SemaRef.Diag(DS->getBeginLoc(),1920SemaRef.getLangOpts().CPlusPlus141921? diag::warn_cxx11_compat_constexpr_type_definition1922: diag::ext_constexpr_type_definition)1923<< isa<CXXConstructorDecl>(Dcl);1924} else if (!SemaRef.getLangOpts().CPlusPlus14) {1925return false;1926}1927}1928continue;19291930case Decl::EnumConstant:1931case Decl::IndirectField:1932case Decl::ParmVar:1933// These can only appear with other declarations which are banned in1934// C++11 and permitted in C++1y, so ignore them.1935continue;19361937case Decl::Var:1938case Decl::Decomposition: {1939// C++1y [dcl.constexpr]p3 allows anything except:1940// a definition of a variable of non-literal type or of static or1941// thread storage duration or [before C++2a] for which no1942// initialization is performed.1943const auto *VD = cast<VarDecl>(DclIt);1944if (VD->isThisDeclarationADefinition()) {1945if (VD->isStaticLocal()) {1946if (Kind == Sema::CheckConstexprKind::Diagnose) {1947SemaRef.Diag(VD->getLocation(),1948SemaRef.getLangOpts().CPlusPlus231949? diag::warn_cxx20_compat_constexpr_var1950: diag::ext_constexpr_static_var)1951<< isa<CXXConstructorDecl>(Dcl)1952<< (VD->getTLSKind() == VarDecl::TLS_Dynamic);1953} else if (!SemaRef.getLangOpts().CPlusPlus23) {1954return false;1955}1956}1957if (SemaRef.LangOpts.CPlusPlus23) {1958CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),1959diag::warn_cxx20_compat_constexpr_var,1960isa<CXXConstructorDecl>(Dcl),1961/*variable of non-literal type*/ 2);1962} else if (CheckLiteralType(1963SemaRef, Kind, VD->getLocation(), VD->getType(),1964diag::err_constexpr_local_var_non_literal_type,1965isa<CXXConstructorDecl>(Dcl))) {1966return false;1967}1968if (!VD->getType()->isDependentType() &&1969!VD->hasInit() && !VD->isCXXForRangeDecl()) {1970if (Kind == Sema::CheckConstexprKind::Diagnose) {1971SemaRef.Diag(1972VD->getLocation(),1973SemaRef.getLangOpts().CPlusPlus201974? diag::warn_cxx17_compat_constexpr_local_var_no_init1975: diag::ext_constexpr_local_var_no_init)1976<< isa<CXXConstructorDecl>(Dcl);1977} else if (!SemaRef.getLangOpts().CPlusPlus20) {1978return false;1979}1980continue;1981}1982}1983if (Kind == Sema::CheckConstexprKind::Diagnose) {1984SemaRef.Diag(VD->getLocation(),1985SemaRef.getLangOpts().CPlusPlus141986? diag::warn_cxx11_compat_constexpr_local_var1987: diag::ext_constexpr_local_var)1988<< isa<CXXConstructorDecl>(Dcl);1989} else if (!SemaRef.getLangOpts().CPlusPlus14) {1990return false;1991}1992continue;1993}19941995case Decl::NamespaceAlias:1996case Decl::Function:1997// These are disallowed in C++11 and permitted in C++1y. Allow them1998// everywhere as an extension.1999if (!Cxx1yLoc.isValid())2000Cxx1yLoc = DS->getBeginLoc();2001continue;20022003default:2004if (Kind == Sema::CheckConstexprKind::Diagnose) {2005SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)2006<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();2007}2008return false;2009}2010}20112012return true;2013}20142015/// Check that the given field is initialized within a constexpr constructor.2016///2017/// \param Dcl The constexpr constructor being checked.2018/// \param Field The field being checked. This may be a member of an anonymous2019/// struct or union nested within the class being checked.2020/// \param Inits All declarations, including anonymous struct/union members and2021/// indirect members, for which any initialization was provided.2022/// \param Diagnosed Whether we've emitted the error message yet. Used to attach2023/// multiple notes for different members to the same error.2024/// \param Kind Whether we're diagnosing a constructor as written or determining2025/// whether the formal requirements are satisfied.2026/// \return \c false if we're checking for validity and the constructor does2027/// not satisfy the requirements on a constexpr constructor.2028static bool CheckConstexprCtorInitializer(Sema &SemaRef,2029const FunctionDecl *Dcl,2030FieldDecl *Field,2031llvm::SmallSet<Decl*, 16> &Inits,2032bool &Diagnosed,2033Sema::CheckConstexprKind Kind) {2034// In C++20 onwards, there's nothing to check for validity.2035if (Kind == Sema::CheckConstexprKind::CheckValid &&2036SemaRef.getLangOpts().CPlusPlus20)2037return true;20382039if (Field->isInvalidDecl())2040return true;20412042if (Field->isUnnamedBitField())2043return true;20442045// Anonymous unions with no variant members and empty anonymous structs do not2046// need to be explicitly initialized. FIXME: Anonymous structs that contain no2047// indirect fields don't need initializing.2048if (Field->isAnonymousStructOrUnion() &&2049(Field->getType()->isUnionType()2050? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()2051: Field->getType()->getAsCXXRecordDecl()->isEmpty()))2052return true;20532054if (!Inits.count(Field)) {2055if (Kind == Sema::CheckConstexprKind::Diagnose) {2056if (!Diagnosed) {2057SemaRef.Diag(Dcl->getLocation(),2058SemaRef.getLangOpts().CPlusPlus202059? diag::warn_cxx17_compat_constexpr_ctor_missing_init2060: diag::ext_constexpr_ctor_missing_init);2061Diagnosed = true;2062}2063SemaRef.Diag(Field->getLocation(),2064diag::note_constexpr_ctor_missing_init);2065} else if (!SemaRef.getLangOpts().CPlusPlus20) {2066return false;2067}2068} else if (Field->isAnonymousStructOrUnion()) {2069const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();2070for (auto *I : RD->fields())2071// If an anonymous union contains an anonymous struct of which any member2072// is initialized, all members must be initialized.2073if (!RD->isUnion() || Inits.count(I))2074if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,2075Kind))2076return false;2077}2078return true;2079}20802081/// Check the provided statement is allowed in a constexpr function2082/// definition.2083static bool2084CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,2085SmallVectorImpl<SourceLocation> &ReturnStmts,2086SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,2087SourceLocation &Cxx2bLoc,2088Sema::CheckConstexprKind Kind) {2089// - its function-body shall be [...] a compound-statement that contains only2090switch (S->getStmtClass()) {2091case Stmt::NullStmtClass:2092// - null statements,2093return true;20942095case Stmt::DeclStmtClass:2096// - static_assert-declarations2097// - using-declarations,2098// - using-directives,2099// - typedef declarations and alias-declarations that do not define2100// classes or enumerations,2101if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))2102return false;2103return true;21042105case Stmt::ReturnStmtClass:2106// - and exactly one return statement;2107if (isa<CXXConstructorDecl>(Dcl)) {2108// C++1y allows return statements in constexpr constructors.2109if (!Cxx1yLoc.isValid())2110Cxx1yLoc = S->getBeginLoc();2111return true;2112}21132114ReturnStmts.push_back(S->getBeginLoc());2115return true;21162117case Stmt::AttributedStmtClass:2118// Attributes on a statement don't affect its formal kind and hence don't2119// affect its validity in a constexpr function.2120return CheckConstexprFunctionStmt(2121SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,2122Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);21232124case Stmt::CompoundStmtClass: {2125// C++1y allows compound-statements.2126if (!Cxx1yLoc.isValid())2127Cxx1yLoc = S->getBeginLoc();21282129CompoundStmt *CompStmt = cast<CompoundStmt>(S);2130for (auto *BodyIt : CompStmt->body()) {2131if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,2132Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2133return false;2134}2135return true;2136}21372138case Stmt::IfStmtClass: {2139// C++1y allows if-statements.2140if (!Cxx1yLoc.isValid())2141Cxx1yLoc = S->getBeginLoc();21422143IfStmt *If = cast<IfStmt>(S);2144if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,2145Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2146return false;2147if (If->getElse() &&2148!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,2149Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2150return false;2151return true;2152}21532154case Stmt::WhileStmtClass:2155case Stmt::DoStmtClass:2156case Stmt::ForStmtClass:2157case Stmt::CXXForRangeStmtClass:2158case Stmt::ContinueStmtClass:2159// C++1y allows all of these. We don't allow them as extensions in C++11,2160// because they don't make sense without variable mutation.2161if (!SemaRef.getLangOpts().CPlusPlus14)2162break;2163if (!Cxx1yLoc.isValid())2164Cxx1yLoc = S->getBeginLoc();2165for (Stmt *SubStmt : S->children()) {2166if (SubStmt &&2167!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2168Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2169return false;2170}2171return true;21722173case Stmt::SwitchStmtClass:2174case Stmt::CaseStmtClass:2175case Stmt::DefaultStmtClass:2176case Stmt::BreakStmtClass:2177// C++1y allows switch-statements, and since they don't need variable2178// mutation, we can reasonably allow them in C++11 as an extension.2179if (!Cxx1yLoc.isValid())2180Cxx1yLoc = S->getBeginLoc();2181for (Stmt *SubStmt : S->children()) {2182if (SubStmt &&2183!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2184Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2185return false;2186}2187return true;21882189case Stmt::LabelStmtClass:2190case Stmt::GotoStmtClass:2191if (Cxx2bLoc.isInvalid())2192Cxx2bLoc = S->getBeginLoc();2193for (Stmt *SubStmt : S->children()) {2194if (SubStmt &&2195!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2196Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2197return false;2198}2199return true;22002201case Stmt::GCCAsmStmtClass:2202case Stmt::MSAsmStmtClass:2203// C++2a allows inline assembly statements.2204case Stmt::CXXTryStmtClass:2205if (Cxx2aLoc.isInvalid())2206Cxx2aLoc = S->getBeginLoc();2207for (Stmt *SubStmt : S->children()) {2208if (SubStmt &&2209!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2210Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2211return false;2212}2213return true;22142215case Stmt::CXXCatchStmtClass:2216// Do not bother checking the language mode (already covered by the2217// try block check).2218if (!CheckConstexprFunctionStmt(2219SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,2220Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2221return false;2222return true;22232224default:2225if (!isa<Expr>(S))2226break;22272228// C++1y allows expression-statements.2229if (!Cxx1yLoc.isValid())2230Cxx1yLoc = S->getBeginLoc();2231return true;2232}22332234if (Kind == Sema::CheckConstexprKind::Diagnose) {2235SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)2236<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();2237}2238return false;2239}22402241/// Check the body for the given constexpr function declaration only contains2242/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.2243///2244/// \return true if the body is OK, false if we have found or diagnosed a2245/// problem.2246static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,2247Stmt *Body,2248Sema::CheckConstexprKind Kind) {2249SmallVector<SourceLocation, 4> ReturnStmts;22502251if (isa<CXXTryStmt>(Body)) {2252// C++11 [dcl.constexpr]p3:2253// The definition of a constexpr function shall satisfy the following2254// constraints: [...]2255// - its function-body shall be = delete, = default, or a2256// compound-statement2257//2258// C++11 [dcl.constexpr]p4:2259// In the definition of a constexpr constructor, [...]2260// - its function-body shall not be a function-try-block;2261//2262// This restriction is lifted in C++2a, as long as inner statements also2263// apply the general constexpr rules.2264switch (Kind) {2265case Sema::CheckConstexprKind::CheckValid:2266if (!SemaRef.getLangOpts().CPlusPlus20)2267return false;2268break;22692270case Sema::CheckConstexprKind::Diagnose:2271SemaRef.Diag(Body->getBeginLoc(),2272!SemaRef.getLangOpts().CPlusPlus202273? diag::ext_constexpr_function_try_block_cxx202274: diag::warn_cxx17_compat_constexpr_function_try_block)2275<< isa<CXXConstructorDecl>(Dcl);2276break;2277}2278}22792280// - its function-body shall be [...] a compound-statement that contains only2281// [... list of cases ...]2282//2283// Note that walking the children here is enough to properly check for2284// CompoundStmt and CXXTryStmt body.2285SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;2286for (Stmt *SubStmt : Body->children()) {2287if (SubStmt &&2288!CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2289Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2290return false;2291}22922293if (Kind == Sema::CheckConstexprKind::CheckValid) {2294// If this is only valid as an extension, report that we don't satisfy the2295// constraints of the current language.2296if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||2297(Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||2298(Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))2299return false;2300} else if (Cxx2bLoc.isValid()) {2301SemaRef.Diag(Cxx2bLoc,2302SemaRef.getLangOpts().CPlusPlus232303? diag::warn_cxx20_compat_constexpr_body_invalid_stmt2304: diag::ext_constexpr_body_invalid_stmt_cxx23)2305<< isa<CXXConstructorDecl>(Dcl);2306} else if (Cxx2aLoc.isValid()) {2307SemaRef.Diag(Cxx2aLoc,2308SemaRef.getLangOpts().CPlusPlus202309? diag::warn_cxx17_compat_constexpr_body_invalid_stmt2310: diag::ext_constexpr_body_invalid_stmt_cxx20)2311<< isa<CXXConstructorDecl>(Dcl);2312} else if (Cxx1yLoc.isValid()) {2313SemaRef.Diag(Cxx1yLoc,2314SemaRef.getLangOpts().CPlusPlus142315? diag::warn_cxx11_compat_constexpr_body_invalid_stmt2316: diag::ext_constexpr_body_invalid_stmt)2317<< isa<CXXConstructorDecl>(Dcl);2318}23192320if (const CXXConstructorDecl *Constructor2321= dyn_cast<CXXConstructorDecl>(Dcl)) {2322const CXXRecordDecl *RD = Constructor->getParent();2323// DR1359:2324// - every non-variant non-static data member and base class sub-object2325// shall be initialized;2326// DR1460:2327// - if the class is a union having variant members, exactly one of them2328// shall be initialized;2329if (RD->isUnion()) {2330if (Constructor->getNumCtorInitializers() == 0 &&2331RD->hasVariantMembers()) {2332if (Kind == Sema::CheckConstexprKind::Diagnose) {2333SemaRef.Diag(2334Dcl->getLocation(),2335SemaRef.getLangOpts().CPlusPlus202336? diag::warn_cxx17_compat_constexpr_union_ctor_no_init2337: diag::ext_constexpr_union_ctor_no_init);2338} else if (!SemaRef.getLangOpts().CPlusPlus20) {2339return false;2340}2341}2342} else if (!Constructor->isDependentContext() &&2343!Constructor->isDelegatingConstructor()) {2344assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");23452346// Skip detailed checking if we have enough initializers, and we would2347// allow at most one initializer per member.2348bool AnyAnonStructUnionMembers = false;2349unsigned Fields = 0;2350for (CXXRecordDecl::field_iterator I = RD->field_begin(),2351E = RD->field_end(); I != E; ++I, ++Fields) {2352if (I->isAnonymousStructOrUnion()) {2353AnyAnonStructUnionMembers = true;2354break;2355}2356}2357// DR1460:2358// - if the class is a union-like class, but is not a union, for each of2359// its anonymous union members having variant members, exactly one of2360// them shall be initialized;2361if (AnyAnonStructUnionMembers ||2362Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {2363// Check initialization of non-static data members. Base classes are2364// always initialized so do not need to be checked. Dependent bases2365// might not have initializers in the member initializer list.2366llvm::SmallSet<Decl*, 16> Inits;2367for (const auto *I: Constructor->inits()) {2368if (FieldDecl *FD = I->getMember())2369Inits.insert(FD);2370else if (IndirectFieldDecl *ID = I->getIndirectMember())2371Inits.insert(ID->chain_begin(), ID->chain_end());2372}23732374bool Diagnosed = false;2375for (auto *I : RD->fields())2376if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,2377Kind))2378return false;2379}2380}2381} else {2382if (ReturnStmts.empty()) {2383switch (Kind) {2384case Sema::CheckConstexprKind::Diagnose:2385if (!CheckConstexprMissingReturn(SemaRef, Dcl))2386return false;2387break;23882389case Sema::CheckConstexprKind::CheckValid:2390// The formal requirements don't include this rule in C++14, even2391// though the "must be able to produce a constant expression" rules2392// still imply it in some cases.2393if (!SemaRef.getLangOpts().CPlusPlus14)2394return false;2395break;2396}2397} else if (ReturnStmts.size() > 1) {2398switch (Kind) {2399case Sema::CheckConstexprKind::Diagnose:2400SemaRef.Diag(2401ReturnStmts.back(),2402SemaRef.getLangOpts().CPlusPlus142403? diag::warn_cxx11_compat_constexpr_body_multiple_return2404: diag::ext_constexpr_body_multiple_return);2405for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)2406SemaRef.Diag(ReturnStmts[I],2407diag::note_constexpr_body_previous_return);2408break;24092410case Sema::CheckConstexprKind::CheckValid:2411if (!SemaRef.getLangOpts().CPlusPlus14)2412return false;2413break;2414}2415}2416}24172418// C++11 [dcl.constexpr]p5:2419// if no function argument values exist such that the function invocation2420// substitution would produce a constant expression, the program is2421// ill-formed; no diagnostic required.2422// C++11 [dcl.constexpr]p3:2423// - every constructor call and implicit conversion used in initializing the2424// return value shall be one of those allowed in a constant expression.2425// C++11 [dcl.constexpr]p4:2426// - every constructor involved in initializing non-static data members and2427// base class sub-objects shall be a constexpr constructor.2428//2429// Note that this rule is distinct from the "requirements for a constexpr2430// function", so is not checked in CheckValid mode. Because the check for2431// constexpr potential is expensive, skip the check if the diagnostic is2432// disabled, the function is declared in a system header, or we're in C++232433// or later mode (see https://wg21.link/P2448).2434bool SkipCheck =2435!SemaRef.getLangOpts().CheckConstexprFunctionBodies ||2436SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||2437SemaRef.getDiagnostics().isIgnored(2438diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());2439SmallVector<PartialDiagnosticAt, 8> Diags;2440if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&2441!Expr::isPotentialConstantExpr(Dcl, Diags)) {2442SemaRef.Diag(Dcl->getLocation(),2443diag::ext_constexpr_function_never_constant_expr)2444<< isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()2445<< Dcl->getNameInfo().getSourceRange();2446for (size_t I = 0, N = Diags.size(); I != N; ++I)2447SemaRef.Diag(Diags[I].first, Diags[I].second);2448// Don't return false here: we allow this for compatibility in2449// system headers.2450}24512452return true;2453}24542455static bool CheckConstexprMissingReturn(Sema &SemaRef,2456const FunctionDecl *Dcl) {2457bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||2458Dcl->getReturnType()->isDependentType();2459// Skip emitting a missing return error diagnostic for non-void functions2460// since C++23 no longer mandates constexpr functions to yield constant2461// expressions.2462if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)2463return true;24642465// C++14 doesn't require constexpr functions to contain a 'return'2466// statement. We still do, unless the return type might be void, because2467// otherwise if there's no return statement, the function cannot2468// be used in a core constant expression.2469bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;2470SemaRef.Diag(Dcl->getLocation(),2471OK ? diag::warn_cxx11_compat_constexpr_body_no_return2472: diag::err_constexpr_body_no_return)2473<< Dcl->isConsteval();2474return OK;2475}24762477bool Sema::CheckImmediateEscalatingFunctionDefinition(2478FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {2479if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())2480return true;2481FD->setBodyContainsImmediateEscalatingExpressions(2482FSI->FoundImmediateEscalatingExpression);2483if (FSI->FoundImmediateEscalatingExpression) {2484auto it = UndefinedButUsed.find(FD->getCanonicalDecl());2485if (it != UndefinedButUsed.end()) {2486Diag(it->second, diag::err_immediate_function_used_before_definition)2487<< it->first;2488Diag(FD->getLocation(), diag::note_defined_here) << FD;2489if (FD->isImmediateFunction() && !FD->isConsteval())2490DiagnoseImmediateEscalatingReason(FD);2491return false;2492}2493}2494return true;2495}24962497void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {2498assert(FD->isImmediateEscalating() && !FD->isConsteval() &&2499"expected an immediate function");2500assert(FD->hasBody() && "expected the function to have a body");2501struct ImmediateEscalatingExpressionsVisitor2502: public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {25032504using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;2505Sema &SemaRef;25062507const FunctionDecl *ImmediateFn;2508bool ImmediateFnIsConstructor;2509CXXConstructorDecl *CurrentConstructor = nullptr;2510CXXCtorInitializer *CurrentInit = nullptr;25112512ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)2513: SemaRef(SemaRef), ImmediateFn(FD),2514ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}25152516bool shouldVisitImplicitCode() const { return true; }2517bool shouldVisitLambdaBody() const { return false; }25182519void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {2520SourceLocation Loc = E->getBeginLoc();2521SourceRange Range = E->getSourceRange();2522if (CurrentConstructor && CurrentInit) {2523Loc = CurrentConstructor->getLocation();2524Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()2525: SourceRange();2526}25272528FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;25292530SemaRef.Diag(Loc, diag::note_immediate_function_reason)2531<< ImmediateFn << Fn << Fn->isConsteval() << IsCall2532<< isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor2533<< (InitializedField != nullptr)2534<< (CurrentInit && !CurrentInit->isWritten())2535<< InitializedField << Range;2536}2537bool TraverseCallExpr(CallExpr *E) {2538if (const auto *DR =2539dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());2540DR && DR->isImmediateEscalating()) {2541Diag(E, E->getDirectCallee(), /*IsCall=*/true);2542return false;2543}25442545for (Expr *A : E->arguments())2546if (!getDerived().TraverseStmt(A))2547return false;25482549return true;2550}25512552bool VisitDeclRefExpr(DeclRefExpr *E) {2553if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());2554ReferencedFn && E->isImmediateEscalating()) {2555Diag(E, ReferencedFn, /*IsCall=*/false);2556return false;2557}25582559return true;2560}25612562bool VisitCXXConstructExpr(CXXConstructExpr *E) {2563CXXConstructorDecl *D = E->getConstructor();2564if (E->isImmediateEscalating()) {2565Diag(E, D, /*IsCall=*/true);2566return false;2567}2568return true;2569}25702571bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {2572llvm::SaveAndRestore RAII(CurrentInit, Init);2573return Base::TraverseConstructorInitializer(Init);2574}25752576bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {2577llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);2578return Base::TraverseCXXConstructorDecl(Ctr);2579}25802581bool TraverseType(QualType T) { return true; }2582bool VisitBlockExpr(BlockExpr *T) { return true; }25832584} Visitor(*this, FD);2585Visitor.TraverseDecl(FD);2586}25872588CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {2589assert(getLangOpts().CPlusPlus && "No class names in C!");25902591if (SS && SS->isInvalid())2592return nullptr;25932594if (SS && SS->isNotEmpty()) {2595DeclContext *DC = computeDeclContext(*SS, true);2596return dyn_cast_or_null<CXXRecordDecl>(DC);2597}25982599return dyn_cast_or_null<CXXRecordDecl>(CurContext);2600}26012602bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,2603const CXXScopeSpec *SS) {2604CXXRecordDecl *CurDecl = getCurrentClass(S, SS);2605return CurDecl && &II == CurDecl->getIdentifier();2606}26072608bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {2609assert(getLangOpts().CPlusPlus && "No class names in C!");26102611if (!getLangOpts().SpellChecking)2612return false;26132614CXXRecordDecl *CurDecl;2615if (SS && SS->isSet() && !SS->isInvalid()) {2616DeclContext *DC = computeDeclContext(*SS, true);2617CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);2618} else2619CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);26202621if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&26223 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())2623< II->getLength()) {2624II = CurDecl->getIdentifier();2625return true;2626}26272628return false;2629}26302631CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,2632SourceRange SpecifierRange,2633bool Virtual, AccessSpecifier Access,2634TypeSourceInfo *TInfo,2635SourceLocation EllipsisLoc) {2636QualType BaseType = TInfo->getType();2637SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();2638if (BaseType->containsErrors()) {2639// Already emitted a diagnostic when parsing the error type.2640return nullptr;2641}26422643if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {2644Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)2645<< TInfo->getTypeLoc().getSourceRange();2646EllipsisLoc = SourceLocation();2647}26482649auto *BaseDecl =2650dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));2651// C++ [class.derived.general]p2:2652// A class-or-decltype shall denote a (possibly cv-qualified) class type2653// that is not an incompletely defined class; any cv-qualifiers are2654// ignored.2655if (BaseDecl) {2656// C++ [class.union.general]p4:2657// [...] A union shall not be used as a base class.2658if (BaseDecl->isUnion()) {2659Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;2660return nullptr;2661}26622663// For the MS ABI, propagate DLL attributes to base class templates.2664if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||2665Context.getTargetInfo().getTriple().isPS()) {2666if (Attr *ClassAttr = getDLLAttr(Class)) {2667if (auto *BaseSpec =2668dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {2669propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,2670BaseLoc);2671}2672}2673}26742675if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,2676SpecifierRange)) {2677Class->setInvalidDecl();2678return nullptr;2679}26802681BaseDecl = BaseDecl->getDefinition();2682assert(BaseDecl && "Base type is not incomplete, but has no definition");26832684// Microsoft docs say:2685// "If a base-class has a code_seg attribute, derived classes must have the2686// same attribute."2687const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();2688const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();2689if ((DerivedCSA || BaseCSA) &&2690(!BaseCSA || !DerivedCSA ||2691BaseCSA->getName() != DerivedCSA->getName())) {2692Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);2693Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)2694<< BaseDecl;2695return nullptr;2696}26972698// A class which contains a flexible array member is not suitable for use as2699// a base class:2700// - If the layout determines that a base comes before another base,2701// the flexible array member would index into the subsequent base.2702// - If the layout determines that base comes before the derived class,2703// the flexible array member would index into the derived class.2704if (BaseDecl->hasFlexibleArrayMember()) {2705Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)2706<< BaseDecl->getDeclName();2707return nullptr;2708}27092710// C++ [class]p3:2711// If a class is marked final and it appears as a base-type-specifier in2712// base-clause, the program is ill-formed.2713if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {2714Diag(BaseLoc, diag::err_class_marked_final_used_as_base)2715<< BaseDecl->getDeclName() << FA->isSpelledAsSealed();2716Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)2717<< BaseDecl->getDeclName() << FA->getRange();2718return nullptr;2719}27202721// If the base class is invalid the derived class is as well.2722if (BaseDecl->isInvalidDecl())2723Class->setInvalidDecl();2724} else if (BaseType->isDependentType()) {2725// Make sure that we don't make an ill-formed AST where the type of the2726// Class is non-dependent and its attached base class specifier is an2727// dependent type, which violates invariants in many clang code paths (e.g.2728// constexpr evaluator). If this case happens (in errory-recovery mode), we2729// explicitly mark the Class decl invalid. The diagnostic was already2730// emitted.2731if (!Class->isDependentContext())2732Class->setInvalidDecl();2733} else {2734// The base class is some non-dependent non-class type.2735Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;2736return nullptr;2737}27382739// In HLSL, unspecified class access is public rather than private.2740if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&2741Access == AS_none)2742Access = AS_public;27432744// Create the base specifier.2745return new (Context) CXXBaseSpecifier(2746SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,2747Access, TInfo, EllipsisLoc);2748}27492750BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,2751const ParsedAttributesView &Attributes,2752bool Virtual, AccessSpecifier Access,2753ParsedType basetype, SourceLocation BaseLoc,2754SourceLocation EllipsisLoc) {2755if (!classdecl)2756return true;27572758AdjustDeclIfTemplate(classdecl);2759CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);2760if (!Class)2761return true;27622763// We haven't yet attached the base specifiers.2764Class->setIsParsingBaseSpecifiers();27652766// We do not support any C++11 attributes on base-specifiers yet.2767// Diagnose any attributes we see.2768for (const ParsedAttr &AL : Attributes) {2769if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)2770continue;2771if (AL.getKind() == ParsedAttr::UnknownAttribute)2772Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)2773<< AL << AL.getRange();2774else2775Diag(AL.getLoc(), diag::err_base_specifier_attribute)2776<< AL << AL.isRegularKeywordAttribute() << AL.getRange();2777}27782779TypeSourceInfo *TInfo = nullptr;2780GetTypeFromParser(basetype, &TInfo);27812782if (EllipsisLoc.isInvalid() &&2783DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,2784UPPC_BaseType))2785return true;27862787// C++ [class.union.general]p4:2788// [...] A union shall not have base classes.2789if (Class->isUnion()) {2790Diag(Class->getLocation(), diag::err_base_clause_on_union)2791<< SpecifierRange;2792return true;2793}27942795if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,2796Virtual, Access, TInfo,2797EllipsisLoc))2798return BaseSpec;27992800Class->setInvalidDecl();2801return true;2802}28032804/// Use small set to collect indirect bases. As this is only used2805/// locally, there's no need to abstract the small size parameter.2806typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;28072808/// Recursively add the bases of Type. Don't add Type itself.2809static void2810NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,2811const QualType &Type)2812{2813// Even though the incoming type is a base, it might not be2814// a class -- it could be a template parm, for instance.2815if (auto Rec = Type->getAs<RecordType>()) {2816auto Decl = Rec->getAsCXXRecordDecl();28172818// Iterate over its bases.2819for (const auto &BaseSpec : Decl->bases()) {2820QualType Base = Context.getCanonicalType(BaseSpec.getType())2821.getUnqualifiedType();2822if (Set.insert(Base).second)2823// If we've not already seen it, recurse.2824NoteIndirectBases(Context, Set, Base);2825}2826}2827}28282829bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,2830MutableArrayRef<CXXBaseSpecifier *> Bases) {2831if (Bases.empty())2832return false;28332834// Used to keep track of which base types we have already seen, so2835// that we can properly diagnose redundant direct base types. Note2836// that the key is always the unqualified canonical type of the base2837// class.2838std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;28392840// Used to track indirect bases so we can see if a direct base is2841// ambiguous.2842IndirectBaseSet IndirectBaseTypes;28432844// Copy non-redundant base specifiers into permanent storage.2845unsigned NumGoodBases = 0;2846bool Invalid = false;2847for (unsigned idx = 0; idx < Bases.size(); ++idx) {2848QualType NewBaseType2849= Context.getCanonicalType(Bases[idx]->getType());2850NewBaseType = NewBaseType.getLocalUnqualifiedType();28512852CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];2853if (KnownBase) {2854// C++ [class.mi]p3:2855// A class shall not be specified as a direct base class of a2856// derived class more than once.2857Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)2858<< KnownBase->getType() << Bases[idx]->getSourceRange();28592860// Delete the duplicate base class specifier; we're going to2861// overwrite its pointer later.2862Context.Deallocate(Bases[idx]);28632864Invalid = true;2865} else {2866// Okay, add this new base class.2867KnownBase = Bases[idx];2868Bases[NumGoodBases++] = Bases[idx];28692870if (NewBaseType->isDependentType())2871continue;2872// Note this base's direct & indirect bases, if there could be ambiguity.2873if (Bases.size() > 1)2874NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);28752876if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {2877const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());2878if (Class->isInterface() &&2879(!RD->isInterfaceLike() ||2880KnownBase->getAccessSpecifier() != AS_public)) {2881// The Microsoft extension __interface does not permit bases that2882// are not themselves public interfaces.2883Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)2884<< getRecordDiagFromTagKind(RD->getTagKind()) << RD2885<< RD->getSourceRange();2886Invalid = true;2887}2888if (RD->hasAttr<WeakAttr>())2889Class->addAttr(WeakAttr::CreateImplicit(Context));2890}2891}2892}28932894// Attach the remaining base class specifiers to the derived class.2895Class->setBases(Bases.data(), NumGoodBases);28962897// Check that the only base classes that are duplicate are virtual.2898for (unsigned idx = 0; idx < NumGoodBases; ++idx) {2899// Check whether this direct base is inaccessible due to ambiguity.2900QualType BaseType = Bases[idx]->getType();29012902// Skip all dependent types in templates being used as base specifiers.2903// Checks below assume that the base specifier is a CXXRecord.2904if (BaseType->isDependentType())2905continue;29062907CanQualType CanonicalBase = Context.getCanonicalType(BaseType)2908.getUnqualifiedType();29092910if (IndirectBaseTypes.count(CanonicalBase)) {2911CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,2912/*DetectVirtual=*/true);2913bool found2914= Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);2915assert(found);2916(void)found;29172918if (Paths.isAmbiguous(CanonicalBase))2919Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)2920<< BaseType << getAmbiguousPathsDisplayString(Paths)2921<< Bases[idx]->getSourceRange();2922else2923assert(Bases[idx]->isVirtual());2924}29252926// Delete the base class specifier, since its data has been copied2927// into the CXXRecordDecl.2928Context.Deallocate(Bases[idx]);2929}29302931return Invalid;2932}29332934void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,2935MutableArrayRef<CXXBaseSpecifier *> Bases) {2936if (!ClassDecl || Bases.empty())2937return;29382939AdjustDeclIfTemplate(ClassDecl);2940AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);2941}29422943bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {2944if (!getLangOpts().CPlusPlus)2945return false;29462947CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();2948if (!DerivedRD)2949return false;29502951CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();2952if (!BaseRD)2953return false;29542955// If either the base or the derived type is invalid, don't try to2956// check whether one is derived from the other.2957if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())2958return false;29592960// FIXME: In a modules build, do we need the entire path to be visible for us2961// to be able to use the inheritance relationship?2962if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())2963return false;29642965return DerivedRD->isDerivedFrom(BaseRD);2966}29672968bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,2969CXXBasePaths &Paths) {2970if (!getLangOpts().CPlusPlus)2971return false;29722973CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();2974if (!DerivedRD)2975return false;29762977CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();2978if (!BaseRD)2979return false;29802981if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())2982return false;29832984return DerivedRD->isDerivedFrom(BaseRD, Paths);2985}29862987static void BuildBasePathArray(const CXXBasePath &Path,2988CXXCastPath &BasePathArray) {2989// We first go backward and check if we have a virtual base.2990// FIXME: It would be better if CXXBasePath had the base specifier for2991// the nearest virtual base.2992unsigned Start = 0;2993for (unsigned I = Path.size(); I != 0; --I) {2994if (Path[I - 1].Base->isVirtual()) {2995Start = I - 1;2996break;2997}2998}29993000// Now add all bases.3001for (unsigned I = Start, E = Path.size(); I != E; ++I)3002BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));3003}300430053006void Sema::BuildBasePathArray(const CXXBasePaths &Paths,3007CXXCastPath &BasePathArray) {3008assert(BasePathArray.empty() && "Base path array must be empty!");3009assert(Paths.isRecordingPaths() && "Must record paths!");3010return ::BuildBasePathArray(Paths.front(), BasePathArray);3011}30123013bool3014Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,3015unsigned InaccessibleBaseID,3016unsigned AmbiguousBaseConvID,3017SourceLocation Loc, SourceRange Range,3018DeclarationName Name,3019CXXCastPath *BasePath,3020bool IgnoreAccess) {3021// First, determine whether the path from Derived to Base is3022// ambiguous. This is slightly more expensive than checking whether3023// the Derived to Base conversion exists, because here we need to3024// explore multiple paths to determine if there is an ambiguity.3025CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3026/*DetectVirtual=*/false);3027bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);3028if (!DerivationOkay)3029return true;30303031const CXXBasePath *Path = nullptr;3032if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))3033Path = &Paths.front();30343035// For MSVC compatibility, check if Derived directly inherits from Base. Clang3036// warns about this hierarchy under -Winaccessible-base, but MSVC allows the3037// user to access such bases.3038if (!Path && getLangOpts().MSVCCompat) {3039for (const CXXBasePath &PossiblePath : Paths) {3040if (PossiblePath.size() == 1) {3041Path = &PossiblePath;3042if (AmbiguousBaseConvID)3043Diag(Loc, diag::ext_ms_ambiguous_direct_base)3044<< Base << Derived << Range;3045break;3046}3047}3048}30493050if (Path) {3051if (!IgnoreAccess) {3052// Check that the base class can be accessed.3053switch (3054CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {3055case AR_inaccessible:3056return true;3057case AR_accessible:3058case AR_dependent:3059case AR_delayed:3060break;3061}3062}30633064// Build a base path if necessary.3065if (BasePath)3066::BuildBasePathArray(*Path, *BasePath);3067return false;3068}30693070if (AmbiguousBaseConvID) {3071// We know that the derived-to-base conversion is ambiguous, and3072// we're going to produce a diagnostic. Perform the derived-to-base3073// search just one more time to compute all of the possible paths so3074// that we can print them out. This is more expensive than any of3075// the previous derived-to-base checks we've done, but at this point3076// performance isn't as much of an issue.3077Paths.clear();3078Paths.setRecordingPaths(true);3079bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);3080assert(StillOkay && "Can only be used with a derived-to-base conversion");3081(void)StillOkay;30823083// Build up a textual representation of the ambiguous paths, e.g.,3084// D -> B -> A, that will be used to illustrate the ambiguous3085// conversions in the diagnostic. We only print one of the paths3086// to each base class subobject.3087std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);30883089Diag(Loc, AmbiguousBaseConvID)3090<< Derived << Base << PathDisplayStr << Range << Name;3091}3092return true;3093}30943095bool3096Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,3097SourceLocation Loc, SourceRange Range,3098CXXCastPath *BasePath,3099bool IgnoreAccess) {3100return CheckDerivedToBaseConversion(3101Derived, Base, diag::err_upcast_to_inaccessible_base,3102diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),3103BasePath, IgnoreAccess);3104}31053106std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {3107std::string PathDisplayStr;3108std::set<unsigned> DisplayedPaths;3109for (CXXBasePaths::paths_iterator Path = Paths.begin();3110Path != Paths.end(); ++Path) {3111if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {3112// We haven't displayed a path to this particular base3113// class subobject yet.3114PathDisplayStr += "\n ";3115PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();3116for (CXXBasePath::const_iterator Element = Path->begin();3117Element != Path->end(); ++Element)3118PathDisplayStr += " -> " + Element->Base->getType().getAsString();3119}3120}31213122return PathDisplayStr;3123}31243125//===----------------------------------------------------------------------===//3126// C++ class member Handling3127//===----------------------------------------------------------------------===//31283129bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,3130SourceLocation ColonLoc,3131const ParsedAttributesView &Attrs) {3132assert(Access != AS_none && "Invalid kind for syntactic access specifier!");3133AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,3134ASLoc, ColonLoc);3135CurContext->addHiddenDecl(ASDecl);3136return ProcessAccessDeclAttributeList(ASDecl, Attrs);3137}31383139void Sema::CheckOverrideControl(NamedDecl *D) {3140if (D->isInvalidDecl())3141return;31423143// We only care about "override" and "final" declarations.3144if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())3145return;31463147CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);31483149// We can't check dependent instance methods.3150if (MD && MD->isInstance() &&3151(MD->getParent()->hasAnyDependentBases() ||3152MD->getType()->isDependentType()))3153return;31543155if (MD && !MD->isVirtual()) {3156// If we have a non-virtual method, check if it hides a virtual method.3157// (In that case, it's most likely the method has the wrong type.)3158SmallVector<CXXMethodDecl *, 8> OverloadedMethods;3159FindHiddenVirtualMethods(MD, OverloadedMethods);31603161if (!OverloadedMethods.empty()) {3162if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {3163Diag(OA->getLocation(),3164diag::override_keyword_hides_virtual_member_function)3165<< "override" << (OverloadedMethods.size() > 1);3166} else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {3167Diag(FA->getLocation(),3168diag::override_keyword_hides_virtual_member_function)3169<< (FA->isSpelledAsSealed() ? "sealed" : "final")3170<< (OverloadedMethods.size() > 1);3171}3172NoteHiddenVirtualMethods(MD, OverloadedMethods);3173MD->setInvalidDecl();3174return;3175}3176// Fall through into the general case diagnostic.3177// FIXME: We might want to attempt typo correction here.3178}31793180if (!MD || !MD->isVirtual()) {3181if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {3182Diag(OA->getLocation(),3183diag::override_keyword_only_allowed_on_virtual_member_functions)3184<< "override" << FixItHint::CreateRemoval(OA->getLocation());3185D->dropAttr<OverrideAttr>();3186}3187if (FinalAttr *FA = D->getAttr<FinalAttr>()) {3188Diag(FA->getLocation(),3189diag::override_keyword_only_allowed_on_virtual_member_functions)3190<< (FA->isSpelledAsSealed() ? "sealed" : "final")3191<< FixItHint::CreateRemoval(FA->getLocation());3192D->dropAttr<FinalAttr>();3193}3194return;3195}31963197// C++11 [class.virtual]p5:3198// If a function is marked with the virt-specifier override and3199// does not override a member function of a base class, the program is3200// ill-formed.3201bool HasOverriddenMethods = MD->size_overridden_methods() != 0;3202if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)3203Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)3204<< MD->getDeclName();3205}32063207void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {3208if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())3209return;3210CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);3211if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())3212return;32133214SourceLocation Loc = MD->getLocation();3215SourceLocation SpellingLoc = Loc;3216if (getSourceManager().isMacroArgExpansion(Loc))3217SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();3218SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);3219if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))3220return;32213222if (MD->size_overridden_methods() > 0) {3223auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {3224unsigned DiagID =3225Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())3226? DiagInconsistent3227: DiagSuggest;3228Diag(MD->getLocation(), DiagID) << MD->getDeclName();3229const CXXMethodDecl *OMD = *MD->begin_overridden_methods();3230Diag(OMD->getLocation(), diag::note_overridden_virtual_function);3231};3232if (isa<CXXDestructorDecl>(MD))3233EmitDiag(3234diag::warn_inconsistent_destructor_marked_not_override_overriding,3235diag::warn_suggest_destructor_marked_not_override_overriding);3236else3237EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,3238diag::warn_suggest_function_marked_not_override_overriding);3239}3240}32413242bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,3243const CXXMethodDecl *Old) {3244FinalAttr *FA = Old->getAttr<FinalAttr>();3245if (!FA)3246return false;32473248Diag(New->getLocation(), diag::err_final_function_overridden)3249<< New->getDeclName()3250<< FA->isSpelledAsSealed();3251Diag(Old->getLocation(), diag::note_overridden_virtual_function);3252return true;3253}32543255static bool InitializationHasSideEffects(const FieldDecl &FD) {3256const Type *T = FD.getType()->getBaseElementTypeUnsafe();3257// FIXME: Destruction of ObjC lifetime types has side-effects.3258if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())3259return !RD->isCompleteDefinition() ||3260!RD->hasTrivialDefaultConstructor() ||3261!RD->hasTrivialDestructor();3262return false;3263}32643265void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,3266DeclarationName FieldName,3267const CXXRecordDecl *RD,3268bool DeclIsField) {3269if (Diags.isIgnored(diag::warn_shadow_field, Loc))3270return;32713272// To record a shadowed field in a base3273std::map<CXXRecordDecl*, NamedDecl*> Bases;3274auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,3275CXXBasePath &Path) {3276const auto Base = Specifier->getType()->getAsCXXRecordDecl();3277// Record an ambiguous path directly3278if (Bases.find(Base) != Bases.end())3279return true;3280for (const auto Field : Base->lookup(FieldName)) {3281if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&3282Field->getAccess() != AS_private) {3283assert(Field->getAccess() != AS_none);3284assert(Bases.find(Base) == Bases.end());3285Bases[Base] = Field;3286return true;3287}3288}3289return false;3290};32913292CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3293/*DetectVirtual=*/true);3294if (!RD->lookupInBases(FieldShadowed, Paths))3295return;32963297for (const auto &P : Paths) {3298auto Base = P.back().Base->getType()->getAsCXXRecordDecl();3299auto It = Bases.find(Base);3300// Skip duplicated bases3301if (It == Bases.end())3302continue;3303auto BaseField = It->second;3304assert(BaseField->getAccess() != AS_private);3305if (AS_none !=3306CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {3307Diag(Loc, diag::warn_shadow_field)3308<< FieldName << RD << Base << DeclIsField;3309Diag(BaseField->getLocation(), diag::note_shadow_field);3310Bases.erase(It);3311}3312}3313}33143315NamedDecl *3316Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,3317MultiTemplateParamsArg TemplateParameterLists,3318Expr *BW, const VirtSpecifiers &VS,3319InClassInitStyle InitStyle) {3320const DeclSpec &DS = D.getDeclSpec();3321DeclarationNameInfo NameInfo = GetNameForDeclarator(D);3322DeclarationName Name = NameInfo.getName();3323SourceLocation Loc = NameInfo.getLoc();33243325// For anonymous bitfields, the location should point to the type.3326if (Loc.isInvalid())3327Loc = D.getBeginLoc();33283329Expr *BitWidth = static_cast<Expr*>(BW);33303331assert(isa<CXXRecordDecl>(CurContext));3332assert(!DS.isFriendSpecified());33333334bool isFunc = D.isDeclarationOfFunction();3335const ParsedAttr *MSPropertyAttr =3336D.getDeclSpec().getAttributes().getMSPropertyAttr();33373338if (cast<CXXRecordDecl>(CurContext)->isInterface()) {3339// The Microsoft extension __interface only permits public member functions3340// and prohibits constructors, destructors, operators, non-public member3341// functions, static methods and data members.3342unsigned InvalidDecl;3343bool ShowDeclName = true;3344if (!isFunc &&3345(DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))3346InvalidDecl = 0;3347else if (!isFunc)3348InvalidDecl = 1;3349else if (AS != AS_public)3350InvalidDecl = 2;3351else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)3352InvalidDecl = 3;3353else switch (Name.getNameKind()) {3354case DeclarationName::CXXConstructorName:3355InvalidDecl = 4;3356ShowDeclName = false;3357break;33583359case DeclarationName::CXXDestructorName:3360InvalidDecl = 5;3361ShowDeclName = false;3362break;33633364case DeclarationName::CXXOperatorName:3365case DeclarationName::CXXConversionFunctionName:3366InvalidDecl = 6;3367break;33683369default:3370InvalidDecl = 0;3371break;3372}33733374if (InvalidDecl) {3375if (ShowDeclName)3376Diag(Loc, diag::err_invalid_member_in_interface)3377<< (InvalidDecl-1) << Name;3378else3379Diag(Loc, diag::err_invalid_member_in_interface)3380<< (InvalidDecl-1) << "";3381return nullptr;3382}3383}33843385// C++ 9.2p6: A member shall not be declared to have automatic storage3386// duration (auto, register) or with the extern storage-class-specifier.3387// C++ 7.1.1p8: The mutable specifier can be applied only to names of class3388// data members and cannot be applied to names declared const or static,3389// and cannot be applied to reference members.3390switch (DS.getStorageClassSpec()) {3391case DeclSpec::SCS_unspecified:3392case DeclSpec::SCS_typedef:3393case DeclSpec::SCS_static:3394break;3395case DeclSpec::SCS_mutable:3396if (isFunc) {3397Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);33983399// FIXME: It would be nicer if the keyword was ignored only for this3400// declarator. Otherwise we could get follow-up errors.3401D.getMutableDeclSpec().ClearStorageClassSpecs();3402}3403break;3404default:3405Diag(DS.getStorageClassSpecLoc(),3406diag::err_storageclass_invalid_for_member);3407D.getMutableDeclSpec().ClearStorageClassSpecs();3408break;3409}34103411bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||3412DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&3413!isFunc && TemplateParameterLists.empty();34143415if (DS.hasConstexprSpecifier() && isInstField) {3416SemaDiagnosticBuilder B =3417Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);3418SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();3419if (InitStyle == ICIS_NoInit) {3420B << 0 << 0;3421if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)3422B << FixItHint::CreateRemoval(ConstexprLoc);3423else {3424B << FixItHint::CreateReplacement(ConstexprLoc, "const");3425D.getMutableDeclSpec().ClearConstexprSpec();3426const char *PrevSpec;3427unsigned DiagID;3428bool Failed = D.getMutableDeclSpec().SetTypeQual(3429DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());3430(void)Failed;3431assert(!Failed && "Making a constexpr member const shouldn't fail");3432}3433} else {3434B << 1;3435const char *PrevSpec;3436unsigned DiagID;3437if (D.getMutableDeclSpec().SetStorageClassSpec(3438*this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,3439Context.getPrintingPolicy())) {3440assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&3441"This is the only DeclSpec that should fail to be applied");3442B << 1;3443} else {3444B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");3445isInstField = false;3446}3447}3448}34493450NamedDecl *Member;3451if (isInstField) {3452CXXScopeSpec &SS = D.getCXXScopeSpec();34533454// Data members must have identifiers for names.3455if (!Name.isIdentifier()) {3456Diag(Loc, diag::err_bad_variable_name)3457<< Name;3458return nullptr;3459}34603461IdentifierInfo *II = Name.getAsIdentifierInfo();3462if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {3463Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)3464<< II3465<< SourceRange(D.getName().TemplateId->LAngleLoc,3466D.getName().TemplateId->RAngleLoc)3467<< D.getName().TemplateId->LAngleLoc;3468D.SetIdentifier(II, Loc);3469}34703471if (SS.isSet() && !SS.isInvalid()) {3472// The user provided a superfluous scope specifier inside a class3473// definition:3474//3475// class X {3476// int X::member;3477// };3478if (DeclContext *DC = computeDeclContext(SS, false)) {3479TemplateIdAnnotation *TemplateId =3480D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId3481? D.getName().TemplateId3482: nullptr;3483diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),3484TemplateId,3485/*IsMemberSpecialization=*/false);3486} else {3487Diag(D.getIdentifierLoc(), diag::err_member_qualification)3488<< Name << SS.getRange();3489}3490SS.clear();3491}34923493if (MSPropertyAttr) {3494Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,3495BitWidth, InitStyle, AS, *MSPropertyAttr);3496if (!Member)3497return nullptr;3498isInstField = false;3499} else {3500Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,3501BitWidth, InitStyle, AS);3502if (!Member)3503return nullptr;3504}35053506CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));3507} else {3508Member = HandleDeclarator(S, D, TemplateParameterLists);3509if (!Member)3510return nullptr;35113512// Non-instance-fields can't have a bitfield.3513if (BitWidth) {3514if (Member->isInvalidDecl()) {3515// don't emit another diagnostic.3516} else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {3517// C++ 9.6p3: A bit-field shall not be a static member.3518// "static member 'A' cannot be a bit-field"3519Diag(Loc, diag::err_static_not_bitfield)3520<< Name << BitWidth->getSourceRange();3521} else if (isa<TypedefDecl>(Member)) {3522// "typedef member 'x' cannot be a bit-field"3523Diag(Loc, diag::err_typedef_not_bitfield)3524<< Name << BitWidth->getSourceRange();3525} else {3526// A function typedef ("typedef int f(); f a;").3527// C++ 9.6p3: A bit-field shall have integral or enumeration type.3528Diag(Loc, diag::err_not_integral_type_bitfield)3529<< Name << cast<ValueDecl>(Member)->getType()3530<< BitWidth->getSourceRange();3531}35323533BitWidth = nullptr;3534Member->setInvalidDecl();3535}35363537NamedDecl *NonTemplateMember = Member;3538if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))3539NonTemplateMember = FunTmpl->getTemplatedDecl();3540else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))3541NonTemplateMember = VarTmpl->getTemplatedDecl();35423543Member->setAccess(AS);35443545// If we have declared a member function template or static data member3546// template, set the access of the templated declaration as well.3547if (NonTemplateMember != Member)3548NonTemplateMember->setAccess(AS);35493550// C++ [temp.deduct.guide]p3:3551// A deduction guide [...] for a member class template [shall be3552// declared] with the same access [as the template].3553if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {3554auto *TD = DG->getDeducedTemplate();3555// Access specifiers are only meaningful if both the template and the3556// deduction guide are from the same scope.3557if (AS != TD->getAccess() &&3558TD->getDeclContext()->getRedeclContext()->Equals(3559DG->getDeclContext()->getRedeclContext())) {3560Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);3561Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)3562<< TD->getAccess();3563const AccessSpecDecl *LastAccessSpec = nullptr;3564for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {3565if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))3566LastAccessSpec = AccessSpec;3567}3568assert(LastAccessSpec && "differing access with no access specifier");3569Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)3570<< AS;3571}3572}3573}35743575if (VS.isOverrideSpecified())3576Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));3577if (VS.isFinalSpecified())3578Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),3579VS.isFinalSpelledSealed()3580? FinalAttr::Keyword_sealed3581: FinalAttr::Keyword_final));35823583if (VS.getLastLocation().isValid()) {3584// Update the end location of a method that has a virt-specifiers.3585if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))3586MD->setRangeEnd(VS.getLastLocation());3587}35883589CheckOverrideControl(Member);35903591assert((Name || isInstField) && "No identifier for non-field ?");35923593if (isInstField) {3594FieldDecl *FD = cast<FieldDecl>(Member);3595FieldCollector->Add(FD);35963597if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {3598// Remember all explicit private FieldDecls that have a name, no side3599// effects and are not part of a dependent type declaration.36003601auto DeclHasUnusedAttr = [](const QualType &T) {3602if (const TagDecl *TD = T->getAsTagDecl())3603return TD->hasAttr<UnusedAttr>();3604if (const TypedefType *TDT = T->getAs<TypedefType>())3605return TDT->getDecl()->hasAttr<UnusedAttr>();3606return false;3607};36083609if (!FD->isImplicit() && FD->getDeclName() &&3610FD->getAccess() == AS_private &&3611!FD->hasAttr<UnusedAttr>() &&3612!FD->getParent()->isDependentContext() &&3613!DeclHasUnusedAttr(FD->getType()) &&3614!InitializationHasSideEffects(*FD))3615UnusedPrivateFields.insert(FD);3616}3617}36183619return Member;3620}36213622namespace {3623class UninitializedFieldVisitor3624: public EvaluatedExprVisitor<UninitializedFieldVisitor> {3625Sema &S;3626// List of Decls to generate a warning on. Also remove Decls that become3627// initialized.3628llvm::SmallPtrSetImpl<ValueDecl*> &Decls;3629// List of base classes of the record. Classes are removed after their3630// initializers.3631llvm::SmallPtrSetImpl<QualType> &BaseClasses;3632// Vector of decls to be removed from the Decl set prior to visiting the3633// nodes. These Decls may have been initialized in the prior initializer.3634llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;3635// If non-null, add a note to the warning pointing back to the constructor.3636const CXXConstructorDecl *Constructor;3637// Variables to hold state when processing an initializer list. When3638// InitList is true, special case initialization of FieldDecls matching3639// InitListFieldDecl.3640bool InitList;3641FieldDecl *InitListFieldDecl;3642llvm::SmallVector<unsigned, 4> InitFieldIndex;36433644public:3645typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;3646UninitializedFieldVisitor(Sema &S,3647llvm::SmallPtrSetImpl<ValueDecl*> &Decls,3648llvm::SmallPtrSetImpl<QualType> &BaseClasses)3649: Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),3650Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}36513652// Returns true if the use of ME is not an uninitialized use.3653bool IsInitListMemberExprInitialized(MemberExpr *ME,3654bool CheckReferenceOnly) {3655llvm::SmallVector<FieldDecl*, 4> Fields;3656bool ReferenceField = false;3657while (ME) {3658FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());3659if (!FD)3660return false;3661Fields.push_back(FD);3662if (FD->getType()->isReferenceType())3663ReferenceField = true;3664ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());3665}36663667// Binding a reference to an uninitialized field is not an3668// uninitialized use.3669if (CheckReferenceOnly && !ReferenceField)3670return true;36713672llvm::SmallVector<unsigned, 4> UsedFieldIndex;3673// Discard the first field since it is the field decl that is being3674// initialized.3675for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))3676UsedFieldIndex.push_back(FD->getFieldIndex());36773678for (auto UsedIter = UsedFieldIndex.begin(),3679UsedEnd = UsedFieldIndex.end(),3680OrigIter = InitFieldIndex.begin(),3681OrigEnd = InitFieldIndex.end();3682UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {3683if (*UsedIter < *OrigIter)3684return true;3685if (*UsedIter > *OrigIter)3686break;3687}36883689return false;3690}36913692void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,3693bool AddressOf) {3694if (isa<EnumConstantDecl>(ME->getMemberDecl()))3695return;36963697// FieldME is the inner-most MemberExpr that is not an anonymous struct3698// or union.3699MemberExpr *FieldME = ME;37003701bool AllPODFields = FieldME->getType().isPODType(S.Context);37023703Expr *Base = ME;3704while (MemberExpr *SubME =3705dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {37063707if (isa<VarDecl>(SubME->getMemberDecl()))3708return;37093710if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))3711if (!FD->isAnonymousStructOrUnion())3712FieldME = SubME;37133714if (!FieldME->getType().isPODType(S.Context))3715AllPODFields = false;37163717Base = SubME->getBase();3718}37193720if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {3721Visit(Base);3722return;3723}37243725if (AddressOf && AllPODFields)3726return;37273728ValueDecl* FoundVD = FieldME->getMemberDecl();37293730if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {3731while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {3732BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());3733}37343735if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {3736QualType T = BaseCast->getType();3737if (T->isPointerType() &&3738BaseClasses.count(T->getPointeeType())) {3739S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)3740<< T->getPointeeType() << FoundVD;3741}3742}3743}37443745if (!Decls.count(FoundVD))3746return;37473748const bool IsReference = FoundVD->getType()->isReferenceType();37493750if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {3751// Special checking for initializer lists.3752if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {3753return;3754}3755} else {3756// Prevent double warnings on use of unbounded references.3757if (CheckReferenceOnly && !IsReference)3758return;3759}37603761unsigned diag = IsReference3762? diag::warn_reference_field_is_uninit3763: diag::warn_field_is_uninit;3764S.Diag(FieldME->getExprLoc(), diag) << FoundVD;3765if (Constructor)3766S.Diag(Constructor->getLocation(),3767diag::note_uninit_in_this_constructor)3768<< (Constructor->isDefaultConstructor() && Constructor->isImplicit());37693770}37713772void HandleValue(Expr *E, bool AddressOf) {3773E = E->IgnoreParens();37743775if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {3776HandleMemberExpr(ME, false /*CheckReferenceOnly*/,3777AddressOf /*AddressOf*/);3778return;3779}37803781if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {3782Visit(CO->getCond());3783HandleValue(CO->getTrueExpr(), AddressOf);3784HandleValue(CO->getFalseExpr(), AddressOf);3785return;3786}37873788if (BinaryConditionalOperator *BCO =3789dyn_cast<BinaryConditionalOperator>(E)) {3790Visit(BCO->getCond());3791HandleValue(BCO->getFalseExpr(), AddressOf);3792return;3793}37943795if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {3796HandleValue(OVE->getSourceExpr(), AddressOf);3797return;3798}37993800if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {3801switch (BO->getOpcode()) {3802default:3803break;3804case(BO_PtrMemD):3805case(BO_PtrMemI):3806HandleValue(BO->getLHS(), AddressOf);3807Visit(BO->getRHS());3808return;3809case(BO_Comma):3810Visit(BO->getLHS());3811HandleValue(BO->getRHS(), AddressOf);3812return;3813}3814}38153816Visit(E);3817}38183819void CheckInitListExpr(InitListExpr *ILE) {3820InitFieldIndex.push_back(0);3821for (auto *Child : ILE->children()) {3822if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {3823CheckInitListExpr(SubList);3824} else {3825Visit(Child);3826}3827++InitFieldIndex.back();3828}3829InitFieldIndex.pop_back();3830}38313832void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,3833FieldDecl *Field, const Type *BaseClass) {3834// Remove Decls that may have been initialized in the previous3835// initializer.3836for (ValueDecl* VD : DeclsToRemove)3837Decls.erase(VD);3838DeclsToRemove.clear();38393840Constructor = FieldConstructor;3841InitListExpr *ILE = dyn_cast<InitListExpr>(E);38423843if (ILE && Field) {3844InitList = true;3845InitListFieldDecl = Field;3846InitFieldIndex.clear();3847CheckInitListExpr(ILE);3848} else {3849InitList = false;3850Visit(E);3851}38523853if (Field)3854Decls.erase(Field);3855if (BaseClass)3856BaseClasses.erase(BaseClass->getCanonicalTypeInternal());3857}38583859void VisitMemberExpr(MemberExpr *ME) {3860// All uses of unbounded reference fields will warn.3861HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);3862}38633864void VisitImplicitCastExpr(ImplicitCastExpr *E) {3865if (E->getCastKind() == CK_LValueToRValue) {3866HandleValue(E->getSubExpr(), false /*AddressOf*/);3867return;3868}38693870Inherited::VisitImplicitCastExpr(E);3871}38723873void VisitCXXConstructExpr(CXXConstructExpr *E) {3874if (E->getConstructor()->isCopyConstructor()) {3875Expr *ArgExpr = E->getArg(0);3876if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))3877if (ILE->getNumInits() == 1)3878ArgExpr = ILE->getInit(0);3879if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))3880if (ICE->getCastKind() == CK_NoOp)3881ArgExpr = ICE->getSubExpr();3882HandleValue(ArgExpr, false /*AddressOf*/);3883return;3884}3885Inherited::VisitCXXConstructExpr(E);3886}38873888void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {3889Expr *Callee = E->getCallee();3890if (isa<MemberExpr>(Callee)) {3891HandleValue(Callee, false /*AddressOf*/);3892for (auto *Arg : E->arguments())3893Visit(Arg);3894return;3895}38963897Inherited::VisitCXXMemberCallExpr(E);3898}38993900void VisitCallExpr(CallExpr *E) {3901// Treat std::move as a use.3902if (E->isCallToStdMove()) {3903HandleValue(E->getArg(0), /*AddressOf=*/false);3904return;3905}39063907Inherited::VisitCallExpr(E);3908}39093910void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {3911Expr *Callee = E->getCallee();39123913if (isa<UnresolvedLookupExpr>(Callee))3914return Inherited::VisitCXXOperatorCallExpr(E);39153916Visit(Callee);3917for (auto *Arg : E->arguments())3918HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);3919}39203921void VisitBinaryOperator(BinaryOperator *E) {3922// If a field assignment is detected, remove the field from the3923// uninitiailized field set.3924if (E->getOpcode() == BO_Assign)3925if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))3926if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))3927if (!FD->getType()->isReferenceType())3928DeclsToRemove.push_back(FD);39293930if (E->isCompoundAssignmentOp()) {3931HandleValue(E->getLHS(), false /*AddressOf*/);3932Visit(E->getRHS());3933return;3934}39353936Inherited::VisitBinaryOperator(E);3937}39383939void VisitUnaryOperator(UnaryOperator *E) {3940if (E->isIncrementDecrementOp()) {3941HandleValue(E->getSubExpr(), false /*AddressOf*/);3942return;3943}3944if (E->getOpcode() == UO_AddrOf) {3945if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {3946HandleValue(ME->getBase(), true /*AddressOf*/);3947return;3948}3949}39503951Inherited::VisitUnaryOperator(E);3952}3953};39543955// Diagnose value-uses of fields to initialize themselves, e.g.3956// foo(foo)3957// where foo is not also a parameter to the constructor.3958// Also diagnose across field uninitialized use such as3959// x(y), y(x)3960// TODO: implement -Wuninitialized and fold this into that framework.3961static void DiagnoseUninitializedFields(3962Sema &SemaRef, const CXXConstructorDecl *Constructor) {39633964if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,3965Constructor->getLocation())) {3966return;3967}39683969if (Constructor->isInvalidDecl())3970return;39713972const CXXRecordDecl *RD = Constructor->getParent();39733974if (RD->isDependentContext())3975return;39763977// Holds fields that are uninitialized.3978llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;39793980// At the beginning, all fields are uninitialized.3981for (auto *I : RD->decls()) {3982if (auto *FD = dyn_cast<FieldDecl>(I)) {3983UninitializedFields.insert(FD);3984} else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {3985UninitializedFields.insert(IFD->getAnonField());3986}3987}39883989llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;3990for (const auto &I : RD->bases())3991UninitializedBaseClasses.insert(I.getType().getCanonicalType());39923993if (UninitializedFields.empty() && UninitializedBaseClasses.empty())3994return;39953996UninitializedFieldVisitor UninitializedChecker(SemaRef,3997UninitializedFields,3998UninitializedBaseClasses);39994000for (const auto *FieldInit : Constructor->inits()) {4001if (UninitializedFields.empty() && UninitializedBaseClasses.empty())4002break;40034004Expr *InitExpr = FieldInit->getInit();4005if (!InitExpr)4006continue;40074008if (CXXDefaultInitExpr *Default =4009dyn_cast<CXXDefaultInitExpr>(InitExpr)) {4010InitExpr = Default->getExpr();4011if (!InitExpr)4012continue;4013// In class initializers will point to the constructor.4014UninitializedChecker.CheckInitializer(InitExpr, Constructor,4015FieldInit->getAnyMember(),4016FieldInit->getBaseClass());4017} else {4018UninitializedChecker.CheckInitializer(InitExpr, nullptr,4019FieldInit->getAnyMember(),4020FieldInit->getBaseClass());4021}4022}4023}4024} // namespace40254026void Sema::ActOnStartCXXInClassMemberInitializer() {4027// Create a synthetic function scope to represent the call to the constructor4028// that notionally surrounds a use of this initializer.4029PushFunctionScope();4030}40314032void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {4033if (!D.isFunctionDeclarator())4034return;4035auto &FTI = D.getFunctionTypeInfo();4036if (!FTI.Params)4037return;4038for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,4039FTI.NumParams)) {4040auto *ParamDecl = cast<NamedDecl>(Param.Param);4041if (ParamDecl->getDeclName())4042PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);4043}4044}40454046ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {4047return ActOnRequiresClause(ConstraintExpr);4048}40494050ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {4051if (ConstraintExpr.isInvalid())4052return ExprError();40534054ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);4055if (ConstraintExpr.isInvalid())4056return ExprError();40574058if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),4059UPPC_RequiresClause))4060return ExprError();40614062return ConstraintExpr;4063}40644065ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,4066Expr *InitExpr,4067SourceLocation InitLoc) {4068InitializedEntity Entity =4069InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);4070InitializationKind Kind =4071FD->getInClassInitStyle() == ICIS_ListInit4072? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),4073InitExpr->getBeginLoc(),4074InitExpr->getEndLoc())4075: InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);4076InitializationSequence Seq(*this, Entity, Kind, InitExpr);4077return Seq.Perform(*this, Entity, Kind, InitExpr);4078}40794080void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,4081SourceLocation InitLoc,4082Expr *InitExpr) {4083// Pop the notional constructor scope we created earlier.4084PopFunctionScopeInfo(nullptr, D);40854086FieldDecl *FD = dyn_cast<FieldDecl>(D);4087assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&4088"must set init style when field is created");40894090if (!InitExpr) {4091D->setInvalidDecl();4092if (FD)4093FD->removeInClassInitializer();4094return;4095}40964097if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {4098FD->setInvalidDecl();4099FD->removeInClassInitializer();4100return;4101}41024103ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,4104/*RecoverUncorrectedTypos=*/true);4105assert(Init.isUsable() && "Init should at least have a RecoveryExpr");4106if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {4107Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);4108// C++11 [class.base.init]p7:4109// The initialization of each base and member constitutes a4110// full-expression.4111if (!Init.isInvalid())4112Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);4113if (Init.isInvalid()) {4114FD->setInvalidDecl();4115return;4116}4117}41184119FD->setInClassInitializer(Init.get());4120}41214122/// Find the direct and/or virtual base specifiers that4123/// correspond to the given base type, for use in base initialization4124/// within a constructor.4125static bool FindBaseInitializer(Sema &SemaRef,4126CXXRecordDecl *ClassDecl,4127QualType BaseType,4128const CXXBaseSpecifier *&DirectBaseSpec,4129const CXXBaseSpecifier *&VirtualBaseSpec) {4130// First, check for a direct base class.4131DirectBaseSpec = nullptr;4132for (const auto &Base : ClassDecl->bases()) {4133if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {4134// We found a direct base of this type. That's what we're4135// initializing.4136DirectBaseSpec = &Base;4137break;4138}4139}41404141// Check for a virtual base class.4142// FIXME: We might be able to short-circuit this if we know in advance that4143// there are no virtual bases.4144VirtualBaseSpec = nullptr;4145if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {4146// We haven't found a base yet; search the class hierarchy for a4147// virtual base class.4148CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,4149/*DetectVirtual=*/false);4150if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),4151SemaRef.Context.getTypeDeclType(ClassDecl),4152BaseType, Paths)) {4153for (CXXBasePaths::paths_iterator Path = Paths.begin();4154Path != Paths.end(); ++Path) {4155if (Path->back().Base->isVirtual()) {4156VirtualBaseSpec = Path->back().Base;4157break;4158}4159}4160}4161}41624163return DirectBaseSpec || VirtualBaseSpec;4164}41654166MemInitResult4167Sema::ActOnMemInitializer(Decl *ConstructorD,4168Scope *S,4169CXXScopeSpec &SS,4170IdentifierInfo *MemberOrBase,4171ParsedType TemplateTypeTy,4172const DeclSpec &DS,4173SourceLocation IdLoc,4174Expr *InitList,4175SourceLocation EllipsisLoc) {4176return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,4177DS, IdLoc, InitList,4178EllipsisLoc);4179}41804181MemInitResult4182Sema::ActOnMemInitializer(Decl *ConstructorD,4183Scope *S,4184CXXScopeSpec &SS,4185IdentifierInfo *MemberOrBase,4186ParsedType TemplateTypeTy,4187const DeclSpec &DS,4188SourceLocation IdLoc,4189SourceLocation LParenLoc,4190ArrayRef<Expr *> Args,4191SourceLocation RParenLoc,4192SourceLocation EllipsisLoc) {4193Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);4194return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,4195DS, IdLoc, List, EllipsisLoc);4196}41974198namespace {41994200// Callback to only accept typo corrections that can be a valid C++ member4201// initializer: either a non-static field member or a base class.4202class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {4203public:4204explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)4205: ClassDecl(ClassDecl) {}42064207bool ValidateCandidate(const TypoCorrection &candidate) override {4208if (NamedDecl *ND = candidate.getCorrectionDecl()) {4209if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))4210return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);4211return isa<TypeDecl>(ND);4212}4213return false;4214}42154216std::unique_ptr<CorrectionCandidateCallback> clone() override {4217return std::make_unique<MemInitializerValidatorCCC>(*this);4218}42194220private:4221CXXRecordDecl *ClassDecl;4222};42234224}42254226bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,4227RecordDecl *ClassDecl,4228const IdentifierInfo *Name) {4229DeclContextLookupResult Result = ClassDecl->lookup(Name);4230DeclContextLookupResult::iterator Found =4231llvm::find_if(Result, [this](const NamedDecl *Elem) {4232return isa<FieldDecl, IndirectFieldDecl>(Elem) &&4233Elem->isPlaceholderVar(getLangOpts());4234});4235// We did not find a placeholder variable4236if (Found == Result.end())4237return false;4238Diag(Loc, diag::err_using_placeholder_variable) << Name;4239for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {4240const NamedDecl *ND = *It;4241if (ND->getDeclContext() != ND->getDeclContext())4242break;4243if (isa<FieldDecl, IndirectFieldDecl>(ND) &&4244ND->isPlaceholderVar(getLangOpts()))4245Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;4246}4247return true;4248}42494250ValueDecl *4251Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,4252const IdentifierInfo *MemberOrBase) {4253ValueDecl *ND = nullptr;4254for (auto *D : ClassDecl->lookup(MemberOrBase)) {4255if (isa<FieldDecl, IndirectFieldDecl>(D)) {4256bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());4257if (ND) {4258if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())4259return nullptr;4260break;4261}4262if (!IsPlaceholder)4263return cast<ValueDecl>(D);4264ND = cast<ValueDecl>(D);4265}4266}4267return ND;4268}42694270ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,4271CXXScopeSpec &SS,4272ParsedType TemplateTypeTy,4273IdentifierInfo *MemberOrBase) {4274if (SS.getScopeRep() || TemplateTypeTy)4275return nullptr;4276return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);4277}42784279MemInitResult4280Sema::BuildMemInitializer(Decl *ConstructorD,4281Scope *S,4282CXXScopeSpec &SS,4283IdentifierInfo *MemberOrBase,4284ParsedType TemplateTypeTy,4285const DeclSpec &DS,4286SourceLocation IdLoc,4287Expr *Init,4288SourceLocation EllipsisLoc) {4289ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,4290/*RecoverUncorrectedTypos=*/true);4291if (!Res.isUsable())4292return true;4293Init = Res.get();42944295if (!ConstructorD)4296return true;42974298AdjustDeclIfTemplate(ConstructorD);42994300CXXConstructorDecl *Constructor4301= dyn_cast<CXXConstructorDecl>(ConstructorD);4302if (!Constructor) {4303// The user wrote a constructor initializer on a function that is4304// not a C++ constructor. Ignore the error for now, because we may4305// have more member initializers coming; we'll diagnose it just4306// once in ActOnMemInitializers.4307return true;4308}43094310CXXRecordDecl *ClassDecl = Constructor->getParent();43114312// C++ [class.base.init]p2:4313// Names in a mem-initializer-id are looked up in the scope of the4314// constructor's class and, if not found in that scope, are looked4315// up in the scope containing the constructor's definition.4316// [Note: if the constructor's class contains a member with the4317// same name as a direct or virtual base class of the class, a4318// mem-initializer-id naming the member or base class and composed4319// of a single identifier refers to the class member. A4320// mem-initializer-id for the hidden base class may be specified4321// using a qualified name. ]43224323// Look for a member, first.4324if (ValueDecl *Member = tryLookupCtorInitMemberDecl(4325ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {4326if (EllipsisLoc.isValid())4327Diag(EllipsisLoc, diag::err_pack_expansion_member_init)4328<< MemberOrBase4329<< SourceRange(IdLoc, Init->getSourceRange().getEnd());43304331return BuildMemberInitializer(Member, Init, IdLoc);4332}4333// It didn't name a member, so see if it names a class.4334QualType BaseType;4335TypeSourceInfo *TInfo = nullptr;43364337if (TemplateTypeTy) {4338BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);4339if (BaseType.isNull())4340return true;4341} else if (DS.getTypeSpecType() == TST_decltype) {4342BaseType = BuildDecltypeType(DS.getRepAsExpr());4343} else if (DS.getTypeSpecType() == TST_decltype_auto) {4344Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);4345return true;4346} else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {4347BaseType =4348BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),4349DS.getBeginLoc(), DS.getEllipsisLoc());4350} else {4351LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);4352LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());43534354TypeDecl *TyD = R.getAsSingle<TypeDecl>();4355if (!TyD) {4356if (R.isAmbiguous()) return true;43574358// We don't want access-control diagnostics here.4359R.suppressDiagnostics();43604361if (SS.isSet() && isDependentScopeSpecifier(SS)) {4362bool NotUnknownSpecialization = false;4363DeclContext *DC = computeDeclContext(SS, false);4364if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))4365NotUnknownSpecialization = !Record->hasAnyDependentBases();43664367if (!NotUnknownSpecialization) {4368// When the scope specifier can refer to a member of an unknown4369// specialization, we take it as a type name.4370BaseType = CheckTypenameType(4371ElaboratedTypeKeyword::None, SourceLocation(),4372SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);4373if (BaseType.isNull())4374return true;43754376TInfo = Context.CreateTypeSourceInfo(BaseType);4377DependentNameTypeLoc TL =4378TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();4379if (!TL.isNull()) {4380TL.setNameLoc(IdLoc);4381TL.setElaboratedKeywordLoc(SourceLocation());4382TL.setQualifierLoc(SS.getWithLocInContext(Context));4383}43844385R.clear();4386R.setLookupName(MemberOrBase);4387}4388}43894390if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {4391if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {4392auto *TempSpec = cast<TemplateSpecializationType>(4393UnqualifiedBase->getInjectedClassNameSpecialization());4394TemplateName TN = TempSpec->getTemplateName();4395for (auto const &Base : ClassDecl->bases()) {4396auto BaseTemplate =4397Base.getType()->getAs<TemplateSpecializationType>();4398if (BaseTemplate && Context.hasSameTemplateName(4399BaseTemplate->getTemplateName(), TN)) {4400Diag(IdLoc, diag::ext_unqualified_base_class)4401<< SourceRange(IdLoc, Init->getSourceRange().getEnd());4402BaseType = Base.getType();4403break;4404}4405}4406}4407}44084409// If no results were found, try to correct typos.4410TypoCorrection Corr;4411MemInitializerValidatorCCC CCC(ClassDecl);4412if (R.empty() && BaseType.isNull() &&4413(Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,4414CCC, CTK_ErrorRecovery, ClassDecl))) {4415if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {4416// We have found a non-static data member with a similar4417// name to what was typed; complain and initialize that4418// member.4419diagnoseTypo(Corr,4420PDiag(diag::err_mem_init_not_member_or_class_suggest)4421<< MemberOrBase << true);4422return BuildMemberInitializer(Member, Init, IdLoc);4423} else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {4424const CXXBaseSpecifier *DirectBaseSpec;4425const CXXBaseSpecifier *VirtualBaseSpec;4426if (FindBaseInitializer(*this, ClassDecl,4427Context.getTypeDeclType(Type),4428DirectBaseSpec, VirtualBaseSpec)) {4429// We have found a direct or virtual base class with a4430// similar name to what was typed; complain and initialize4431// that base class.4432diagnoseTypo(Corr,4433PDiag(diag::err_mem_init_not_member_or_class_suggest)4434<< MemberOrBase << false,4435PDiag() /*Suppress note, we provide our own.*/);44364437const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec4438: VirtualBaseSpec;4439Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)4440<< BaseSpec->getType() << BaseSpec->getSourceRange();44414442TyD = Type;4443}4444}4445}44464447if (!TyD && BaseType.isNull()) {4448Diag(IdLoc, diag::err_mem_init_not_member_or_class)4449<< MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());4450return true;4451}4452}44534454if (BaseType.isNull()) {4455BaseType = getElaboratedType(ElaboratedTypeKeyword::None, SS,4456Context.getTypeDeclType(TyD));4457MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);4458TInfo = Context.CreateTypeSourceInfo(BaseType);4459ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();4460TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);4461TL.setElaboratedKeywordLoc(SourceLocation());4462TL.setQualifierLoc(SS.getWithLocInContext(Context));4463}4464}44654466if (!TInfo)4467TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);44684469return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);4470}44714472MemInitResult4473Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,4474SourceLocation IdLoc) {4475FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);4476IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);4477assert((DirectMember || IndirectMember) &&4478"Member must be a FieldDecl or IndirectFieldDecl");44794480if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))4481return true;44824483if (Member->isInvalidDecl())4484return true;44854486MultiExprArg Args;4487if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4488Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4489} else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {4490Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());4491} else {4492// Template instantiation doesn't reconstruct ParenListExprs for us.4493Args = Init;4494}44954496SourceRange InitRange = Init->getSourceRange();44974498if (Member->getType()->isDependentType() || Init->isTypeDependent()) {4499// Can't check initialization for a member of dependent type or when4500// any of the arguments are type-dependent expressions.4501DiscardCleanupsInEvaluationContext();4502} else {4503bool InitList = false;4504if (isa<InitListExpr>(Init)) {4505InitList = true;4506Args = Init;4507}45084509// Initialize the member.4510InitializedEntity MemberEntity =4511DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)4512: InitializedEntity::InitializeMember(IndirectMember,4513nullptr);4514InitializationKind Kind =4515InitList ? InitializationKind::CreateDirectList(4516IdLoc, Init->getBeginLoc(), Init->getEndLoc())4517: InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),4518InitRange.getEnd());45194520InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);4521ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,4522nullptr);4523if (!MemberInit.isInvalid()) {4524// C++11 [class.base.init]p7:4525// The initialization of each base and member constitutes a4526// full-expression.4527MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),4528/*DiscardedValue*/ false);4529}45304531if (MemberInit.isInvalid()) {4532// Args were sensible expressions but we couldn't initialize the member4533// from them. Preserve them in a RecoveryExpr instead.4534Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,4535Member->getType())4536.get();4537if (!Init)4538return true;4539} else {4540Init = MemberInit.get();4541}4542}45434544if (DirectMember) {4545return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,4546InitRange.getBegin(), Init,4547InitRange.getEnd());4548} else {4549return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,4550InitRange.getBegin(), Init,4551InitRange.getEnd());4552}4553}45544555MemInitResult4556Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,4557CXXRecordDecl *ClassDecl) {4558SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();4559if (!LangOpts.CPlusPlus11)4560return Diag(NameLoc, diag::err_delegating_ctor)4561<< TInfo->getTypeLoc().getSourceRange();4562Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);45634564bool InitList = true;4565MultiExprArg Args = Init;4566if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4567InitList = false;4568Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4569}45704571SourceRange InitRange = Init->getSourceRange();4572// Initialize the object.4573InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(4574QualType(ClassDecl->getTypeForDecl(), 0));4575InitializationKind Kind =4576InitList ? InitializationKind::CreateDirectList(4577NameLoc, Init->getBeginLoc(), Init->getEndLoc())4578: InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),4579InitRange.getEnd());4580InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);4581ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,4582Args, nullptr);4583if (!DelegationInit.isInvalid()) {4584assert((DelegationInit.get()->containsErrors() ||4585cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&4586"Delegating constructor with no target?");45874588// C++11 [class.base.init]p7:4589// The initialization of each base and member constitutes a4590// full-expression.4591DelegationInit = ActOnFinishFullExpr(4592DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);4593}45944595if (DelegationInit.isInvalid()) {4596DelegationInit =4597CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,4598QualType(ClassDecl->getTypeForDecl(), 0));4599if (DelegationInit.isInvalid())4600return true;4601} else {4602// If we are in a dependent context, template instantiation will4603// perform this type-checking again. Just save the arguments that we4604// received in a ParenListExpr.4605// FIXME: This isn't quite ideal, since our ASTs don't capture all4606// of the information that we have about the base4607// initializer. However, deconstructing the ASTs is a dicey process,4608// and this approach is far more likely to get the corner cases right.4609if (CurContext->isDependentContext())4610DelegationInit = Init;4611}46124613return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),4614DelegationInit.getAs<Expr>(),4615InitRange.getEnd());4616}46174618MemInitResult4619Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,4620Expr *Init, CXXRecordDecl *ClassDecl,4621SourceLocation EllipsisLoc) {4622SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();46234624if (!BaseType->isDependentType() && !BaseType->isRecordType())4625return Diag(BaseLoc, diag::err_base_init_does_not_name_class)4626<< BaseType << BaseTInfo->getTypeLoc().getSourceRange();46274628// C++ [class.base.init]p2:4629// [...] Unless the mem-initializer-id names a nonstatic data4630// member of the constructor's class or a direct or virtual base4631// of that class, the mem-initializer is ill-formed. A4632// mem-initializer-list can initialize a base class using any4633// name that denotes that base class type.46344635// We can store the initializers in "as-written" form and delay analysis until4636// instantiation if the constructor is dependent. But not for dependent4637// (broken) code in a non-template! SetCtorInitializers does not expect this.4638bool Dependent = CurContext->isDependentContext() &&4639(BaseType->isDependentType() || Init->isTypeDependent());46404641SourceRange InitRange = Init->getSourceRange();4642if (EllipsisLoc.isValid()) {4643// This is a pack expansion.4644if (!BaseType->containsUnexpandedParameterPack()) {4645Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)4646<< SourceRange(BaseLoc, InitRange.getEnd());46474648EllipsisLoc = SourceLocation();4649}4650} else {4651// Check for any unexpanded parameter packs.4652if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))4653return true;46544655if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))4656return true;4657}46584659// Check for direct and virtual base classes.4660const CXXBaseSpecifier *DirectBaseSpec = nullptr;4661const CXXBaseSpecifier *VirtualBaseSpec = nullptr;4662if (!Dependent) {4663if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),4664BaseType))4665return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);46664667FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,4668VirtualBaseSpec);46694670// C++ [base.class.init]p2:4671// Unless the mem-initializer-id names a nonstatic data member of the4672// constructor's class or a direct or virtual base of that class, the4673// mem-initializer is ill-formed.4674if (!DirectBaseSpec && !VirtualBaseSpec) {4675// If the class has any dependent bases, then it's possible that4676// one of those types will resolve to the same type as4677// BaseType. Therefore, just treat this as a dependent base4678// class initialization. FIXME: Should we try to check the4679// initialization anyway? It seems odd.4680if (ClassDecl->hasAnyDependentBases())4681Dependent = true;4682else4683return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)4684<< BaseType << Context.getTypeDeclType(ClassDecl)4685<< BaseTInfo->getTypeLoc().getSourceRange();4686}4687}46884689if (Dependent) {4690DiscardCleanupsInEvaluationContext();46914692return new (Context) CXXCtorInitializer(Context, BaseTInfo,4693/*IsVirtual=*/false,4694InitRange.getBegin(), Init,4695InitRange.getEnd(), EllipsisLoc);4696}46974698// C++ [base.class.init]p2:4699// If a mem-initializer-id is ambiguous because it designates both4700// a direct non-virtual base class and an inherited virtual base4701// class, the mem-initializer is ill-formed.4702if (DirectBaseSpec && VirtualBaseSpec)4703return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)4704<< BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();47054706const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;4707if (!BaseSpec)4708BaseSpec = VirtualBaseSpec;47094710// Initialize the base.4711bool InitList = true;4712MultiExprArg Args = Init;4713if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4714InitList = false;4715Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4716}47174718InitializedEntity BaseEntity =4719InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);4720InitializationKind Kind =4721InitList ? InitializationKind::CreateDirectList(BaseLoc)4722: InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),4723InitRange.getEnd());4724InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);4725ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);4726if (!BaseInit.isInvalid()) {4727// C++11 [class.base.init]p7:4728// The initialization of each base and member constitutes a4729// full-expression.4730BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),4731/*DiscardedValue*/ false);4732}47334734if (BaseInit.isInvalid()) {4735BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),4736Args, BaseType);4737if (BaseInit.isInvalid())4738return true;4739} else {4740// If we are in a dependent context, template instantiation will4741// perform this type-checking again. Just save the arguments that we4742// received in a ParenListExpr.4743// FIXME: This isn't quite ideal, since our ASTs don't capture all4744// of the information that we have about the base4745// initializer. However, deconstructing the ASTs is a dicey process,4746// and this approach is far more likely to get the corner cases right.4747if (CurContext->isDependentContext())4748BaseInit = Init;4749}47504751return new (Context) CXXCtorInitializer(Context, BaseTInfo,4752BaseSpec->isVirtual(),4753InitRange.getBegin(),4754BaseInit.getAs<Expr>(),4755InitRange.getEnd(), EllipsisLoc);4756}47574758// Create a static_cast\<T&&>(expr).4759static Expr *CastForMoving(Sema &SemaRef, Expr *E) {4760QualType TargetType =4761SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,4762SourceLocation(), DeclarationName());4763SourceLocation ExprLoc = E->getBeginLoc();4764TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(4765TargetType, ExprLoc);47664767return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,4768SourceRange(ExprLoc, ExprLoc),4769E->getSourceRange()).get();4770}47714772/// ImplicitInitializerKind - How an implicit base or member initializer should4773/// initialize its base or member.4774enum ImplicitInitializerKind {4775IIK_Default,4776IIK_Copy,4777IIK_Move,4778IIK_Inherit4779};47804781static bool4782BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,4783ImplicitInitializerKind ImplicitInitKind,4784CXXBaseSpecifier *BaseSpec,4785bool IsInheritedVirtualBase,4786CXXCtorInitializer *&CXXBaseInit) {4787InitializedEntity InitEntity4788= InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,4789IsInheritedVirtualBase);47904791ExprResult BaseInit;47924793switch (ImplicitInitKind) {4794case IIK_Inherit:4795case IIK_Default: {4796InitializationKind InitKind4797= InitializationKind::CreateDefault(Constructor->getLocation());4798InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);4799BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);4800break;4801}48024803case IIK_Move:4804case IIK_Copy: {4805bool Moving = ImplicitInitKind == IIK_Move;4806ParmVarDecl *Param = Constructor->getParamDecl(0);4807QualType ParamType = Param->getType().getNonReferenceType();48084809Expr *CopyCtorArg =4810DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),4811SourceLocation(), Param, false,4812Constructor->getLocation(), ParamType,4813VK_LValue, nullptr);48144815SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));48164817// Cast to the base class to avoid ambiguities.4818QualType ArgTy =4819SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),4820ParamType.getQualifiers());48214822if (Moving) {4823CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);4824}48254826CXXCastPath BasePath;4827BasePath.push_back(BaseSpec);4828CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,4829CK_UncheckedDerivedToBase,4830Moving ? VK_XValue : VK_LValue,4831&BasePath).get();48324833InitializationKind InitKind4834= InitializationKind::CreateDirect(Constructor->getLocation(),4835SourceLocation(), SourceLocation());4836InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);4837BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);4838break;4839}4840}48414842BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);4843if (BaseInit.isInvalid())4844return true;48454846CXXBaseInit =4847new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,4848SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),4849SourceLocation()),4850BaseSpec->isVirtual(),4851SourceLocation(),4852BaseInit.getAs<Expr>(),4853SourceLocation(),4854SourceLocation());48554856return false;4857}48584859static bool RefersToRValueRef(Expr *MemRef) {4860ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();4861return Referenced->getType()->isRValueReferenceType();4862}48634864static bool4865BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,4866ImplicitInitializerKind ImplicitInitKind,4867FieldDecl *Field, IndirectFieldDecl *Indirect,4868CXXCtorInitializer *&CXXMemberInit) {4869if (Field->isInvalidDecl())4870return true;48714872SourceLocation Loc = Constructor->getLocation();48734874if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {4875bool Moving = ImplicitInitKind == IIK_Move;4876ParmVarDecl *Param = Constructor->getParamDecl(0);4877QualType ParamType = Param->getType().getNonReferenceType();48784879// Suppress copying zero-width bitfields.4880if (Field->isZeroLengthBitField(SemaRef.Context))4881return false;48824883Expr *MemberExprBase =4884DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),4885SourceLocation(), Param, false,4886Loc, ParamType, VK_LValue, nullptr);48874888SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));48894890if (Moving) {4891MemberExprBase = CastForMoving(SemaRef, MemberExprBase);4892}48934894// Build a reference to this field within the parameter.4895CXXScopeSpec SS;4896LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,4897Sema::LookupMemberName);4898MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)4899: cast<ValueDecl>(Field), AS_public);4900MemberLookup.resolveKind();4901ExprResult CtorArg4902= SemaRef.BuildMemberReferenceExpr(MemberExprBase,4903ParamType, Loc,4904/*IsArrow=*/false,4905SS,4906/*TemplateKWLoc=*/SourceLocation(),4907/*FirstQualifierInScope=*/nullptr,4908MemberLookup,4909/*TemplateArgs=*/nullptr,4910/*S*/nullptr);4911if (CtorArg.isInvalid())4912return true;49134914// C++11 [class.copy]p15:4915// - if a member m has rvalue reference type T&&, it is direct-initialized4916// with static_cast<T&&>(x.m);4917if (RefersToRValueRef(CtorArg.get())) {4918CtorArg = CastForMoving(SemaRef, CtorArg.get());4919}49204921InitializedEntity Entity =4922Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,4923/*Implicit*/ true)4924: InitializedEntity::InitializeMember(Field, nullptr,4925/*Implicit*/ true);49264927// Direct-initialize to use the copy constructor.4928InitializationKind InitKind =4929InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());49304931Expr *CtorArgE = CtorArg.getAs<Expr>();4932InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);4933ExprResult MemberInit =4934InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));4935MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);4936if (MemberInit.isInvalid())4937return true;49384939if (Indirect)4940CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(4941SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);4942else4943CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(4944SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);4945return false;4946}49474948assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&4949"Unhandled implicit init kind!");49504951QualType FieldBaseElementType =4952SemaRef.Context.getBaseElementType(Field->getType());49534954if (FieldBaseElementType->isRecordType()) {4955InitializedEntity InitEntity =4956Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,4957/*Implicit*/ true)4958: InitializedEntity::InitializeMember(Field, nullptr,4959/*Implicit*/ true);4960InitializationKind InitKind =4961InitializationKind::CreateDefault(Loc);49624963InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);4964ExprResult MemberInit =4965InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);49664967MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);4968if (MemberInit.isInvalid())4969return true;49704971if (Indirect)4972CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,4973Indirect, Loc,4974Loc,4975MemberInit.get(),4976Loc);4977else4978CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,4979Field, Loc, Loc,4980MemberInit.get(),4981Loc);4982return false;4983}49844985if (!Field->getParent()->isUnion()) {4986if (FieldBaseElementType->isReferenceType()) {4987SemaRef.Diag(Constructor->getLocation(),4988diag::err_uninitialized_member_in_ctor)4989<< (int)Constructor->isImplicit()4990<< SemaRef.Context.getTagDeclType(Constructor->getParent())4991<< 0 << Field->getDeclName();4992SemaRef.Diag(Field->getLocation(), diag::note_declared_at);4993return true;4994}49954996if (FieldBaseElementType.isConstQualified()) {4997SemaRef.Diag(Constructor->getLocation(),4998diag::err_uninitialized_member_in_ctor)4999<< (int)Constructor->isImplicit()5000<< SemaRef.Context.getTagDeclType(Constructor->getParent())5001<< 1 << Field->getDeclName();5002SemaRef.Diag(Field->getLocation(), diag::note_declared_at);5003return true;5004}5005}50065007if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {5008// ARC and Weak:5009// Default-initialize Objective-C pointers to NULL.5010CXXMemberInit5011= new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,5012Loc, Loc,5013new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),5014Loc);5015return false;5016}50175018// Nothing to initialize.5019CXXMemberInit = nullptr;5020return false;5021}50225023namespace {5024struct BaseAndFieldInfo {5025Sema &S;5026CXXConstructorDecl *Ctor;5027bool AnyErrorsInInits;5028ImplicitInitializerKind IIK;5029llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;5030SmallVector<CXXCtorInitializer*, 8> AllToInit;5031llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;50325033BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)5034: S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {5035bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();5036if (Ctor->getInheritedConstructor())5037IIK = IIK_Inherit;5038else if (Generated && Ctor->isCopyConstructor())5039IIK = IIK_Copy;5040else if (Generated && Ctor->isMoveConstructor())5041IIK = IIK_Move;5042else5043IIK = IIK_Default;5044}50455046bool isImplicitCopyOrMove() const {5047switch (IIK) {5048case IIK_Copy:5049case IIK_Move:5050return true;50515052case IIK_Default:5053case IIK_Inherit:5054return false;5055}50565057llvm_unreachable("Invalid ImplicitInitializerKind!");5058}50595060bool addFieldInitializer(CXXCtorInitializer *Init) {5061AllToInit.push_back(Init);50625063// Check whether this initializer makes the field "used".5064if (Init->getInit()->HasSideEffects(S.Context))5065S.UnusedPrivateFields.remove(Init->getAnyMember());50665067return false;5068}50695070bool isInactiveUnionMember(FieldDecl *Field) {5071RecordDecl *Record = Field->getParent();5072if (!Record->isUnion())5073return false;50745075if (FieldDecl *Active =5076ActiveUnionMember.lookup(Record->getCanonicalDecl()))5077return Active != Field->getCanonicalDecl();50785079// In an implicit copy or move constructor, ignore any in-class initializer.5080if (isImplicitCopyOrMove())5081return true;50825083// If there's no explicit initialization, the field is active only if it5084// has an in-class initializer...5085if (Field->hasInClassInitializer())5086return false;5087// ... or it's an anonymous struct or union whose class has an in-class5088// initializer.5089if (!Field->isAnonymousStructOrUnion())5090return true;5091CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();5092return !FieldRD->hasInClassInitializer();5093}50945095/// Determine whether the given field is, or is within, a union member5096/// that is inactive (because there was an initializer given for a different5097/// member of the union, or because the union was not initialized at all).5098bool isWithinInactiveUnionMember(FieldDecl *Field,5099IndirectFieldDecl *Indirect) {5100if (!Indirect)5101return isInactiveUnionMember(Field);51025103for (auto *C : Indirect->chain()) {5104FieldDecl *Field = dyn_cast<FieldDecl>(C);5105if (Field && isInactiveUnionMember(Field))5106return true;5107}5108return false;5109}5110};5111}51125113/// Determine whether the given type is an incomplete or zero-lenfgth5114/// array type.5115static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {5116if (T->isIncompleteArrayType())5117return true;51185119while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {5120if (ArrayT->isZeroSize())5121return true;51225123T = ArrayT->getElementType();5124}51255126return false;5127}51285129static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,5130FieldDecl *Field,5131IndirectFieldDecl *Indirect = nullptr) {5132if (Field->isInvalidDecl())5133return false;51345135// Overwhelmingly common case: we have a direct initializer for this field.5136if (CXXCtorInitializer *Init =5137Info.AllBaseFields.lookup(Field->getCanonicalDecl()))5138return Info.addFieldInitializer(Init);51395140// C++11 [class.base.init]p8:5141// if the entity is a non-static data member that has a5142// brace-or-equal-initializer and either5143// -- the constructor's class is a union and no other variant member of that5144// union is designated by a mem-initializer-id or5145// -- the constructor's class is not a union, and, if the entity is a member5146// of an anonymous union, no other member of that union is designated by5147// a mem-initializer-id,5148// the entity is initialized as specified in [dcl.init].5149//5150// We also apply the same rules to handle anonymous structs within anonymous5151// unions.5152if (Info.isWithinInactiveUnionMember(Field, Indirect))5153return false;51545155if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {5156ExprResult DIE =5157SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);5158if (DIE.isInvalid())5159return true;51605161auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);5162SemaRef.checkInitializerLifetime(Entity, DIE.get());51635164CXXCtorInitializer *Init;5165if (Indirect)5166Init = new (SemaRef.Context)5167CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),5168SourceLocation(), DIE.get(), SourceLocation());5169else5170Init = new (SemaRef.Context)5171CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),5172SourceLocation(), DIE.get(), SourceLocation());5173return Info.addFieldInitializer(Init);5174}51755176// Don't initialize incomplete or zero-length arrays.5177if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))5178return false;51795180// Don't try to build an implicit initializer if there were semantic5181// errors in any of the initializers (and therefore we might be5182// missing some that the user actually wrote).5183if (Info.AnyErrorsInInits)5184return false;51855186CXXCtorInitializer *Init = nullptr;5187if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,5188Indirect, Init))5189return true;51905191if (!Init)5192return false;51935194return Info.addFieldInitializer(Init);5195}51965197bool5198Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,5199CXXCtorInitializer *Initializer) {5200assert(Initializer->isDelegatingInitializer());5201Constructor->setNumCtorInitializers(1);5202CXXCtorInitializer **initializer =5203new (Context) CXXCtorInitializer*[1];5204memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));5205Constructor->setCtorInitializers(initializer);52065207if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {5208MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);5209DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());5210}52115212DelegatingCtorDecls.push_back(Constructor);52135214DiagnoseUninitializedFields(*this, Constructor);52155216return false;5217}52185219bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,5220ArrayRef<CXXCtorInitializer *> Initializers) {5221if (Constructor->isDependentContext()) {5222// Just store the initializers as written, they will be checked during5223// instantiation.5224if (!Initializers.empty()) {5225Constructor->setNumCtorInitializers(Initializers.size());5226CXXCtorInitializer **baseOrMemberInitializers =5227new (Context) CXXCtorInitializer*[Initializers.size()];5228memcpy(baseOrMemberInitializers, Initializers.data(),5229Initializers.size() * sizeof(CXXCtorInitializer*));5230Constructor->setCtorInitializers(baseOrMemberInitializers);5231}52325233// Let template instantiation know whether we had errors.5234if (AnyErrors)5235Constructor->setInvalidDecl();52365237return false;5238}52395240BaseAndFieldInfo Info(*this, Constructor, AnyErrors);52415242// We need to build the initializer AST according to order of construction5243// and not what user specified in the Initializers list.5244CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();5245if (!ClassDecl)5246return true;52475248bool HadError = false;52495250for (unsigned i = 0; i < Initializers.size(); i++) {5251CXXCtorInitializer *Member = Initializers[i];52525253if (Member->isBaseInitializer())5254Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;5255else {5256Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;52575258if (IndirectFieldDecl *F = Member->getIndirectMember()) {5259for (auto *C : F->chain()) {5260FieldDecl *FD = dyn_cast<FieldDecl>(C);5261if (FD && FD->getParent()->isUnion())5262Info.ActiveUnionMember.insert(std::make_pair(5263FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));5264}5265} else if (FieldDecl *FD = Member->getMember()) {5266if (FD->getParent()->isUnion())5267Info.ActiveUnionMember.insert(std::make_pair(5268FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));5269}5270}5271}52725273// Keep track of the direct virtual bases.5274llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;5275for (auto &I : ClassDecl->bases()) {5276if (I.isVirtual())5277DirectVBases.insert(&I);5278}52795280// Push virtual bases before others.5281for (auto &VBase : ClassDecl->vbases()) {5282if (CXXCtorInitializer *Value5283= Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {5284// [class.base.init]p7, per DR257:5285// A mem-initializer where the mem-initializer-id names a virtual base5286// class is ignored during execution of a constructor of any class that5287// is not the most derived class.5288if (ClassDecl->isAbstract()) {5289// FIXME: Provide a fixit to remove the base specifier. This requires5290// tracking the location of the associated comma for a base specifier.5291Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)5292<< VBase.getType() << ClassDecl;5293DiagnoseAbstractType(ClassDecl);5294}52955296Info.AllToInit.push_back(Value);5297} else if (!AnyErrors && !ClassDecl->isAbstract()) {5298// [class.base.init]p8, per DR257:5299// If a given [...] base class is not named by a mem-initializer-id5300// [...] and the entity is not a virtual base class of an abstract5301// class, then [...] the entity is default-initialized.5302bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);5303CXXCtorInitializer *CXXBaseInit;5304if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,5305&VBase, IsInheritedVirtualBase,5306CXXBaseInit)) {5307HadError = true;5308continue;5309}53105311Info.AllToInit.push_back(CXXBaseInit);5312}5313}53145315// Non-virtual bases.5316for (auto &Base : ClassDecl->bases()) {5317// Virtuals are in the virtual base list and already constructed.5318if (Base.isVirtual())5319continue;53205321if (CXXCtorInitializer *Value5322= Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {5323Info.AllToInit.push_back(Value);5324} else if (!AnyErrors) {5325CXXCtorInitializer *CXXBaseInit;5326if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,5327&Base, /*IsInheritedVirtualBase=*/false,5328CXXBaseInit)) {5329HadError = true;5330continue;5331}53325333Info.AllToInit.push_back(CXXBaseInit);5334}5335}53365337// Fields.5338for (auto *Mem : ClassDecl->decls()) {5339if (auto *F = dyn_cast<FieldDecl>(Mem)) {5340// C++ [class.bit]p2:5341// A declaration for a bit-field that omits the identifier declares an5342// unnamed bit-field. Unnamed bit-fields are not members and cannot be5343// initialized.5344if (F->isUnnamedBitField())5345continue;53465347// If we're not generating the implicit copy/move constructor, then we'll5348// handle anonymous struct/union fields based on their individual5349// indirect fields.5350if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())5351continue;53525353if (CollectFieldInitializer(*this, Info, F))5354HadError = true;5355continue;5356}53575358// Beyond this point, we only consider default initialization.5359if (Info.isImplicitCopyOrMove())5360continue;53615362if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {5363if (F->getType()->isIncompleteArrayType()) {5364assert(ClassDecl->hasFlexibleArrayMember() &&5365"Incomplete array type is not valid");5366continue;5367}53685369// Initialize each field of an anonymous struct individually.5370if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))5371HadError = true;53725373continue;5374}5375}53765377unsigned NumInitializers = Info.AllToInit.size();5378if (NumInitializers > 0) {5379Constructor->setNumCtorInitializers(NumInitializers);5380CXXCtorInitializer **baseOrMemberInitializers =5381new (Context) CXXCtorInitializer*[NumInitializers];5382memcpy(baseOrMemberInitializers, Info.AllToInit.data(),5383NumInitializers * sizeof(CXXCtorInitializer*));5384Constructor->setCtorInitializers(baseOrMemberInitializers);53855386// Constructors implicitly reference the base and member5387// destructors.5388MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),5389Constructor->getParent());5390}53915392return HadError;5393}53945395static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {5396if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {5397const RecordDecl *RD = RT->getDecl();5398if (RD->isAnonymousStructOrUnion()) {5399for (auto *Field : RD->fields())5400PopulateKeysForFields(Field, IdealInits);5401return;5402}5403}5404IdealInits.push_back(Field->getCanonicalDecl());5405}54065407static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {5408return Context.getCanonicalType(BaseType).getTypePtr();5409}54105411static const void *GetKeyForMember(ASTContext &Context,5412CXXCtorInitializer *Member) {5413if (!Member->isAnyMemberInitializer())5414return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));54155416return Member->getAnyMember()->getCanonicalDecl();5417}54185419static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,5420const CXXCtorInitializer *Previous,5421const CXXCtorInitializer *Current) {5422if (Previous->isAnyMemberInitializer())5423Diag << 0 << Previous->getAnyMember();5424else5425Diag << 1 << Previous->getTypeSourceInfo()->getType();54265427if (Current->isAnyMemberInitializer())5428Diag << 0 << Current->getAnyMember();5429else5430Diag << 1 << Current->getTypeSourceInfo()->getType();5431}54325433static void DiagnoseBaseOrMemInitializerOrder(5434Sema &SemaRef, const CXXConstructorDecl *Constructor,5435ArrayRef<CXXCtorInitializer *> Inits) {5436if (Constructor->getDeclContext()->isDependentContext())5437return;54385439// Don't check initializers order unless the warning is enabled at the5440// location of at least one initializer.5441bool ShouldCheckOrder = false;5442for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {5443CXXCtorInitializer *Init = Inits[InitIndex];5444if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,5445Init->getSourceLocation())) {5446ShouldCheckOrder = true;5447break;5448}5449}5450if (!ShouldCheckOrder)5451return;54525453// Build the list of bases and members in the order that they'll5454// actually be initialized. The explicit initializers should be in5455// this same order but may be missing things.5456SmallVector<const void*, 32> IdealInitKeys;54575458const CXXRecordDecl *ClassDecl = Constructor->getParent();54595460// 1. Virtual bases.5461for (const auto &VBase : ClassDecl->vbases())5462IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));54635464// 2. Non-virtual bases.5465for (const auto &Base : ClassDecl->bases()) {5466if (Base.isVirtual())5467continue;5468IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));5469}54705471// 3. Direct fields.5472for (auto *Field : ClassDecl->fields()) {5473if (Field->isUnnamedBitField())5474continue;54755476PopulateKeysForFields(Field, IdealInitKeys);5477}54785479unsigned NumIdealInits = IdealInitKeys.size();5480unsigned IdealIndex = 0;54815482// Track initializers that are in an incorrect order for either a warning or5483// note if multiple ones occur.5484SmallVector<unsigned> WarnIndexes;5485// Correlates the index of an initializer in the init-list to the index of5486// the field/base in the class.5487SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;54885489for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {5490const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);54915492// Scan forward to try to find this initializer in the idealized5493// initializers list.5494for (; IdealIndex != NumIdealInits; ++IdealIndex)5495if (InitKey == IdealInitKeys[IdealIndex])5496break;54975498// If we didn't find this initializer, it must be because we5499// scanned past it on a previous iteration. That can only5500// happen if we're out of order; emit a warning.5501if (IdealIndex == NumIdealInits && InitIndex) {5502WarnIndexes.push_back(InitIndex);55035504// Move back to the initializer's location in the ideal list.5505for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)5506if (InitKey == IdealInitKeys[IdealIndex])5507break;55085509assert(IdealIndex < NumIdealInits &&5510"initializer not found in initializer list");5511}5512CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);5513}55145515if (WarnIndexes.empty())5516return;55175518// Sort based on the ideal order, first in the pair.5519llvm::sort(CorrelatedInitOrder, llvm::less_first());55205521// Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to5522// emit the diagnostic before we can try adding notes.5523{5524Sema::SemaDiagnosticBuilder D = SemaRef.Diag(5525Inits[WarnIndexes.front() - 1]->getSourceLocation(),5526WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order5527: diag::warn_some_initializers_out_of_order);55285529for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {5530if (CorrelatedInitOrder[I].second == I)5531continue;5532// Ideally we would be using InsertFromRange here, but clang doesn't5533// appear to handle InsertFromRange correctly when the source range is5534// modified by another fix-it.5535D << FixItHint::CreateReplacement(5536Inits[I]->getSourceRange(),5537Lexer::getSourceText(5538CharSourceRange::getTokenRange(5539Inits[CorrelatedInitOrder[I].second]->getSourceRange()),5540SemaRef.getSourceManager(), SemaRef.getLangOpts()));5541}55425543// If there is only 1 item out of order, the warning expects the name and5544// type of each being added to it.5545if (WarnIndexes.size() == 1) {5546AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],5547Inits[WarnIndexes.front()]);5548return;5549}5550}5551// More than 1 item to warn, create notes letting the user know which ones5552// are bad.5553for (unsigned WarnIndex : WarnIndexes) {5554const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];5555auto D = SemaRef.Diag(PrevInit->getSourceLocation(),5556diag::note_initializer_out_of_order);5557AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);5558D << PrevInit->getSourceRange();5559}5560}55615562namespace {5563bool CheckRedundantInit(Sema &S,5564CXXCtorInitializer *Init,5565CXXCtorInitializer *&PrevInit) {5566if (!PrevInit) {5567PrevInit = Init;5568return false;5569}55705571if (FieldDecl *Field = Init->getAnyMember())5572S.Diag(Init->getSourceLocation(),5573diag::err_multiple_mem_initialization)5574<< Field->getDeclName()5575<< Init->getSourceRange();5576else {5577const Type *BaseClass = Init->getBaseClass();5578assert(BaseClass && "neither field nor base");5579S.Diag(Init->getSourceLocation(),5580diag::err_multiple_base_initialization)5581<< QualType(BaseClass, 0)5582<< Init->getSourceRange();5583}5584S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)5585<< 0 << PrevInit->getSourceRange();55865587return true;5588}55895590typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;5591typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;55925593bool CheckRedundantUnionInit(Sema &S,5594CXXCtorInitializer *Init,5595RedundantUnionMap &Unions) {5596FieldDecl *Field = Init->getAnyMember();5597RecordDecl *Parent = Field->getParent();5598NamedDecl *Child = Field;55995600while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {5601if (Parent->isUnion()) {5602UnionEntry &En = Unions[Parent];5603if (En.first && En.first != Child) {5604S.Diag(Init->getSourceLocation(),5605diag::err_multiple_mem_union_initialization)5606<< Field->getDeclName()5607<< Init->getSourceRange();5608S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)5609<< 0 << En.second->getSourceRange();5610return true;5611}5612if (!En.first) {5613En.first = Child;5614En.second = Init;5615}5616if (!Parent->isAnonymousStructOrUnion())5617return false;5618}56195620Child = Parent;5621Parent = cast<RecordDecl>(Parent->getDeclContext());5622}56235624return false;5625}5626} // namespace56275628void Sema::ActOnMemInitializers(Decl *ConstructorDecl,5629SourceLocation ColonLoc,5630ArrayRef<CXXCtorInitializer*> MemInits,5631bool AnyErrors) {5632if (!ConstructorDecl)5633return;56345635AdjustDeclIfTemplate(ConstructorDecl);56365637CXXConstructorDecl *Constructor5638= dyn_cast<CXXConstructorDecl>(ConstructorDecl);56395640if (!Constructor) {5641Diag(ColonLoc, diag::err_only_constructors_take_base_inits);5642return;5643}56445645// Mapping for the duplicate initializers check.5646// For member initializers, this is keyed with a FieldDecl*.5647// For base initializers, this is keyed with a Type*.5648llvm::DenseMap<const void *, CXXCtorInitializer *> Members;56495650// Mapping for the inconsistent anonymous-union initializers check.5651RedundantUnionMap MemberUnions;56525653bool HadError = false;5654for (unsigned i = 0; i < MemInits.size(); i++) {5655CXXCtorInitializer *Init = MemInits[i];56565657// Set the source order index.5658Init->setSourceOrder(i);56595660if (Init->isAnyMemberInitializer()) {5661const void *Key = GetKeyForMember(Context, Init);5662if (CheckRedundantInit(*this, Init, Members[Key]) ||5663CheckRedundantUnionInit(*this, Init, MemberUnions))5664HadError = true;5665} else if (Init->isBaseInitializer()) {5666const void *Key = GetKeyForMember(Context, Init);5667if (CheckRedundantInit(*this, Init, Members[Key]))5668HadError = true;5669} else {5670assert(Init->isDelegatingInitializer());5671// This must be the only initializer5672if (MemInits.size() != 1) {5673Diag(Init->getSourceLocation(),5674diag::err_delegating_initializer_alone)5675<< Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();5676// We will treat this as being the only initializer.5677}5678SetDelegatingInitializer(Constructor, MemInits[i]);5679// Return immediately as the initializer is set.5680return;5681}5682}56835684if (HadError)5685return;56865687DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);56885689SetCtorInitializers(Constructor, AnyErrors, MemInits);56905691DiagnoseUninitializedFields(*this, Constructor);5692}56935694void5695Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,5696CXXRecordDecl *ClassDecl) {5697// Ignore dependent contexts. Also ignore unions, since their members never5698// have destructors implicitly called.5699if (ClassDecl->isDependentContext() || ClassDecl->isUnion())5700return;57015702// FIXME: all the access-control diagnostics are positioned on the5703// field/base declaration. That's probably good; that said, the5704// user might reasonably want to know why the destructor is being5705// emitted, and we currently don't say.57065707// Non-static data members.5708for (auto *Field : ClassDecl->fields()) {5709if (Field->isInvalidDecl())5710continue;57115712// Don't destroy incomplete or zero-length arrays.5713if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))5714continue;57155716QualType FieldType = Context.getBaseElementType(Field->getType());57175718const RecordType* RT = FieldType->getAs<RecordType>();5719if (!RT)5720continue;57215722CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());5723if (FieldClassDecl->isInvalidDecl())5724continue;5725if (FieldClassDecl->hasIrrelevantDestructor())5726continue;5727// The destructor for an implicit anonymous union member is never invoked.5728if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())5729continue;57305731CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);5732// Dtor might still be missing, e.g because it's invalid.5733if (!Dtor)5734continue;5735CheckDestructorAccess(Field->getLocation(), Dtor,5736PDiag(diag::err_access_dtor_field)5737<< Field->getDeclName()5738<< FieldType);57395740MarkFunctionReferenced(Location, Dtor);5741DiagnoseUseOfDecl(Dtor, Location);5742}57435744// We only potentially invoke the destructors of potentially constructed5745// subobjects.5746bool VisitVirtualBases = !ClassDecl->isAbstract();57475748// If the destructor exists and has already been marked used in the MS ABI,5749// then virtual base destructors have already been checked and marked used.5750// Skip checking them again to avoid duplicate diagnostics.5751if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {5752CXXDestructorDecl *Dtor = ClassDecl->getDestructor();5753if (Dtor && Dtor->isUsed())5754VisitVirtualBases = false;5755}57565757llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;57585759// Bases.5760for (const auto &Base : ClassDecl->bases()) {5761const RecordType *RT = Base.getType()->getAs<RecordType>();5762if (!RT)5763continue;57645765// Remember direct virtual bases.5766if (Base.isVirtual()) {5767if (!VisitVirtualBases)5768continue;5769DirectVirtualBases.insert(RT);5770}57715772CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());5773// If our base class is invalid, we probably can't get its dtor anyway.5774if (BaseClassDecl->isInvalidDecl())5775continue;5776if (BaseClassDecl->hasIrrelevantDestructor())5777continue;57785779CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);5780// Dtor might still be missing, e.g because it's invalid.5781if (!Dtor)5782continue;57835784// FIXME: caret should be on the start of the class name5785CheckDestructorAccess(Base.getBeginLoc(), Dtor,5786PDiag(diag::err_access_dtor_base)5787<< Base.getType() << Base.getSourceRange(),5788Context.getTypeDeclType(ClassDecl));57895790MarkFunctionReferenced(Location, Dtor);5791DiagnoseUseOfDecl(Dtor, Location);5792}57935794if (VisitVirtualBases)5795MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,5796&DirectVirtualBases);5797}57985799void Sema::MarkVirtualBaseDestructorsReferenced(5800SourceLocation Location, CXXRecordDecl *ClassDecl,5801llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {5802// Virtual bases.5803for (const auto &VBase : ClassDecl->vbases()) {5804// Bases are always records in a well-formed non-dependent class.5805const RecordType *RT = VBase.getType()->castAs<RecordType>();58065807// Ignore already visited direct virtual bases.5808if (DirectVirtualBases && DirectVirtualBases->count(RT))5809continue;58105811CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());5812// If our base class is invalid, we probably can't get its dtor anyway.5813if (BaseClassDecl->isInvalidDecl())5814continue;5815if (BaseClassDecl->hasIrrelevantDestructor())5816continue;58175818CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);5819// Dtor might still be missing, e.g because it's invalid.5820if (!Dtor)5821continue;5822if (CheckDestructorAccess(5823ClassDecl->getLocation(), Dtor,5824PDiag(diag::err_access_dtor_vbase)5825<< Context.getTypeDeclType(ClassDecl) << VBase.getType(),5826Context.getTypeDeclType(ClassDecl)) ==5827AR_accessible) {5828CheckDerivedToBaseConversion(5829Context.getTypeDeclType(ClassDecl), VBase.getType(),5830diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),5831SourceRange(), DeclarationName(), nullptr);5832}58335834MarkFunctionReferenced(Location, Dtor);5835DiagnoseUseOfDecl(Dtor, Location);5836}5837}58385839void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {5840if (!CDtorDecl)5841return;58425843if (CXXConstructorDecl *Constructor5844= dyn_cast<CXXConstructorDecl>(CDtorDecl)) {5845if (CXXRecordDecl *ClassDecl = Constructor->getParent();5846!ClassDecl || ClassDecl->isInvalidDecl()) {5847return;5848}5849SetCtorInitializers(Constructor, /*AnyErrors=*/false);5850DiagnoseUninitializedFields(*this, Constructor);5851}5852}58535854bool Sema::isAbstractType(SourceLocation Loc, QualType T) {5855if (!getLangOpts().CPlusPlus)5856return false;58575858const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();5859if (!RD)5860return false;58615862// FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a5863// class template specialization here, but doing so breaks a lot of code.58645865// We can't answer whether something is abstract until it has a5866// definition. If it's currently being defined, we'll walk back5867// over all the declarations when we have a full definition.5868const CXXRecordDecl *Def = RD->getDefinition();5869if (!Def || Def->isBeingDefined())5870return false;58715872return RD->isAbstract();5873}58745875bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,5876TypeDiagnoser &Diagnoser) {5877if (!isAbstractType(Loc, T))5878return false;58795880T = Context.getBaseElementType(T);5881Diagnoser.diagnose(*this, Loc, T);5882DiagnoseAbstractType(T->getAsCXXRecordDecl());5883return true;5884}58855886void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {5887// Check if we've already emitted the list of pure virtual functions5888// for this class.5889if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))5890return;58915892// If the diagnostic is suppressed, don't emit the notes. We're only5893// going to emit them once, so try to attach them to a diagnostic we're5894// actually going to show.5895if (Diags.isLastDiagnosticIgnored())5896return;58975898CXXFinalOverriderMap FinalOverriders;5899RD->getFinalOverriders(FinalOverriders);59005901// Keep a set of seen pure methods so we won't diagnose the same method5902// more than once.5903llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;59045905for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),5906MEnd = FinalOverriders.end();5907M != MEnd;5908++M) {5909for (OverridingMethods::iterator SO = M->second.begin(),5910SOEnd = M->second.end();5911SO != SOEnd; ++SO) {5912// C++ [class.abstract]p4:5913// A class is abstract if it contains or inherits at least one5914// pure virtual function for which the final overrider is pure5915// virtual.59165917//5918if (SO->second.size() != 1)5919continue;59205921if (!SO->second.front().Method->isPureVirtual())5922continue;59235924if (!SeenPureMethods.insert(SO->second.front().Method).second)5925continue;59265927Diag(SO->second.front().Method->getLocation(),5928diag::note_pure_virtual_function)5929<< SO->second.front().Method->getDeclName() << RD->getDeclName();5930}5931}59325933if (!PureVirtualClassDiagSet)5934PureVirtualClassDiagSet.reset(new RecordDeclSetTy);5935PureVirtualClassDiagSet->insert(RD);5936}59375938namespace {5939struct AbstractUsageInfo {5940Sema &S;5941CXXRecordDecl *Record;5942CanQualType AbstractType;5943bool Invalid;59445945AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)5946: S(S), Record(Record),5947AbstractType(S.Context.getCanonicalType(5948S.Context.getTypeDeclType(Record))),5949Invalid(false) {}59505951void DiagnoseAbstractType() {5952if (Invalid) return;5953S.DiagnoseAbstractType(Record);5954Invalid = true;5955}59565957void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);5958};59595960struct CheckAbstractUsage {5961AbstractUsageInfo &Info;5962const NamedDecl *Ctx;59635964CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)5965: Info(Info), Ctx(Ctx) {}59665967void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {5968switch (TL.getTypeLocClass()) {5969#define ABSTRACT_TYPELOC(CLASS, PARENT)5970#define TYPELOC(CLASS, PARENT) \5971case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;5972#include "clang/AST/TypeLocNodes.def"5973}5974}59755976void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {5977Visit(TL.getReturnLoc(), Sema::AbstractReturnType);5978for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {5979if (!TL.getParam(I))5980continue;59815982TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();5983if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);5984}5985}59865987void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {5988Visit(TL.getElementLoc(), Sema::AbstractArrayType);5989}59905991void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {5992// Visit the type parameters from a permissive context.5993for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {5994TemplateArgumentLoc TAL = TL.getArgLoc(I);5995if (TAL.getArgument().getKind() == TemplateArgument::Type)5996if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())5997Visit(TSI->getTypeLoc(), Sema::AbstractNone);5998// TODO: other template argument types?5999}6000}60016002// Visit pointee types from a permissive context.6003#define CheckPolymorphic(Type) \6004void Check(Type TL, Sema::AbstractDiagSelID Sel) { \6005Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \6006}6007CheckPolymorphic(PointerTypeLoc)6008CheckPolymorphic(ReferenceTypeLoc)6009CheckPolymorphic(MemberPointerTypeLoc)6010CheckPolymorphic(BlockPointerTypeLoc)6011CheckPolymorphic(AtomicTypeLoc)60126013/// Handle all the types we haven't given a more specific6014/// implementation for above.6015void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {6016// Every other kind of type that we haven't called out already6017// that has an inner type is either (1) sugar or (2) contains that6018// inner type in some way as a subobject.6019if (TypeLoc Next = TL.getNextTypeLoc())6020return Visit(Next, Sel);60216022// If there's no inner type and we're in a permissive context,6023// don't diagnose.6024if (Sel == Sema::AbstractNone) return;60256026// Check whether the type matches the abstract type.6027QualType T = TL.getType();6028if (T->isArrayType()) {6029Sel = Sema::AbstractArrayType;6030T = Info.S.Context.getBaseElementType(T);6031}6032CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();6033if (CT != Info.AbstractType) return;60346035// It matched; do some magic.6036// FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.6037if (Sel == Sema::AbstractArrayType) {6038Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)6039<< T << TL.getSourceRange();6040} else {6041Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)6042<< Sel << T << TL.getSourceRange();6043}6044Info.DiagnoseAbstractType();6045}6046};60476048void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,6049Sema::AbstractDiagSelID Sel) {6050CheckAbstractUsage(*this, D).Visit(TL, Sel);6051}60526053}60546055/// Check for invalid uses of an abstract type in a function declaration.6056static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6057FunctionDecl *FD) {6058// Only definitions are required to refer to complete and6059// non-abstract types.6060if (!FD->doesThisDeclarationHaveABody())6061return;60626063// For safety's sake, just ignore it if we don't have type source6064// information. This should never happen for non-implicit methods,6065// but...6066if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())6067Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);6068}60696070/// Check for invalid uses of an abstract type in a variable0 declaration.6071static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6072VarDecl *VD) {6073// No need to do the check on definitions, which require that6074// the type is complete.6075if (VD->isThisDeclarationADefinition())6076return;60776078Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),6079Sema::AbstractVariableType);6080}60816082/// Check for invalid uses of an abstract type within a class definition.6083static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6084CXXRecordDecl *RD) {6085for (auto *D : RD->decls()) {6086if (D->isImplicit()) continue;60876088// Step through friends to the befriended declaration.6089if (auto *FD = dyn_cast<FriendDecl>(D)) {6090D = FD->getFriendDecl();6091if (!D) continue;6092}60936094// Functions and function templates.6095if (auto *FD = dyn_cast<FunctionDecl>(D)) {6096CheckAbstractClassUsage(Info, FD);6097} else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {6098CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());60996100// Fields and static variables.6101} else if (auto *FD = dyn_cast<FieldDecl>(D)) {6102if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())6103Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);6104} else if (auto *VD = dyn_cast<VarDecl>(D)) {6105CheckAbstractClassUsage(Info, VD);6106} else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {6107CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());61086109// Nested classes and class templates.6110} else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {6111CheckAbstractClassUsage(Info, RD);6112} else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {6113CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());6114}6115}6116}61176118static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {6119Attr *ClassAttr = getDLLAttr(Class);6120if (!ClassAttr)6121return;61226123assert(ClassAttr->getKind() == attr::DLLExport);61246125TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();61266127if (TSK == TSK_ExplicitInstantiationDeclaration)6128// Don't go any further if this is just an explicit instantiation6129// declaration.6130return;61316132// Add a context note to explain how we got to any diagnostics produced below.6133struct MarkingClassDllexported {6134Sema &S;6135MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,6136SourceLocation AttrLoc)6137: S(S) {6138Sema::CodeSynthesisContext Ctx;6139Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;6140Ctx.PointOfInstantiation = AttrLoc;6141Ctx.Entity = Class;6142S.pushCodeSynthesisContext(Ctx);6143}6144~MarkingClassDllexported() {6145S.popCodeSynthesisContext();6146}6147} MarkingDllexportedContext(S, Class, ClassAttr->getLocation());61486149if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())6150S.MarkVTableUsed(Class->getLocation(), Class, true);61516152for (Decl *Member : Class->decls()) {6153// Skip members that were not marked exported.6154if (!Member->hasAttr<DLLExportAttr>())6155continue;61566157// Defined static variables that are members of an exported base6158// class must be marked export too.6159auto *VD = dyn_cast<VarDecl>(Member);6160if (VD && VD->getStorageClass() == SC_Static &&6161TSK == TSK_ImplicitInstantiation)6162S.MarkVariableReferenced(VD->getLocation(), VD);61636164auto *MD = dyn_cast<CXXMethodDecl>(Member);6165if (!MD)6166continue;61676168if (MD->isUserProvided()) {6169// Instantiate non-default class member functions ...61706171// .. except for certain kinds of template specializations.6172if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())6173continue;61746175// If this is an MS ABI dllexport default constructor, instantiate any6176// default arguments.6177if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {6178auto *CD = dyn_cast<CXXConstructorDecl>(MD);6179if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {6180S.InstantiateDefaultCtorDefaultArgs(CD);6181}6182}61836184S.MarkFunctionReferenced(Class->getLocation(), MD);61856186// The function will be passed to the consumer when its definition is6187// encountered.6188} else if (MD->isExplicitlyDefaulted()) {6189// Synthesize and instantiate explicitly defaulted methods.6190S.MarkFunctionReferenced(Class->getLocation(), MD);61916192if (TSK != TSK_ExplicitInstantiationDefinition) {6193// Except for explicit instantiation defs, we will not see the6194// definition again later, so pass it to the consumer now.6195S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));6196}6197} else if (!MD->isTrivial() ||6198MD->isCopyAssignmentOperator() ||6199MD->isMoveAssignmentOperator()) {6200// Synthesize and instantiate non-trivial implicit methods, and the copy6201// and move assignment operators. The latter are exported even if they6202// are trivial, because the address of an operator can be taken and6203// should compare equal across libraries.6204S.MarkFunctionReferenced(Class->getLocation(), MD);62056206// There is no later point when we will see the definition of this6207// function, so pass it to the consumer now.6208S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));6209}6210}6211}62126213static void checkForMultipleExportedDefaultConstructors(Sema &S,6214CXXRecordDecl *Class) {6215// Only the MS ABI has default constructor closures, so we don't need to do6216// this semantic checking anywhere else.6217if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())6218return;62196220CXXConstructorDecl *LastExportedDefaultCtor = nullptr;6221for (Decl *Member : Class->decls()) {6222// Look for exported default constructors.6223auto *CD = dyn_cast<CXXConstructorDecl>(Member);6224if (!CD || !CD->isDefaultConstructor())6225continue;6226auto *Attr = CD->getAttr<DLLExportAttr>();6227if (!Attr)6228continue;62296230// If the class is non-dependent, mark the default arguments as ODR-used so6231// that we can properly codegen the constructor closure.6232if (!Class->isDependentContext()) {6233for (ParmVarDecl *PD : CD->parameters()) {6234(void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);6235S.DiscardCleanupsInEvaluationContext();6236}6237}62386239if (LastExportedDefaultCtor) {6240S.Diag(LastExportedDefaultCtor->getLocation(),6241diag::err_attribute_dll_ambiguous_default_ctor)6242<< Class;6243S.Diag(CD->getLocation(), diag::note_entity_declared_at)6244<< CD->getDeclName();6245return;6246}6247LastExportedDefaultCtor = CD;6248}6249}62506251static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,6252CXXRecordDecl *Class) {6253bool ErrorReported = false;6254auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,6255ClassTemplateDecl *TD) {6256if (ErrorReported)6257return;6258S.Diag(TD->getLocation(),6259diag::err_cuda_device_builtin_surftex_cls_template)6260<< /*surface*/ 0 << TD;6261ErrorReported = true;6262};62636264ClassTemplateDecl *TD = Class->getDescribedClassTemplate();6265if (!TD) {6266auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);6267if (!SD) {6268S.Diag(Class->getLocation(),6269diag::err_cuda_device_builtin_surftex_ref_decl)6270<< /*surface*/ 0 << Class;6271S.Diag(Class->getLocation(),6272diag::note_cuda_device_builtin_surftex_should_be_template_class)6273<< Class;6274return;6275}6276TD = SD->getSpecializedTemplate();6277}62786279TemplateParameterList *Params = TD->getTemplateParameters();6280unsigned N = Params->size();62816282if (N != 2) {6283reportIllegalClassTemplate(S, TD);6284S.Diag(TD->getLocation(),6285diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)6286<< TD << 2;6287}6288if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {6289reportIllegalClassTemplate(S, TD);6290S.Diag(TD->getLocation(),6291diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6292<< TD << /*1st*/ 0 << /*type*/ 0;6293}6294if (N > 1) {6295auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));6296if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6297reportIllegalClassTemplate(S, TD);6298S.Diag(TD->getLocation(),6299diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6300<< TD << /*2nd*/ 1 << /*integer*/ 1;6301}6302}6303}63046305static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,6306CXXRecordDecl *Class) {6307bool ErrorReported = false;6308auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,6309ClassTemplateDecl *TD) {6310if (ErrorReported)6311return;6312S.Diag(TD->getLocation(),6313diag::err_cuda_device_builtin_surftex_cls_template)6314<< /*texture*/ 1 << TD;6315ErrorReported = true;6316};63176318ClassTemplateDecl *TD = Class->getDescribedClassTemplate();6319if (!TD) {6320auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);6321if (!SD) {6322S.Diag(Class->getLocation(),6323diag::err_cuda_device_builtin_surftex_ref_decl)6324<< /*texture*/ 1 << Class;6325S.Diag(Class->getLocation(),6326diag::note_cuda_device_builtin_surftex_should_be_template_class)6327<< Class;6328return;6329}6330TD = SD->getSpecializedTemplate();6331}63326333TemplateParameterList *Params = TD->getTemplateParameters();6334unsigned N = Params->size();63356336if (N != 3) {6337reportIllegalClassTemplate(S, TD);6338S.Diag(TD->getLocation(),6339diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)6340<< TD << 3;6341}6342if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {6343reportIllegalClassTemplate(S, TD);6344S.Diag(TD->getLocation(),6345diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6346<< TD << /*1st*/ 0 << /*type*/ 0;6347}6348if (N > 1) {6349auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));6350if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6351reportIllegalClassTemplate(S, TD);6352S.Diag(TD->getLocation(),6353diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6354<< TD << /*2nd*/ 1 << /*integer*/ 1;6355}6356}6357if (N > 2) {6358auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));6359if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6360reportIllegalClassTemplate(S, TD);6361S.Diag(TD->getLocation(),6362diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6363<< TD << /*3rd*/ 2 << /*integer*/ 1;6364}6365}6366}63676368void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {6369// Mark any compiler-generated routines with the implicit code_seg attribute.6370for (auto *Method : Class->methods()) {6371if (Method->isUserProvided())6372continue;6373if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))6374Method->addAttr(A);6375}6376}63776378void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {6379Attr *ClassAttr = getDLLAttr(Class);63806381// MSVC inherits DLL attributes to partial class template specializations.6382if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {6383if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {6384if (Attr *TemplateAttr =6385getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {6386auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));6387A->setInherited(true);6388ClassAttr = A;6389}6390}6391}63926393if (!ClassAttr)6394return;63956396// MSVC allows imported or exported template classes that have UniqueExternal6397// linkage. This occurs when the template class has been instantiated with6398// a template parameter which itself has internal linkage.6399// We drop the attribute to avoid exporting or importing any members.6400if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||6401Context.getTargetInfo().getTriple().isPS()) &&6402(!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {6403Class->dropAttrs<DLLExportAttr, DLLImportAttr>();6404return;6405}64066407if (!Class->isExternallyVisible()) {6408Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)6409<< Class << ClassAttr;6410return;6411}64126413if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&6414!ClassAttr->isInherited()) {6415// Diagnose dll attributes on members of class with dll attribute.6416for (Decl *Member : Class->decls()) {6417if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))6418continue;6419InheritableAttr *MemberAttr = getDLLAttr(Member);6420if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())6421continue;64226423Diag(MemberAttr->getLocation(),6424diag::err_attribute_dll_member_of_dll_class)6425<< MemberAttr << ClassAttr;6426Diag(ClassAttr->getLocation(), diag::note_previous_attribute);6427Member->setInvalidDecl();6428}6429}64306431if (Class->getDescribedClassTemplate())6432// Don't inherit dll attribute until the template is instantiated.6433return;64346435// The class is either imported or exported.6436const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;64376438// Check if this was a dllimport attribute propagated from a derived class to6439// a base class template specialization. We don't apply these attributes to6440// static data members.6441const bool PropagatedImport =6442!ClassExported &&6443cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();64446445TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();64466447// Ignore explicit dllexport on explicit class template instantiation6448// declarations, except in MinGW mode.6449if (ClassExported && !ClassAttr->isInherited() &&6450TSK == TSK_ExplicitInstantiationDeclaration &&6451!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {6452Class->dropAttr<DLLExportAttr>();6453return;6454}64556456// Force declaration of implicit members so they can inherit the attribute.6457ForceDeclarationOfImplicitMembers(Class);64586459// FIXME: MSVC's docs say all bases must be exportable, but this doesn't6460// seem to be true in practice?64616462for (Decl *Member : Class->decls()) {6463VarDecl *VD = dyn_cast<VarDecl>(Member);6464CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);64656466// Only methods and static fields inherit the attributes.6467if (!VD && !MD)6468continue;64696470if (MD) {6471// Don't process deleted methods.6472if (MD->isDeleted())6473continue;64746475if (MD->isInlined()) {6476// MinGW does not import or export inline methods. But do it for6477// template instantiations.6478if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&6479TSK != TSK_ExplicitInstantiationDeclaration &&6480TSK != TSK_ExplicitInstantiationDefinition)6481continue;64826483// MSVC versions before 2015 don't export the move assignment operators6484// and move constructor, so don't attempt to import/export them if6485// we have a definition.6486auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);6487if ((MD->isMoveAssignmentOperator() ||6488(Ctor && Ctor->isMoveConstructor())) &&6489!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))6490continue;64916492// MSVC2015 doesn't export trivial defaulted x-tor but copy assign6493// operator is exported anyway.6494if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&6495(Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())6496continue;6497}6498}64996500// Don't apply dllimport attributes to static data members of class template6501// instantiations when the attribute is propagated from a derived class.6502if (VD && PropagatedImport)6503continue;65046505if (!cast<NamedDecl>(Member)->isExternallyVisible())6506continue;65076508if (!getDLLAttr(Member)) {6509InheritableAttr *NewAttr = nullptr;65106511// Do not export/import inline function when -fno-dllexport-inlines is6512// passed. But add attribute for later local static var check.6513if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&6514TSK != TSK_ExplicitInstantiationDeclaration &&6515TSK != TSK_ExplicitInstantiationDefinition) {6516if (ClassExported) {6517NewAttr = ::new (getASTContext())6518DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);6519} else {6520NewAttr = ::new (getASTContext())6521DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);6522}6523} else {6524NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6525}65266527NewAttr->setInherited(true);6528Member->addAttr(NewAttr);65296530if (MD) {6531// Propagate DLLAttr to friend re-declarations of MD that have already6532// been constructed.6533for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;6534FD = FD->getPreviousDecl()) {6535if (FD->getFriendObjectKind() == Decl::FOK_None)6536continue;6537assert(!getDLLAttr(FD) &&6538"friend re-decl should not already have a DLLAttr");6539NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6540NewAttr->setInherited(true);6541FD->addAttr(NewAttr);6542}6543}6544}6545}65466547if (ClassExported)6548DelayedDllExportClasses.push_back(Class);6549}65506551void Sema::propagateDLLAttrToBaseClassTemplate(6552CXXRecordDecl *Class, Attr *ClassAttr,6553ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {6554if (getDLLAttr(6555BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {6556// If the base class template has a DLL attribute, don't try to change it.6557return;6558}65596560auto TSK = BaseTemplateSpec->getSpecializationKind();6561if (!getDLLAttr(BaseTemplateSpec) &&6562(TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||6563TSK == TSK_ImplicitInstantiation)) {6564// The template hasn't been instantiated yet (or it has, but only as an6565// explicit instantiation declaration or implicit instantiation, which means6566// we haven't codegenned any members yet), so propagate the attribute.6567auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6568NewAttr->setInherited(true);6569BaseTemplateSpec->addAttr(NewAttr);65706571// If this was an import, mark that we propagated it from a derived class to6572// a base class template specialization.6573if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))6574ImportAttr->setPropagatedToBaseTemplate();65756576// If the template is already instantiated, checkDLLAttributeRedeclaration()6577// needs to be run again to work see the new attribute. Otherwise this will6578// get run whenever the template is instantiated.6579if (TSK != TSK_Undeclared)6580checkClassLevelDLLAttribute(BaseTemplateSpec);65816582return;6583}65846585if (getDLLAttr(BaseTemplateSpec)) {6586// The template has already been specialized or instantiated with an6587// attribute, explicitly or through propagation. We should not try to change6588// it.6589return;6590}65916592// The template was previously instantiated or explicitly specialized without6593// a dll attribute, It's too late for us to add an attribute, so warn that6594// this is unsupported.6595Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)6596<< BaseTemplateSpec->isExplicitSpecialization();6597Diag(ClassAttr->getLocation(), diag::note_attribute);6598if (BaseTemplateSpec->isExplicitSpecialization()) {6599Diag(BaseTemplateSpec->getLocation(),6600diag::note_template_class_explicit_specialization_was_here)6601<< BaseTemplateSpec;6602} else {6603Diag(BaseTemplateSpec->getPointOfInstantiation(),6604diag::note_template_class_instantiation_was_here)6605<< BaseTemplateSpec;6606}6607}66086609Sema::DefaultedFunctionKind6610Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {6611if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {6612if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {6613if (Ctor->isDefaultConstructor())6614return CXXSpecialMemberKind::DefaultConstructor;66156616if (Ctor->isCopyConstructor())6617return CXXSpecialMemberKind::CopyConstructor;66186619if (Ctor->isMoveConstructor())6620return CXXSpecialMemberKind::MoveConstructor;6621}66226623if (MD->isCopyAssignmentOperator())6624return CXXSpecialMemberKind::CopyAssignment;66256626if (MD->isMoveAssignmentOperator())6627return CXXSpecialMemberKind::MoveAssignment;66286629if (isa<CXXDestructorDecl>(FD))6630return CXXSpecialMemberKind::Destructor;6631}66326633switch (FD->getDeclName().getCXXOverloadedOperator()) {6634case OO_EqualEqual:6635return DefaultedComparisonKind::Equal;66366637case OO_ExclaimEqual:6638return DefaultedComparisonKind::NotEqual;66396640case OO_Spaceship:6641// No point allowing this if <=> doesn't exist in the current language mode.6642if (!getLangOpts().CPlusPlus20)6643break;6644return DefaultedComparisonKind::ThreeWay;66456646case OO_Less:6647case OO_LessEqual:6648case OO_Greater:6649case OO_GreaterEqual:6650// No point allowing this if <=> doesn't exist in the current language mode.6651if (!getLangOpts().CPlusPlus20)6652break;6653return DefaultedComparisonKind::Relational;66546655default:6656break;6657}66586659// Not defaultable.6660return DefaultedFunctionKind();6661}66626663static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,6664SourceLocation DefaultLoc) {6665Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);6666if (DFK.isComparison())6667return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());66686669switch (DFK.asSpecialMember()) {6670case CXXSpecialMemberKind::DefaultConstructor:6671S.DefineImplicitDefaultConstructor(DefaultLoc,6672cast<CXXConstructorDecl>(FD));6673break;6674case CXXSpecialMemberKind::CopyConstructor:6675S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));6676break;6677case CXXSpecialMemberKind::CopyAssignment:6678S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));6679break;6680case CXXSpecialMemberKind::Destructor:6681S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));6682break;6683case CXXSpecialMemberKind::MoveConstructor:6684S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));6685break;6686case CXXSpecialMemberKind::MoveAssignment:6687S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));6688break;6689case CXXSpecialMemberKind::Invalid:6690llvm_unreachable("Invalid special member.");6691}6692}66936694/// Determine whether a type is permitted to be passed or returned in6695/// registers, per C++ [class.temporary]p3.6696static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,6697TargetInfo::CallingConvKind CCK) {6698if (D->isDependentType() || D->isInvalidDecl())6699return false;67006701// Clang <= 4 used the pre-C++11 rule, which ignores move operations.6702// The PS4 platform ABI follows the behavior of Clang 3.2.6703if (CCK == TargetInfo::CCK_ClangABI4OrPS4)6704return !D->hasNonTrivialDestructorForCall() &&6705!D->hasNonTrivialCopyConstructorForCall();67066707if (CCK == TargetInfo::CCK_MicrosoftWin64) {6708bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;6709bool DtorIsTrivialForCall = false;67106711// If a class has at least one eligible, trivial copy constructor, it6712// is passed according to the C ABI. Otherwise, it is passed indirectly.6713//6714// Note: This permits classes with non-trivial copy or move ctors to be6715// passed in registers, so long as they *also* have a trivial copy ctor,6716// which is non-conforming.6717if (D->needsImplicitCopyConstructor()) {6718if (!D->defaultedCopyConstructorIsDeleted()) {6719if (D->hasTrivialCopyConstructor())6720CopyCtorIsTrivial = true;6721if (D->hasTrivialCopyConstructorForCall())6722CopyCtorIsTrivialForCall = true;6723}6724} else {6725for (const CXXConstructorDecl *CD : D->ctors()) {6726if (CD->isCopyConstructor() && !CD->isDeleted() &&6727!CD->isIneligibleOrNotSelected()) {6728if (CD->isTrivial())6729CopyCtorIsTrivial = true;6730if (CD->isTrivialForCall())6731CopyCtorIsTrivialForCall = true;6732}6733}6734}67356736if (D->needsImplicitDestructor()) {6737if (!D->defaultedDestructorIsDeleted() &&6738D->hasTrivialDestructorForCall())6739DtorIsTrivialForCall = true;6740} else if (const auto *DD = D->getDestructor()) {6741if (!DD->isDeleted() && DD->isTrivialForCall())6742DtorIsTrivialForCall = true;6743}67446745// If the copy ctor and dtor are both trivial-for-calls, pass direct.6746if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)6747return true;67486749// If a class has a destructor, we'd really like to pass it indirectly6750// because it allows us to elide copies. Unfortunately, MSVC makes that6751// impossible for small types, which it will pass in a single register or6752// stack slot. Most objects with dtors are large-ish, so handle that early.6753// We can't call out all large objects as being indirect because there are6754// multiple x64 calling conventions and the C++ ABI code shouldn't dictate6755// how we pass large POD types.67566757// Note: This permits small classes with nontrivial destructors to be6758// passed in registers, which is non-conforming.6759bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();6760uint64_t TypeSize = isAArch64 ? 128 : 64;67616762if (CopyCtorIsTrivial &&6763S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)6764return true;6765return false;6766}67676768// Per C++ [class.temporary]p3, the relevant condition is:6769// each copy constructor, move constructor, and destructor of X is6770// either trivial or deleted, and X has at least one non-deleted copy6771// or move constructor6772bool HasNonDeletedCopyOrMove = false;67736774if (D->needsImplicitCopyConstructor() &&6775!D->defaultedCopyConstructorIsDeleted()) {6776if (!D->hasTrivialCopyConstructorForCall())6777return false;6778HasNonDeletedCopyOrMove = true;6779}67806781if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&6782!D->defaultedMoveConstructorIsDeleted()) {6783if (!D->hasTrivialMoveConstructorForCall())6784return false;6785HasNonDeletedCopyOrMove = true;6786}67876788if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&6789!D->hasTrivialDestructorForCall())6790return false;67916792for (const CXXMethodDecl *MD : D->methods()) {6793if (MD->isDeleted() || MD->isIneligibleOrNotSelected())6794continue;67956796auto *CD = dyn_cast<CXXConstructorDecl>(MD);6797if (CD && CD->isCopyOrMoveConstructor())6798HasNonDeletedCopyOrMove = true;6799else if (!isa<CXXDestructorDecl>(MD))6800continue;68016802if (!MD->isTrivialForCall())6803return false;6804}68056806return HasNonDeletedCopyOrMove;6807}68086809/// Report an error regarding overriding, along with any relevant6810/// overridden methods.6811///6812/// \param DiagID the primary error to report.6813/// \param MD the overriding method.6814static bool6815ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,6816llvm::function_ref<bool(const CXXMethodDecl *)> Report) {6817bool IssuedDiagnostic = false;6818for (const CXXMethodDecl *O : MD->overridden_methods()) {6819if (Report(O)) {6820if (!IssuedDiagnostic) {6821S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();6822IssuedDiagnostic = true;6823}6824S.Diag(O->getLocation(), diag::note_overridden_virtual_function);6825}6826}6827return IssuedDiagnostic;6828}68296830void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {6831if (!Record)6832return;68336834if (Record->isAbstract() && !Record->isInvalidDecl()) {6835AbstractUsageInfo Info(*this, Record);6836CheckAbstractClassUsage(Info, Record);6837}68386839// If this is not an aggregate type and has no user-declared constructor,6840// complain about any non-static data members of reference or const scalar6841// type, since they will never get initializers.6842if (!Record->isInvalidDecl() && !Record->isDependentType() &&6843!Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&6844!Record->isLambda()) {6845bool Complained = false;6846for (const auto *F : Record->fields()) {6847if (F->hasInClassInitializer() || F->isUnnamedBitField())6848continue;68496850if (F->getType()->isReferenceType() ||6851(F->getType().isConstQualified() && F->getType()->isScalarType())) {6852if (!Complained) {6853Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)6854<< llvm::to_underlying(Record->getTagKind()) << Record;6855Complained = true;6856}68576858Diag(F->getLocation(), diag::note_refconst_member_not_initialized)6859<< F->getType()->isReferenceType()6860<< F->getDeclName();6861}6862}6863}68646865if (Record->getIdentifier()) {6866// C++ [class.mem]p13:6867// If T is the name of a class, then each of the following shall have a6868// name different from T:6869// - every member of every anonymous union that is a member of class T.6870//6871// C++ [class.mem]p14:6872// In addition, if class T has a user-declared constructor (12.1), every6873// non-static data member of class T shall have a name different from T.6874DeclContext::lookup_result R = Record->lookup(Record->getDeclName());6875for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;6876++I) {6877NamedDecl *D = (*I)->getUnderlyingDecl();6878if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&6879Record->hasUserDeclaredConstructor()) ||6880isa<IndirectFieldDecl>(D)) {6881Diag((*I)->getLocation(), diag::err_member_name_of_class)6882<< D->getDeclName();6883break;6884}6885}6886}68876888// Warn if the class has virtual methods but non-virtual public destructor.6889if (Record->isPolymorphic() && !Record->isDependentType()) {6890CXXDestructorDecl *dtor = Record->getDestructor();6891if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&6892!Record->hasAttr<FinalAttr>())6893Diag(dtor ? dtor->getLocation() : Record->getLocation(),6894diag::warn_non_virtual_dtor) << Context.getRecordType(Record);6895}68966897if (Record->isAbstract()) {6898if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {6899Diag(Record->getLocation(), diag::warn_abstract_final_class)6900<< FA->isSpelledAsSealed();6901DiagnoseAbstractType(Record);6902}6903}69046905// Warn if the class has a final destructor but is not itself marked final.6906if (!Record->hasAttr<FinalAttr>()) {6907if (const CXXDestructorDecl *dtor = Record->getDestructor()) {6908if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {6909Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)6910<< FA->isSpelledAsSealed()6911<< FixItHint::CreateInsertion(6912getLocForEndOfToken(Record->getLocation()),6913(FA->isSpelledAsSealed() ? " sealed" : " final"));6914Diag(Record->getLocation(),6915diag::note_final_dtor_non_final_class_silence)6916<< Context.getRecordType(Record) << FA->isSpelledAsSealed();6917}6918}6919}69206921// See if trivial_abi has to be dropped.6922if (Record->hasAttr<TrivialABIAttr>())6923checkIllFormedTrivialABIStruct(*Record);69246925// Set HasTrivialSpecialMemberForCall if the record has attribute6926// "trivial_abi".6927bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();69286929if (HasTrivialABI)6930Record->setHasTrivialSpecialMemberForCall();69316932// Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).6933// We check these last because they can depend on the properties of the6934// primary comparison functions (==, <=>).6935llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;69366937// Perform checks that can't be done until we know all the properties of a6938// member function (whether it's defaulted, deleted, virtual, overriding,6939// ...).6940auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {6941// A static function cannot override anything.6942if (MD->getStorageClass() == SC_Static) {6943if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,6944[](const CXXMethodDecl *) { return true; }))6945return;6946}69476948// A deleted function cannot override a non-deleted function and vice6949// versa.6950if (ReportOverrides(*this,6951MD->isDeleted() ? diag::err_deleted_override6952: diag::err_non_deleted_override,6953MD, [&](const CXXMethodDecl *V) {6954return MD->isDeleted() != V->isDeleted();6955})) {6956if (MD->isDefaulted() && MD->isDeleted())6957// Explain why this defaulted function was deleted.6958DiagnoseDeletedDefaultedFunction(MD);6959return;6960}69616962// A consteval function cannot override a non-consteval function and vice6963// versa.6964if (ReportOverrides(*this,6965MD->isConsteval() ? diag::err_consteval_override6966: diag::err_non_consteval_override,6967MD, [&](const CXXMethodDecl *V) {6968return MD->isConsteval() != V->isConsteval();6969})) {6970if (MD->isDefaulted() && MD->isDeleted())6971// Explain why this defaulted function was deleted.6972DiagnoseDeletedDefaultedFunction(MD);6973return;6974}6975};69766977auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {6978if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())6979return false;69806981DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);6982if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||6983DFK.asComparison() == DefaultedComparisonKind::Relational) {6984DefaultedSecondaryComparisons.push_back(FD);6985return true;6986}69876988CheckExplicitlyDefaultedFunction(S, FD);6989return false;6990};69916992if (!Record->isInvalidDecl() &&6993Record->hasAttr<VTablePointerAuthenticationAttr>())6994checkIncorrectVTablePointerAuthenticationAttribute(*Record);69956996auto CompleteMemberFunction = [&](CXXMethodDecl *M) {6997// Check whether the explicitly-defaulted members are valid.6998bool Incomplete = CheckForDefaultedFunction(M);69997000// Skip the rest of the checks for a member of a dependent class.7001if (Record->isDependentType())7002return;70037004// For an explicitly defaulted or deleted special member, we defer7005// determining triviality until the class is complete. That time is now!7006CXXSpecialMemberKind CSM = getSpecialMember(M);7007if (!M->isImplicit() && !M->isUserProvided()) {7008if (CSM != CXXSpecialMemberKind::Invalid) {7009M->setTrivial(SpecialMemberIsTrivial(M, CSM));7010// Inform the class that we've finished declaring this member.7011Record->finishedDefaultedOrDeletedMember(M);7012M->setTrivialForCall(7013HasTrivialABI ||7014SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));7015Record->setTrivialForCallFlags(M);7016}7017}70187019// Set triviality for the purpose of calls if this is a user-provided7020// copy/move constructor or destructor.7021if ((CSM == CXXSpecialMemberKind::CopyConstructor ||7022CSM == CXXSpecialMemberKind::MoveConstructor ||7023CSM == CXXSpecialMemberKind::Destructor) &&7024M->isUserProvided()) {7025M->setTrivialForCall(HasTrivialABI);7026Record->setTrivialForCallFlags(M);7027}70287029if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&7030M->hasAttr<DLLExportAttr>()) {7031if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&7032M->isTrivial() &&7033(CSM == CXXSpecialMemberKind::DefaultConstructor ||7034CSM == CXXSpecialMemberKind::CopyConstructor ||7035CSM == CXXSpecialMemberKind::Destructor))7036M->dropAttr<DLLExportAttr>();70377038if (M->hasAttr<DLLExportAttr>()) {7039// Define after any fields with in-class initializers have been parsed.7040DelayedDllExportMemberFunctions.push_back(M);7041}7042}70437044bool EffectivelyConstexprDestructor = true;7045// Avoid triggering vtable instantiation due to a dtor that is not7046// "effectively constexpr" for better compatibility.7047// See https://github.com/llvm/llvm-project/issues/102293 for more info.7048if (isa<CXXDestructorDecl>(M)) {7049auto Check = [](QualType T, auto &&Check) -> bool {7050const CXXRecordDecl *RD =7051T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();7052if (!RD || !RD->isCompleteDefinition())7053return true;70547055if (!RD->hasConstexprDestructor())7056return false;70577058QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();7059for (const CXXBaseSpecifier &B : RD->bases())7060if (B.getType().getCanonicalType().getUnqualifiedType() !=7061CanUnqualT &&7062!Check(B.getType(), Check))7063return false;7064for (const FieldDecl *FD : RD->fields())7065if (FD->getType().getCanonicalType().getUnqualifiedType() !=7066CanUnqualT &&7067!Check(FD->getType(), Check))7068return false;7069return true;7070};7071EffectivelyConstexprDestructor =7072Check(QualType(Record->getTypeForDecl(), 0), Check);7073}70747075// Define defaulted constexpr virtual functions that override a base class7076// function right away.7077// FIXME: We can defer doing this until the vtable is marked as used.7078if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&7079M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&7080EffectivelyConstexprDestructor)7081DefineDefaultedFunction(*this, M, M->getLocation());70827083if (!Incomplete)7084CheckCompletedMemberFunction(M);7085};70867087// Check the destructor before any other member function. We need to7088// determine whether it's trivial in order to determine whether the claas7089// type is a literal type, which is a prerequisite for determining whether7090// other special member functions are valid and whether they're implicitly7091// 'constexpr'.7092if (CXXDestructorDecl *Dtor = Record->getDestructor())7093CompleteMemberFunction(Dtor);70947095bool HasMethodWithOverrideControl = false,7096HasOverridingMethodWithoutOverrideControl = false;7097for (auto *D : Record->decls()) {7098if (auto *M = dyn_cast<CXXMethodDecl>(D)) {7099// FIXME: We could do this check for dependent types with non-dependent7100// bases.7101if (!Record->isDependentType()) {7102// See if a method overloads virtual methods in a base7103// class without overriding any.7104if (!M->isStatic())7105DiagnoseHiddenVirtualMethods(M);7106if (M->hasAttr<OverrideAttr>())7107HasMethodWithOverrideControl = true;7108else if (M->size_overridden_methods() > 0)7109HasOverridingMethodWithoutOverrideControl = true;7110}71117112if (!isa<CXXDestructorDecl>(M))7113CompleteMemberFunction(M);7114} else if (auto *F = dyn_cast<FriendDecl>(D)) {7115CheckForDefaultedFunction(7116dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));7117}7118}71197120if (HasOverridingMethodWithoutOverrideControl) {7121bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;7122for (auto *M : Record->methods())7123DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);7124}71257126// Check the defaulted secondary comparisons after any other member functions.7127for (FunctionDecl *FD : DefaultedSecondaryComparisons) {7128CheckExplicitlyDefaultedFunction(S, FD);71297130// If this is a member function, we deferred checking it until now.7131if (auto *MD = dyn_cast<CXXMethodDecl>(FD))7132CheckCompletedMemberFunction(MD);7133}71347135// ms_struct is a request to use the same ABI rules as MSVC. Check7136// whether this class uses any C++ features that are implemented7137// completely differently in MSVC, and if so, emit a diagnostic.7138// That diagnostic defaults to an error, but we allow projects to7139// map it down to a warning (or ignore it). It's a fairly common7140// practice among users of the ms_struct pragma to mass-annotate7141// headers, sweeping up a bunch of types that the project doesn't7142// really rely on MSVC-compatible layout for. We must therefore7143// support "ms_struct except for C++ stuff" as a secondary ABI.7144// Don't emit this diagnostic if the feature was enabled as a7145// language option (as opposed to via a pragma or attribute), as7146// the option -mms-bitfields otherwise essentially makes it impossible7147// to build C++ code, unless this diagnostic is turned off.7148if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&7149(Record->isPolymorphic() || Record->getNumBases())) {7150Diag(Record->getLocation(), diag::warn_cxx_ms_struct);7151}71527153checkClassLevelDLLAttribute(Record);7154checkClassLevelCodeSegAttribute(Record);71557156bool ClangABICompat4 =7157Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;7158TargetInfo::CallingConvKind CCK =7159Context.getTargetInfo().getCallingConvKind(ClangABICompat4);7160bool CanPass = canPassInRegisters(*this, Record, CCK);71617162// Do not change ArgPassingRestrictions if it has already been set to7163// RecordArgPassingKind::CanNeverPassInRegs.7164if (Record->getArgPassingRestrictions() !=7165RecordArgPassingKind::CanNeverPassInRegs)7166Record->setArgPassingRestrictions(7167CanPass ? RecordArgPassingKind::CanPassInRegs7168: RecordArgPassingKind::CannotPassInRegs);71697170// If canPassInRegisters returns true despite the record having a non-trivial7171// destructor, the record is destructed in the callee. This happens only when7172// the record or one of its subobjects has a field annotated with trivial_abi7173// or a field qualified with ObjC __strong/__weak.7174if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())7175Record->setParamDestroyedInCallee(true);7176else if (Record->hasNonTrivialDestructor())7177Record->setParamDestroyedInCallee(CanPass);71787179if (getLangOpts().ForceEmitVTables) {7180// If we want to emit all the vtables, we need to mark it as used. This7181// is especially required for cases like vtable assumption loads.7182MarkVTableUsed(Record->getInnerLocStart(), Record);7183}71847185if (getLangOpts().CUDA) {7186if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())7187checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);7188else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())7189checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);7190}7191}71927193/// Look up the special member function that would be called by a special7194/// member function for a subobject of class type.7195///7196/// \param Class The class type of the subobject.7197/// \param CSM The kind of special member function.7198/// \param FieldQuals If the subobject is a field, its cv-qualifiers.7199/// \param ConstRHS True if this is a copy operation with a const object7200/// on its RHS, that is, if the argument to the outer special member7201/// function is 'const' and this is not a field marked 'mutable'.7202static Sema::SpecialMemberOverloadResult7203lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,7204CXXSpecialMemberKind CSM, unsigned FieldQuals,7205bool ConstRHS) {7206unsigned LHSQuals = 0;7207if (CSM == CXXSpecialMemberKind::CopyAssignment ||7208CSM == CXXSpecialMemberKind::MoveAssignment)7209LHSQuals = FieldQuals;72107211unsigned RHSQuals = FieldQuals;7212if (CSM == CXXSpecialMemberKind::DefaultConstructor ||7213CSM == CXXSpecialMemberKind::Destructor)7214RHSQuals = 0;7215else if (ConstRHS)7216RHSQuals |= Qualifiers::Const;72177218return S.LookupSpecialMember(Class, CSM,7219RHSQuals & Qualifiers::Const,7220RHSQuals & Qualifiers::Volatile,7221false,7222LHSQuals & Qualifiers::Const,7223LHSQuals & Qualifiers::Volatile);7224}72257226class Sema::InheritedConstructorInfo {7227Sema &S;7228SourceLocation UseLoc;72297230/// A mapping from the base classes through which the constructor was7231/// inherited to the using shadow declaration in that base class (or a null7232/// pointer if the constructor was declared in that base class).7233llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>7234InheritedFromBases;72357236public:7237InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,7238ConstructorUsingShadowDecl *Shadow)7239: S(S), UseLoc(UseLoc) {7240bool DiagnosedMultipleConstructedBases = false;7241CXXRecordDecl *ConstructedBase = nullptr;7242BaseUsingDecl *ConstructedBaseIntroducer = nullptr;72437244// Find the set of such base class subobjects and check that there's a7245// unique constructed subobject.7246for (auto *D : Shadow->redecls()) {7247auto *DShadow = cast<ConstructorUsingShadowDecl>(D);7248auto *DNominatedBase = DShadow->getNominatedBaseClass();7249auto *DConstructedBase = DShadow->getConstructedBaseClass();72507251InheritedFromBases.insert(7252std::make_pair(DNominatedBase->getCanonicalDecl(),7253DShadow->getNominatedBaseClassShadowDecl()));7254if (DShadow->constructsVirtualBase())7255InheritedFromBases.insert(7256std::make_pair(DConstructedBase->getCanonicalDecl(),7257DShadow->getConstructedBaseClassShadowDecl()));7258else7259assert(DNominatedBase == DConstructedBase);72607261// [class.inhctor.init]p2:7262// If the constructor was inherited from multiple base class subobjects7263// of type B, the program is ill-formed.7264if (!ConstructedBase) {7265ConstructedBase = DConstructedBase;7266ConstructedBaseIntroducer = D->getIntroducer();7267} else if (ConstructedBase != DConstructedBase &&7268!Shadow->isInvalidDecl()) {7269if (!DiagnosedMultipleConstructedBases) {7270S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)7271<< Shadow->getTargetDecl();7272S.Diag(ConstructedBaseIntroducer->getLocation(),7273diag::note_ambiguous_inherited_constructor_using)7274<< ConstructedBase;7275DiagnosedMultipleConstructedBases = true;7276}7277S.Diag(D->getIntroducer()->getLocation(),7278diag::note_ambiguous_inherited_constructor_using)7279<< DConstructedBase;7280}7281}72827283if (DiagnosedMultipleConstructedBases)7284Shadow->setInvalidDecl();7285}72867287/// Find the constructor to use for inherited construction of a base class,7288/// and whether that base class constructor inherits the constructor from a7289/// virtual base class (in which case it won't actually invoke it).7290std::pair<CXXConstructorDecl *, bool>7291findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {7292auto It = InheritedFromBases.find(Base->getCanonicalDecl());7293if (It == InheritedFromBases.end())7294return std::make_pair(nullptr, false);72957296// This is an intermediary class.7297if (It->second)7298return std::make_pair(7299S.findInheritingConstructor(UseLoc, Ctor, It->second),7300It->second->constructsVirtualBase());73017302// This is the base class from which the constructor was inherited.7303return std::make_pair(Ctor, false);7304}7305};73067307/// Is the special member function which would be selected to perform the7308/// specified operation on the specified class type a constexpr constructor?7309static bool specialMemberIsConstexpr(7310Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,7311bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,7312Sema::InheritedConstructorInfo *Inherited = nullptr) {7313// Suppress duplicate constraint checking here, in case a constraint check7314// caused us to decide to do this. Any truely recursive checks will get7315// caught during these checks anyway.7316Sema::SatisfactionStackResetRAII SSRAII{S};73177318// If we're inheriting a constructor, see if we need to call it for this base7319// class.7320if (InheritedCtor) {7321assert(CSM == CXXSpecialMemberKind::DefaultConstructor);7322auto BaseCtor =7323Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;7324if (BaseCtor)7325return BaseCtor->isConstexpr();7326}73277328if (CSM == CXXSpecialMemberKind::DefaultConstructor)7329return ClassDecl->hasConstexprDefaultConstructor();7330if (CSM == CXXSpecialMemberKind::Destructor)7331return ClassDecl->hasConstexprDestructor();73327333Sema::SpecialMemberOverloadResult SMOR =7334lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);7335if (!SMOR.getMethod())7336// A constructor we wouldn't select can't be "involved in initializing"7337// anything.7338return true;7339return SMOR.getMethod()->isConstexpr();7340}73417342/// Determine whether the specified special member function would be constexpr7343/// if it were implicitly defined.7344static bool defaultedSpecialMemberIsConstexpr(7345Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,7346CXXConstructorDecl *InheritedCtor = nullptr,7347Sema::InheritedConstructorInfo *Inherited = nullptr) {7348if (!S.getLangOpts().CPlusPlus11)7349return false;73507351// C++11 [dcl.constexpr]p4:7352// In the definition of a constexpr constructor [...]7353bool Ctor = true;7354switch (CSM) {7355case CXXSpecialMemberKind::DefaultConstructor:7356if (Inherited)7357break;7358// Since default constructor lookup is essentially trivial (and cannot7359// involve, for instance, template instantiation), we compute whether a7360// defaulted default constructor is constexpr directly within CXXRecordDecl.7361//7362// This is important for performance; we need to know whether the default7363// constructor is constexpr to determine whether the type is a literal type.7364return ClassDecl->defaultedDefaultConstructorIsConstexpr();73657366case CXXSpecialMemberKind::CopyConstructor:7367case CXXSpecialMemberKind::MoveConstructor:7368// For copy or move constructors, we need to perform overload resolution.7369break;73707371case CXXSpecialMemberKind::CopyAssignment:7372case CXXSpecialMemberKind::MoveAssignment:7373if (!S.getLangOpts().CPlusPlus14)7374return false;7375// In C++1y, we need to perform overload resolution.7376Ctor = false;7377break;73787379case CXXSpecialMemberKind::Destructor:7380return ClassDecl->defaultedDestructorIsConstexpr();73817382case CXXSpecialMemberKind::Invalid:7383return false;7384}73857386// -- if the class is a non-empty union, or for each non-empty anonymous7387// union member of a non-union class, exactly one non-static data member7388// shall be initialized; [DR1359]7389//7390// If we squint, this is guaranteed, since exactly one non-static data member7391// will be initialized (if the constructor isn't deleted), we just don't know7392// which one.7393if (Ctor && ClassDecl->isUnion())7394return CSM == CXXSpecialMemberKind::DefaultConstructor7395? ClassDecl->hasInClassInitializer() ||7396!ClassDecl->hasVariantMembers()7397: true;73987399// -- the class shall not have any virtual base classes;7400if (Ctor && ClassDecl->getNumVBases())7401return false;74027403// C++1y [class.copy]p26:7404// -- [the class] is a literal type, and7405if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)7406return false;74077408// -- every constructor involved in initializing [...] base class7409// sub-objects shall be a constexpr constructor;7410// -- the assignment operator selected to copy/move each direct base7411// class is a constexpr function, and7412if (!S.getLangOpts().CPlusPlus23) {7413for (const auto &B : ClassDecl->bases()) {7414const RecordType *BaseType = B.getType()->getAs<RecordType>();7415if (!BaseType)7416continue;7417CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());7418if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,7419InheritedCtor, Inherited))7420return false;7421}7422}74237424// -- every constructor involved in initializing non-static data members7425// [...] shall be a constexpr constructor;7426// -- every non-static data member and base class sub-object shall be7427// initialized7428// -- for each non-static data member of X that is of class type (or array7429// thereof), the assignment operator selected to copy/move that member is7430// a constexpr function7431if (!S.getLangOpts().CPlusPlus23) {7432for (const auto *F : ClassDecl->fields()) {7433if (F->isInvalidDecl())7434continue;7435if (CSM == CXXSpecialMemberKind::DefaultConstructor &&7436F->hasInClassInitializer())7437continue;7438QualType BaseType = S.Context.getBaseElementType(F->getType());7439if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {7440CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());7441if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,7442BaseType.getCVRQualifiers(),7443ConstArg && !F->isMutable()))7444return false;7445} else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {7446return false;7447}7448}7449}74507451// All OK, it's constexpr!7452return true;7453}74547455namespace {7456/// RAII object to register a defaulted function as having its exception7457/// specification computed.7458struct ComputingExceptionSpec {7459Sema &S;74607461ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)7462: S(S) {7463Sema::CodeSynthesisContext Ctx;7464Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;7465Ctx.PointOfInstantiation = Loc;7466Ctx.Entity = FD;7467S.pushCodeSynthesisContext(Ctx);7468}7469~ComputingExceptionSpec() {7470S.popCodeSynthesisContext();7471}7472};7473}74747475static Sema::ImplicitExceptionSpecification7476ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,7477CXXMethodDecl *MD,7478CXXSpecialMemberKind CSM,7479Sema::InheritedConstructorInfo *ICI);74807481static Sema::ImplicitExceptionSpecification7482ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,7483FunctionDecl *FD,7484Sema::DefaultedComparisonKind DCK);74857486static Sema::ImplicitExceptionSpecification7487computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {7488auto DFK = S.getDefaultedFunctionKind(FD);7489if (DFK.isSpecialMember())7490return ComputeDefaultedSpecialMemberExceptionSpec(7491S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);7492if (DFK.isComparison())7493return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,7494DFK.asComparison());74957496auto *CD = cast<CXXConstructorDecl>(FD);7497assert(CD->getInheritedConstructor() &&7498"only defaulted functions and inherited constructors have implicit "7499"exception specs");7500Sema::InheritedConstructorInfo ICI(7501S, Loc, CD->getInheritedConstructor().getShadowDecl());7502return ComputeDefaultedSpecialMemberExceptionSpec(7503S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);7504}75057506static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,7507CXXMethodDecl *MD) {7508FunctionProtoType::ExtProtoInfo EPI;75097510// Build an exception specification pointing back at this member.7511EPI.ExceptionSpec.Type = EST_Unevaluated;7512EPI.ExceptionSpec.SourceDecl = MD;75137514// Set the calling convention to the default for C++ instance methods.7515EPI.ExtInfo = EPI.ExtInfo.withCallingConv(7516S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,7517/*IsCXXMethod=*/true));7518return EPI;7519}75207521void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {7522const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();7523if (FPT->getExceptionSpecType() != EST_Unevaluated)7524return;75257526// Evaluate the exception specification.7527auto IES = computeImplicitExceptionSpec(*this, Loc, FD);7528auto ESI = IES.getExceptionSpec();75297530// Update the type of the special member to use it.7531UpdateExceptionSpec(FD, ESI);7532}75337534void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {7535assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");75367537DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);7538if (!DefKind) {7539assert(FD->getDeclContext()->isDependentContext());7540return;7541}75427543if (DefKind.isComparison())7544UnusedPrivateFields.clear();75457546if (DefKind.isSpecialMember()7547? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),7548DefKind.asSpecialMember(),7549FD->getDefaultLoc())7550: CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))7551FD->setInvalidDecl();7552}75537554bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,7555CXXSpecialMemberKind CSM,7556SourceLocation DefaultLoc) {7557CXXRecordDecl *RD = MD->getParent();75587559assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&7560"not an explicitly-defaulted special member");75617562// Defer all checking for special members of a dependent type.7563if (RD->isDependentType())7564return false;75657566// Whether this was the first-declared instance of the constructor.7567// This affects whether we implicitly add an exception spec and constexpr.7568bool First = MD == MD->getCanonicalDecl();75697570bool HadError = false;75717572// C++11 [dcl.fct.def.default]p1:7573// A function that is explicitly defaulted shall7574// -- be a special member function [...] (checked elsewhere),7575// -- have the same type (except for ref-qualifiers, and except that a7576// copy operation can take a non-const reference) as an implicit7577// declaration, and7578// -- not have default arguments.7579// C++2a changes the second bullet to instead delete the function if it's7580// defaulted on its first declaration, unless it's "an assignment operator,7581// and its return type differs or its parameter type is not a reference".7582bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;7583bool ShouldDeleteForTypeMismatch = false;7584unsigned ExpectedParams = 1;7585if (CSM == CXXSpecialMemberKind::DefaultConstructor ||7586CSM == CXXSpecialMemberKind::Destructor)7587ExpectedParams = 0;7588if (MD->getNumExplicitParams() != ExpectedParams) {7589// This checks for default arguments: a copy or move constructor with a7590// default argument is classified as a default constructor, and assignment7591// operations and destructors can't have default arguments.7592Diag(MD->getLocation(), diag::err_defaulted_special_member_params)7593<< llvm::to_underlying(CSM) << MD->getSourceRange();7594HadError = true;7595} else if (MD->isVariadic()) {7596if (DeleteOnTypeMismatch)7597ShouldDeleteForTypeMismatch = true;7598else {7599Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)7600<< llvm::to_underlying(CSM) << MD->getSourceRange();7601HadError = true;7602}7603}76047605const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();76067607bool CanHaveConstParam = false;7608if (CSM == CXXSpecialMemberKind::CopyConstructor)7609CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();7610else if (CSM == CXXSpecialMemberKind::CopyAssignment)7611CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();76127613QualType ReturnType = Context.VoidTy;7614if (CSM == CXXSpecialMemberKind::CopyAssignment ||7615CSM == CXXSpecialMemberKind::MoveAssignment) {7616// Check for return type matching.7617ReturnType = Type->getReturnType();7618QualType ThisType = MD->getFunctionObjectParameterType();76197620QualType DeclType = Context.getTypeDeclType(RD);7621DeclType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,7622DeclType, nullptr);7623DeclType = Context.getAddrSpaceQualType(7624DeclType, ThisType.getQualifiers().getAddressSpace());7625QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);76267627if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {7628Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)7629<< (CSM == CXXSpecialMemberKind::MoveAssignment)7630<< ExpectedReturnType;7631HadError = true;7632}76337634// A defaulted special member cannot have cv-qualifiers.7635if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {7636if (DeleteOnTypeMismatch)7637ShouldDeleteForTypeMismatch = true;7638else {7639Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)7640<< (CSM == CXXSpecialMemberKind::MoveAssignment)7641<< getLangOpts().CPlusPlus14;7642HadError = true;7643}7644}7645// [C++23][dcl.fct.def.default]/p2.27646// if F2 has an implicit object parameter of type “reference to C”,7647// F1 may be an explicit object member function whose explicit object7648// parameter is of (possibly different) type “reference to C”,7649// in which case the type of F1 would differ from the type of F27650// in that the type of F1 has an additional parameter;7651if (!Context.hasSameType(7652ThisType.getNonReferenceType().getUnqualifiedType(),7653Context.getRecordType(RD))) {7654if (DeleteOnTypeMismatch)7655ShouldDeleteForTypeMismatch = true;7656else {7657Diag(MD->getLocation(),7658diag::err_defaulted_special_member_explicit_object_mismatch)7659<< (CSM == CXXSpecialMemberKind::MoveAssignment) << RD7660<< MD->getSourceRange();7661HadError = true;7662}7663}7664}76657666// Check for parameter type matching.7667QualType ArgType =7668ExpectedParams7669? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)7670: QualType();7671bool HasConstParam = false;7672if (ExpectedParams && ArgType->isReferenceType()) {7673// Argument must be reference to possibly-const T.7674QualType ReferentType = ArgType->getPointeeType();7675HasConstParam = ReferentType.isConstQualified();76767677if (ReferentType.isVolatileQualified()) {7678if (DeleteOnTypeMismatch)7679ShouldDeleteForTypeMismatch = true;7680else {7681Diag(MD->getLocation(),7682diag::err_defaulted_special_member_volatile_param)7683<< llvm::to_underlying(CSM);7684HadError = true;7685}7686}76877688if (HasConstParam && !CanHaveConstParam) {7689if (DeleteOnTypeMismatch)7690ShouldDeleteForTypeMismatch = true;7691else if (CSM == CXXSpecialMemberKind::CopyConstructor ||7692CSM == CXXSpecialMemberKind::CopyAssignment) {7693Diag(MD->getLocation(),7694diag::err_defaulted_special_member_copy_const_param)7695<< (CSM == CXXSpecialMemberKind::CopyAssignment);7696// FIXME: Explain why this special member can't be const.7697HadError = true;7698} else {7699Diag(MD->getLocation(),7700diag::err_defaulted_special_member_move_const_param)7701<< (CSM == CXXSpecialMemberKind::MoveAssignment);7702HadError = true;7703}7704}7705} else if (ExpectedParams) {7706// A copy assignment operator can take its argument by value, but a7707// defaulted one cannot.7708assert(CSM == CXXSpecialMemberKind::CopyAssignment &&7709"unexpected non-ref argument");7710Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);7711HadError = true;7712}77137714// C++11 [dcl.fct.def.default]p2:7715// An explicitly-defaulted function may be declared constexpr only if it7716// would have been implicitly declared as constexpr,7717// Do not apply this rule to members of class templates, since core issue 13587718// makes such functions always instantiate to constexpr functions. For7719// functions which cannot be constexpr (for non-constructors in C++11 and for7720// destructors in C++14 and C++17), this is checked elsewhere.7721//7722// FIXME: This should not apply if the member is deleted.7723bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,7724HasConstParam);77257726// C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):7727// If the instantiated template specialization of a constexpr function7728// template or member function of a class template would fail to satisfy7729// the requirements for a constexpr function or constexpr constructor, that7730// specialization is still a constexpr function or constexpr constructor,7731// even though a call to such a function cannot appear in a constant7732// expression.7733if (MD->isTemplateInstantiation() && MD->isConstexpr())7734Constexpr = true;77357736if ((getLangOpts().CPlusPlus20 ||7737(getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)7738: isa<CXXConstructorDecl>(MD))) &&7739MD->isConstexpr() && !Constexpr &&7740MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {7741if (!MD->isConsteval() && RD->getNumVBases()) {7742Diag(MD->getBeginLoc(),7743diag::err_incorrect_defaulted_constexpr_with_vb)7744<< llvm::to_underlying(CSM);7745for (const auto &I : RD->vbases())7746Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);7747} else {7748Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)7749<< llvm::to_underlying(CSM) << MD->isConsteval();7750}7751HadError = true;7752// FIXME: Explain why the special member can't be constexpr.7753}77547755if (First) {7756// C++2a [dcl.fct.def.default]p3:7757// If a function is explicitly defaulted on its first declaration, it is7758// implicitly considered to be constexpr if the implicit declaration7759// would be.7760MD->setConstexprKind(Constexpr ? (MD->isConsteval()7761? ConstexprSpecKind::Consteval7762: ConstexprSpecKind::Constexpr)7763: ConstexprSpecKind::Unspecified);77647765if (!Type->hasExceptionSpec()) {7766// C++2a [except.spec]p3:7767// If a declaration of a function does not have a noexcept-specifier7768// [and] is defaulted on its first declaration, [...] the exception7769// specification is as specified below7770FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();7771EPI.ExceptionSpec.Type = EST_Unevaluated;7772EPI.ExceptionSpec.SourceDecl = MD;7773MD->setType(7774Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));7775}7776}77777778if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {7779if (First) {7780SetDeclDeleted(MD, MD->getLocation());7781if (!inTemplateInstantiation() && !HadError) {7782Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)7783<< llvm::to_underlying(CSM);7784if (ShouldDeleteForTypeMismatch) {7785Diag(MD->getLocation(), diag::note_deleted_type_mismatch)7786<< llvm::to_underlying(CSM);7787} else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,7788/*Diagnose*/ true) &&7789DefaultLoc.isValid()) {7790Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)7791<< FixItHint::CreateReplacement(DefaultLoc, "delete");7792}7793}7794if (ShouldDeleteForTypeMismatch && !HadError) {7795Diag(MD->getLocation(),7796diag::warn_cxx17_compat_defaulted_method_type_mismatch)7797<< llvm::to_underlying(CSM);7798}7799} else {7800// C++11 [dcl.fct.def.default]p4:7801// [For a] user-provided explicitly-defaulted function [...] if such a7802// function is implicitly defined as deleted, the program is ill-formed.7803Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)7804<< llvm::to_underlying(CSM);7805assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");7806ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);7807HadError = true;7808}7809}78107811return HadError;7812}78137814namespace {7815/// Helper class for building and checking a defaulted comparison.7816///7817/// Defaulted functions are built in two phases:7818///7819/// * First, the set of operations that the function will perform are7820/// identified, and some of them are checked. If any of the checked7821/// operations is invalid in certain ways, the comparison function is7822/// defined as deleted and no body is built.7823/// * Then, if the function is not defined as deleted, the body is built.7824///7825/// This is accomplished by performing two visitation steps over the eventual7826/// body of the function.7827template<typename Derived, typename ResultList, typename Result,7828typename Subobject>7829class DefaultedComparisonVisitor {7830public:7831using DefaultedComparisonKind = Sema::DefaultedComparisonKind;78327833DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,7834DefaultedComparisonKind DCK)7835: S(S), RD(RD), FD(FD), DCK(DCK) {7836if (auto *Info = FD->getDefalutedOrDeletedInfo()) {7837// FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an7838// UnresolvedSet to avoid this copy.7839Fns.assign(Info->getUnqualifiedLookups().begin(),7840Info->getUnqualifiedLookups().end());7841}7842}78437844ResultList visit() {7845// The type of an lvalue naming a parameter of this function.7846QualType ParamLvalType =7847FD->getParamDecl(0)->getType().getNonReferenceType();78487849ResultList Results;78507851switch (DCK) {7852case DefaultedComparisonKind::None:7853llvm_unreachable("not a defaulted comparison");78547855case DefaultedComparisonKind::Equal:7856case DefaultedComparisonKind::ThreeWay:7857getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());7858return Results;78597860case DefaultedComparisonKind::NotEqual:7861case DefaultedComparisonKind::Relational:7862Results.add(getDerived().visitExpandedSubobject(7863ParamLvalType, getDerived().getCompleteObject()));7864return Results;7865}7866llvm_unreachable("");7867}78687869protected:7870Derived &getDerived() { return static_cast<Derived&>(*this); }78717872/// Visit the expanded list of subobjects of the given type, as specified in7873/// C++2a [class.compare.default].7874///7875/// \return \c true if the ResultList object said we're done, \c false if not.7876bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,7877Qualifiers Quals) {7878// C++2a [class.compare.default]p4:7879// The direct base class subobjects of C7880for (CXXBaseSpecifier &Base : Record->bases())7881if (Results.add(getDerived().visitSubobject(7882S.Context.getQualifiedType(Base.getType(), Quals),7883getDerived().getBase(&Base))))7884return true;78857886// followed by the non-static data members of C7887for (FieldDecl *Field : Record->fields()) {7888// C++23 [class.bit]p2:7889// Unnamed bit-fields are not members ...7890if (Field->isUnnamedBitField())7891continue;7892// Recursively expand anonymous structs.7893if (Field->isAnonymousStructOrUnion()) {7894if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),7895Quals))7896return true;7897continue;7898}78997900// Figure out the type of an lvalue denoting this field.7901Qualifiers FieldQuals = Quals;7902if (Field->isMutable())7903FieldQuals.removeConst();7904QualType FieldType =7905S.Context.getQualifiedType(Field->getType(), FieldQuals);79067907if (Results.add(getDerived().visitSubobject(7908FieldType, getDerived().getField(Field))))7909return true;7910}79117912// form a list of subobjects.7913return false;7914}79157916Result visitSubobject(QualType Type, Subobject Subobj) {7917// In that list, any subobject of array type is recursively expanded7918const ArrayType *AT = S.Context.getAsArrayType(Type);7919if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))7920return getDerived().visitSubobjectArray(CAT->getElementType(),7921CAT->getSize(), Subobj);7922return getDerived().visitExpandedSubobject(Type, Subobj);7923}79247925Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,7926Subobject Subobj) {7927return getDerived().visitSubobject(Type, Subobj);7928}79297930protected:7931Sema &S;7932CXXRecordDecl *RD;7933FunctionDecl *FD;7934DefaultedComparisonKind DCK;7935UnresolvedSet<16> Fns;7936};79377938/// Information about a defaulted comparison, as determined by7939/// DefaultedComparisonAnalyzer.7940struct DefaultedComparisonInfo {7941bool Deleted = false;7942bool Constexpr = true;7943ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;79447945static DefaultedComparisonInfo deleted() {7946DefaultedComparisonInfo Deleted;7947Deleted.Deleted = true;7948return Deleted;7949}79507951bool add(const DefaultedComparisonInfo &R) {7952Deleted |= R.Deleted;7953Constexpr &= R.Constexpr;7954Category = commonComparisonType(Category, R.Category);7955return Deleted;7956}7957};79587959/// An element in the expanded list of subobjects of a defaulted comparison, as7960/// specified in C++2a [class.compare.default]p4.7961struct DefaultedComparisonSubobject {7962enum { CompleteObject, Member, Base } Kind;7963NamedDecl *Decl;7964SourceLocation Loc;7965};79667967/// A visitor over the notional body of a defaulted comparison that determines7968/// whether that body would be deleted or constexpr.7969class DefaultedComparisonAnalyzer7970: public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,7971DefaultedComparisonInfo,7972DefaultedComparisonInfo,7973DefaultedComparisonSubobject> {7974public:7975enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };79767977private:7978DiagnosticKind Diagnose;79797980public:7981using Base = DefaultedComparisonVisitor;7982using Result = DefaultedComparisonInfo;7983using Subobject = DefaultedComparisonSubobject;79847985friend Base;79867987DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,7988DefaultedComparisonKind DCK,7989DiagnosticKind Diagnose = NoDiagnostics)7990: Base(S, RD, FD, DCK), Diagnose(Diagnose) {}79917992Result visit() {7993if ((DCK == DefaultedComparisonKind::Equal ||7994DCK == DefaultedComparisonKind::ThreeWay) &&7995RD->hasVariantMembers()) {7996// C++2a [class.compare.default]p2 [P2002R0]:7997// A defaulted comparison operator function for class C is defined as7998// deleted if [...] C has variant members.7999if (Diagnose == ExplainDeleted) {8000S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)8001<< FD << RD->isUnion() << RD;8002}8003return Result::deleted();8004}80058006return Base::visit();8007}80088009private:8010Subobject getCompleteObject() {8011return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};8012}80138014Subobject getBase(CXXBaseSpecifier *Base) {8015return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),8016Base->getBaseTypeLoc()};8017}80188019Subobject getField(FieldDecl *Field) {8020return Subobject{Subobject::Member, Field, Field->getLocation()};8021}80228023Result visitExpandedSubobject(QualType Type, Subobject Subobj) {8024// C++2a [class.compare.default]p2 [P2002R0]:8025// A defaulted <=> or == operator function for class C is defined as8026// deleted if any non-static data member of C is of reference type8027if (Type->isReferenceType()) {8028if (Diagnose == ExplainDeleted) {8029S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)8030<< FD << RD;8031}8032return Result::deleted();8033}80348035// [...] Let xi be an lvalue denoting the ith element [...]8036OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);8037Expr *Args[] = {&Xi, &Xi};80388039// All operators start by trying to apply that same operator recursively.8040OverloadedOperatorKind OO = FD->getOverloadedOperator();8041assert(OO != OO_None && "not an overloaded operator!");8042return visitBinaryOperator(OO, Args, Subobj);8043}80448045Result8046visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,8047Subobject Subobj,8048OverloadCandidateSet *SpaceshipCandidates = nullptr) {8049// Note that there is no need to consider rewritten candidates here if8050// we've already found there is no viable 'operator<=>' candidate (and are8051// considering synthesizing a '<=>' from '==' and '<').8052OverloadCandidateSet CandidateSet(8053FD->getLocation(), OverloadCandidateSet::CSK_Operator,8054OverloadCandidateSet::OperatorRewriteInfo(8055OO, FD->getLocation(),8056/*AllowRewrittenCandidates=*/!SpaceshipCandidates));80578058/// C++2a [class.compare.default]p1 [P2002R0]:8059/// [...] the defaulted function itself is never a candidate for overload8060/// resolution [...]8061CandidateSet.exclude(FD);80628063if (Args[0]->getType()->isOverloadableType())8064S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);8065else8066// FIXME: We determine whether this is a valid expression by checking to8067// see if there's a viable builtin operator candidate for it. That isn't8068// really what the rules ask us to do, but should give the right results.8069S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);80708071Result R;80728073OverloadCandidateSet::iterator Best;8074switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {8075case OR_Success: {8076// C++2a [class.compare.secondary]p2 [P2002R0]:8077// The operator function [...] is defined as deleted if [...] the8078// candidate selected by overload resolution is not a rewritten8079// candidate.8080if ((DCK == DefaultedComparisonKind::NotEqual ||8081DCK == DefaultedComparisonKind::Relational) &&8082!Best->RewriteKind) {8083if (Diagnose == ExplainDeleted) {8084if (Best->Function) {8085S.Diag(Best->Function->getLocation(),8086diag::note_defaulted_comparison_not_rewritten_callee)8087<< FD;8088} else {8089assert(Best->Conversions.size() == 2 &&8090Best->Conversions[0].isUserDefined() &&8091"non-user-defined conversion from class to built-in "8092"comparison");8093S.Diag(Best->Conversions[0]8094.UserDefined.FoundConversionFunction.getDecl()8095->getLocation(),8096diag::note_defaulted_comparison_not_rewritten_conversion)8097<< FD;8098}8099}8100return Result::deleted();8101}81028103// Throughout C++2a [class.compare]: if overload resolution does not8104// result in a usable function, the candidate function is defined as8105// deleted. This requires that we selected an accessible function.8106//8107// Note that this only considers the access of the function when named8108// within the type of the subobject, and not the access path for any8109// derived-to-base conversion.8110CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();8111if (ArgClass && Best->FoundDecl.getDecl() &&8112Best->FoundDecl.getDecl()->isCXXClassMember()) {8113QualType ObjectType = Subobj.Kind == Subobject::Member8114? Args[0]->getType()8115: S.Context.getRecordType(RD);8116if (!S.isMemberAccessibleForDeletion(8117ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,8118Diagnose == ExplainDeleted8119? S.PDiag(diag::note_defaulted_comparison_inaccessible)8120<< FD << Subobj.Kind << Subobj.Decl8121: S.PDiag()))8122return Result::deleted();8123}81248125bool NeedsDeducing =8126OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();81278128if (FunctionDecl *BestFD = Best->Function) {8129// C++2a [class.compare.default]p3 [P2002R0]:8130// A defaulted comparison function is constexpr-compatible if8131// [...] no overlod resolution performed [...] results in a8132// non-constexpr function.8133assert(!BestFD->isDeleted() && "wrong overload resolution result");8134// If it's not constexpr, explain why not.8135if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {8136if (Subobj.Kind != Subobject::CompleteObject)8137S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)8138<< Subobj.Kind << Subobj.Decl;8139S.Diag(BestFD->getLocation(),8140diag::note_defaulted_comparison_not_constexpr_here);8141// Bail out after explaining; we don't want any more notes.8142return Result::deleted();8143}8144R.Constexpr &= BestFD->isConstexpr();81458146if (NeedsDeducing) {8147// If any callee has an undeduced return type, deduce it now.8148// FIXME: It's not clear how a failure here should be handled. For8149// now, we produce an eager diagnostic, because that is forward8150// compatible with most (all?) other reasonable options.8151if (BestFD->getReturnType()->isUndeducedType() &&8152S.DeduceReturnType(BestFD, FD->getLocation(),8153/*Diagnose=*/false)) {8154// Don't produce a duplicate error when asked to explain why the8155// comparison is deleted: we diagnosed that when initially checking8156// the defaulted operator.8157if (Diagnose == NoDiagnostics) {8158S.Diag(8159FD->getLocation(),8160diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)8161<< Subobj.Kind << Subobj.Decl;8162S.Diag(8163Subobj.Loc,8164diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)8165<< Subobj.Kind << Subobj.Decl;8166S.Diag(BestFD->getLocation(),8167diag::note_defaulted_comparison_cannot_deduce_callee)8168<< Subobj.Kind << Subobj.Decl;8169}8170return Result::deleted();8171}8172auto *Info = S.Context.CompCategories.lookupInfoForType(8173BestFD->getCallResultType());8174if (!Info) {8175if (Diagnose == ExplainDeleted) {8176S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)8177<< Subobj.Kind << Subobj.Decl8178<< BestFD->getCallResultType().withoutLocalFastQualifiers();8179S.Diag(BestFD->getLocation(),8180diag::note_defaulted_comparison_cannot_deduce_callee)8181<< Subobj.Kind << Subobj.Decl;8182}8183return Result::deleted();8184}8185R.Category = Info->Kind;8186}8187} else {8188QualType T = Best->BuiltinParamTypes[0];8189assert(T == Best->BuiltinParamTypes[1] &&8190"builtin comparison for different types?");8191assert(Best->BuiltinParamTypes[2].isNull() &&8192"invalid builtin comparison");81938194if (NeedsDeducing) {8195std::optional<ComparisonCategoryType> Cat =8196getComparisonCategoryForBuiltinCmp(T);8197assert(Cat && "no category for builtin comparison?");8198R.Category = *Cat;8199}8200}82018202// Note that we might be rewriting to a different operator. That call is8203// not considered until we come to actually build the comparison function.8204break;8205}82068207case OR_Ambiguous:8208if (Diagnose == ExplainDeleted) {8209unsigned Kind = 0;8210if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)8211Kind = OO == OO_EqualEqual ? 1 : 2;8212CandidateSet.NoteCandidates(8213PartialDiagnosticAt(8214Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)8215<< FD << Kind << Subobj.Kind << Subobj.Decl),8216S, OCD_AmbiguousCandidates, Args);8217}8218R = Result::deleted();8219break;82208221case OR_Deleted:8222if (Diagnose == ExplainDeleted) {8223if ((DCK == DefaultedComparisonKind::NotEqual ||8224DCK == DefaultedComparisonKind::Relational) &&8225!Best->RewriteKind) {8226S.Diag(Best->Function->getLocation(),8227diag::note_defaulted_comparison_not_rewritten_callee)8228<< FD;8229} else {8230S.Diag(Subobj.Loc,8231diag::note_defaulted_comparison_calls_deleted)8232<< FD << Subobj.Kind << Subobj.Decl;8233S.NoteDeletedFunction(Best->Function);8234}8235}8236R = Result::deleted();8237break;82388239case OR_No_Viable_Function:8240// If there's no usable candidate, we're done unless we can rewrite a8241// '<=>' in terms of '==' and '<'.8242if (OO == OO_Spaceship &&8243S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {8244// For any kind of comparison category return type, we need a usable8245// '==' and a usable '<'.8246if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,8247&CandidateSet)))8248R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));8249break;8250}82518252if (Diagnose == ExplainDeleted) {8253S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)8254<< FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)8255<< Subobj.Kind << Subobj.Decl;82568257// For a three-way comparison, list both the candidates for the8258// original operator and the candidates for the synthesized operator.8259if (SpaceshipCandidates) {8260SpaceshipCandidates->NoteCandidates(8261S, Args,8262SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,8263Args, FD->getLocation()));8264S.Diag(Subobj.Loc,8265diag::note_defaulted_comparison_no_viable_function_synthesized)8266<< (OO == OO_EqualEqual ? 0 : 1);8267}82688269CandidateSet.NoteCandidates(8270S, Args,8271CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,8272FD->getLocation()));8273}8274R = Result::deleted();8275break;8276}82778278return R;8279}8280};82818282/// A list of statements.8283struct StmtListResult {8284bool IsInvalid = false;8285llvm::SmallVector<Stmt*, 16> Stmts;82868287bool add(const StmtResult &S) {8288IsInvalid |= S.isInvalid();8289if (IsInvalid)8290return true;8291Stmts.push_back(S.get());8292return false;8293}8294};82958296/// A visitor over the notional body of a defaulted comparison that synthesizes8297/// the actual body.8298class DefaultedComparisonSynthesizer8299: public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,8300StmtListResult, StmtResult,8301std::pair<ExprResult, ExprResult>> {8302SourceLocation Loc;8303unsigned ArrayDepth = 0;83048305public:8306using Base = DefaultedComparisonVisitor;8307using ExprPair = std::pair<ExprResult, ExprResult>;83088309friend Base;83108311DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,8312DefaultedComparisonKind DCK,8313SourceLocation BodyLoc)8314: Base(S, RD, FD, DCK), Loc(BodyLoc) {}83158316/// Build a suitable function body for this defaulted comparison operator.8317StmtResult build() {8318Sema::CompoundScopeRAII CompoundScope(S);83198320StmtListResult Stmts = visit();8321if (Stmts.IsInvalid)8322return StmtError();83238324ExprResult RetVal;8325switch (DCK) {8326case DefaultedComparisonKind::None:8327llvm_unreachable("not a defaulted comparison");83288329case DefaultedComparisonKind::Equal: {8330// C++2a [class.eq]p3:8331// [...] compar[e] the corresponding elements [...] until the first8332// index i where xi == yi yields [...] false. If no such index exists,8333// V is true. Otherwise, V is false.8334//8335// Join the comparisons with '&&'s and return the result. Use a right8336// fold (traversing the conditions right-to-left), because that8337// short-circuits more naturally.8338auto OldStmts = std::move(Stmts.Stmts);8339Stmts.Stmts.clear();8340ExprResult CmpSoFar;8341// Finish a particular comparison chain.8342auto FinishCmp = [&] {8343if (Expr *Prior = CmpSoFar.get()) {8344// Convert the last expression to 'return ...;'8345if (RetVal.isUnset() && Stmts.Stmts.empty())8346RetVal = CmpSoFar;8347// Convert any prior comparison to 'if (!(...)) return false;'8348else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))8349return true;8350CmpSoFar = ExprResult();8351}8352return false;8353};8354for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {8355Expr *E = dyn_cast<Expr>(EAsStmt);8356if (!E) {8357// Found an array comparison.8358if (FinishCmp() || Stmts.add(EAsStmt))8359return StmtError();8360continue;8361}83628363if (CmpSoFar.isUnset()) {8364CmpSoFar = E;8365continue;8366}8367CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());8368if (CmpSoFar.isInvalid())8369return StmtError();8370}8371if (FinishCmp())8372return StmtError();8373std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());8374// If no such index exists, V is true.8375if (RetVal.isUnset())8376RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);8377break;8378}83798380case DefaultedComparisonKind::ThreeWay: {8381// Per C++2a [class.spaceship]p3, as a fallback add:8382// return static_cast<R>(std::strong_ordering::equal);8383QualType StrongOrdering = S.CheckComparisonCategoryType(8384ComparisonCategoryType::StrongOrdering, Loc,8385Sema::ComparisonCategoryUsage::DefaultedOperator);8386if (StrongOrdering.isNull())8387return StmtError();8388VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)8389.getValueInfo(ComparisonCategoryResult::Equal)8390->VD;8391RetVal = getDecl(EqualVD);8392if (RetVal.isInvalid())8393return StmtError();8394RetVal = buildStaticCastToR(RetVal.get());8395break;8396}83978398case DefaultedComparisonKind::NotEqual:8399case DefaultedComparisonKind::Relational:8400RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());8401break;8402}84038404// Build the final return statement.8405if (RetVal.isInvalid())8406return StmtError();8407StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());8408if (ReturnStmt.isInvalid())8409return StmtError();8410Stmts.Stmts.push_back(ReturnStmt.get());84118412return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);8413}84148415private:8416ExprResult getDecl(ValueDecl *VD) {8417return S.BuildDeclarationNameExpr(8418CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);8419}84208421ExprResult getParam(unsigned I) {8422ParmVarDecl *PD = FD->getParamDecl(I);8423return getDecl(PD);8424}84258426ExprPair getCompleteObject() {8427unsigned Param = 0;8428ExprResult LHS;8429if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);8430MD && MD->isImplicitObjectMemberFunction()) {8431// LHS is '*this'.8432LHS = S.ActOnCXXThis(Loc);8433if (!LHS.isInvalid())8434LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());8435} else {8436LHS = getParam(Param++);8437}8438ExprResult RHS = getParam(Param++);8439assert(Param == FD->getNumParams());8440return {LHS, RHS};8441}84428443ExprPair getBase(CXXBaseSpecifier *Base) {8444ExprPair Obj = getCompleteObject();8445if (Obj.first.isInvalid() || Obj.second.isInvalid())8446return {ExprError(), ExprError()};8447CXXCastPath Path = {Base};8448return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),8449CK_DerivedToBase, VK_LValue, &Path),8450S.ImpCastExprToType(Obj.second.get(), Base->getType(),8451CK_DerivedToBase, VK_LValue, &Path)};8452}84538454ExprPair getField(FieldDecl *Field) {8455ExprPair Obj = getCompleteObject();8456if (Obj.first.isInvalid() || Obj.second.isInvalid())8457return {ExprError(), ExprError()};84588459DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());8460DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);8461return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,8462CXXScopeSpec(), Field, Found, NameInfo),8463S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,8464CXXScopeSpec(), Field, Found, NameInfo)};8465}84668467// FIXME: When expanding a subobject, register a note in the code synthesis8468// stack to say which subobject we're comparing.84698470StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {8471if (Cond.isInvalid())8472return StmtError();84738474ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());8475if (NotCond.isInvalid())8476return StmtError();84778478ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);8479assert(!False.isInvalid() && "should never fail");8480StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());8481if (ReturnFalse.isInvalid())8482return StmtError();84838484return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,8485S.ActOnCondition(nullptr, Loc, NotCond.get(),8486Sema::ConditionKind::Boolean),8487Loc, ReturnFalse.get(), SourceLocation(), nullptr);8488}84898490StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,8491ExprPair Subobj) {8492QualType SizeType = S.Context.getSizeType();8493Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));84948495// Build 'size_t i$n = 0'.8496IdentifierInfo *IterationVarName = nullptr;8497{8498SmallString<8> Str;8499llvm::raw_svector_ostream OS(Str);8500OS << "i" << ArrayDepth;8501IterationVarName = &S.Context.Idents.get(OS.str());8502}8503VarDecl *IterationVar = VarDecl::Create(8504S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,8505S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);8506llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);8507IterationVar->setInit(8508IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));8509Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);85108511auto IterRef = [&] {8512ExprResult Ref = S.BuildDeclarationNameExpr(8513CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),8514IterationVar);8515assert(!Ref.isInvalid() && "can't reference our own variable?");8516return Ref.get();8517};85188519// Build 'i$n != Size'.8520ExprResult Cond = S.CreateBuiltinBinOp(8521Loc, BO_NE, IterRef(),8522IntegerLiteral::Create(S.Context, Size, SizeType, Loc));8523assert(!Cond.isInvalid() && "should never fail");85248525// Build '++i$n'.8526ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());8527assert(!Inc.isInvalid() && "should never fail");85288529// Build 'a[i$n]' and 'b[i$n]'.8530auto Index = [&](ExprResult E) {8531if (E.isInvalid())8532return ExprError();8533return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);8534};8535Subobj.first = Index(Subobj.first);8536Subobj.second = Index(Subobj.second);85378538// Compare the array elements.8539++ArrayDepth;8540StmtResult Substmt = visitSubobject(Type, Subobj);8541--ArrayDepth;85428543if (Substmt.isInvalid())8544return StmtError();85458546// For the inner level of an 'operator==', build 'if (!cmp) return false;'.8547// For outer levels or for an 'operator<=>' we already have a suitable8548// statement that returns as necessary.8549if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {8550assert(DCK == DefaultedComparisonKind::Equal &&8551"should have non-expression statement");8552Substmt = buildIfNotCondReturnFalse(ElemCmp);8553if (Substmt.isInvalid())8554return StmtError();8555}85568557// Build 'for (...) ...'8558return S.ActOnForStmt(Loc, Loc, Init,8559S.ActOnCondition(nullptr, Loc, Cond.get(),8560Sema::ConditionKind::Boolean),8561S.MakeFullDiscardedValueExpr(Inc.get()), Loc,8562Substmt.get());8563}85648565StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {8566if (Obj.first.isInvalid() || Obj.second.isInvalid())8567return StmtError();85688569OverloadedOperatorKind OO = FD->getOverloadedOperator();8570BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);8571ExprResult Op;8572if (Type->isOverloadableType())8573Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),8574Obj.second.get(), /*PerformADL=*/true,8575/*AllowRewrittenCandidates=*/true, FD);8576else8577Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());8578if (Op.isInvalid())8579return StmtError();85808581switch (DCK) {8582case DefaultedComparisonKind::None:8583llvm_unreachable("not a defaulted comparison");85848585case DefaultedComparisonKind::Equal:8586// Per C++2a [class.eq]p2, each comparison is individually contextually8587// converted to bool.8588Op = S.PerformContextuallyConvertToBool(Op.get());8589if (Op.isInvalid())8590return StmtError();8591return Op.get();85928593case DefaultedComparisonKind::ThreeWay: {8594// Per C++2a [class.spaceship]p3, form:8595// if (R cmp = static_cast<R>(op); cmp != 0)8596// return cmp;8597QualType R = FD->getReturnType();8598Op = buildStaticCastToR(Op.get());8599if (Op.isInvalid())8600return StmtError();86018602// R cmp = ...;8603IdentifierInfo *Name = &S.Context.Idents.get("cmp");8604VarDecl *VD =8605VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,8606S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);8607S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);8608Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);86098610// cmp != 08611ExprResult VDRef = getDecl(VD);8612if (VDRef.isInvalid())8613return StmtError();8614llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);8615Expr *Zero =8616IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);8617ExprResult Comp;8618if (VDRef.get()->getType()->isOverloadableType())8619Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,8620true, FD);8621else8622Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);8623if (Comp.isInvalid())8624return StmtError();8625Sema::ConditionResult Cond = S.ActOnCondition(8626nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);8627if (Cond.isInvalid())8628return StmtError();86298630// return cmp;8631VDRef = getDecl(VD);8632if (VDRef.isInvalid())8633return StmtError();8634StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());8635if (ReturnStmt.isInvalid())8636return StmtError();86378638// if (...)8639return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,8640Loc, ReturnStmt.get(),8641/*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);8642}86438644case DefaultedComparisonKind::NotEqual:8645case DefaultedComparisonKind::Relational:8646// C++2a [class.compare.secondary]p2:8647// Otherwise, the operator function yields x @ y.8648return Op.get();8649}8650llvm_unreachable("");8651}86528653/// Build "static_cast<R>(E)".8654ExprResult buildStaticCastToR(Expr *E) {8655QualType R = FD->getReturnType();8656assert(!R->isUndeducedType() && "type should have been deduced already");86578658// Don't bother forming a no-op cast in the common case.8659if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))8660return E;8661return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,8662S.Context.getTrivialTypeSourceInfo(R, Loc), E,8663SourceRange(Loc, Loc), SourceRange(Loc, Loc));8664}8665};8666}86678668/// Perform the unqualified lookups that might be needed to form a defaulted8669/// comparison function for the given operator.8670static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,8671UnresolvedSetImpl &Operators,8672OverloadedOperatorKind Op) {8673auto Lookup = [&](OverloadedOperatorKind OO) {8674Self.LookupOverloadedOperatorName(OO, S, Operators);8675};86768677// Every defaulted operator looks up itself.8678Lookup(Op);8679// ... and the rewritten form of itself, if any.8680if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))8681Lookup(ExtraOp);86828683// For 'operator<=>', we also form a 'cmp != 0' expression, and might8684// synthesize a three-way comparison from '<' and '=='. In a dependent8685// context, we also need to look up '==' in case we implicitly declare a8686// defaulted 'operator=='.8687if (Op == OO_Spaceship) {8688Lookup(OO_ExclaimEqual);8689Lookup(OO_Less);8690Lookup(OO_EqualEqual);8691}8692}86938694bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,8695DefaultedComparisonKind DCK) {8696assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");86978698// Perform any unqualified lookups we're going to need to default this8699// function.8700if (S) {8701UnresolvedSet<32> Operators;8702lookupOperatorsForDefaultedComparison(*this, S, Operators,8703FD->getOverloadedOperator());8704FD->setDefaultedOrDeletedInfo(8705FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(8706Context, Operators.pairs()));8707}87088709// C++2a [class.compare.default]p1:8710// A defaulted comparison operator function for some class C shall be a8711// non-template function declared in the member-specification of C that is8712// -- a non-static const non-volatile member of C having one parameter of8713// type const C& and either no ref-qualifier or the ref-qualifier &, or8714// -- a friend of C having two parameters of type const C& or two8715// parameters of type C.87168717CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());8718bool IsMethod = isa<CXXMethodDecl>(FD);8719if (IsMethod) {8720auto *MD = cast<CXXMethodDecl>(FD);8721assert(!MD->isStatic() && "comparison function cannot be a static member");87228723if (MD->getRefQualifier() == RQ_RValue) {8724Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);87258726// Remove the ref qualifier to recover.8727const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8728FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8729EPI.RefQualifier = RQ_None;8730MD->setType(Context.getFunctionType(FPT->getReturnType(),8731FPT->getParamTypes(), EPI));8732}87338734// If we're out-of-class, this is the class we're comparing.8735if (!RD)8736RD = MD->getParent();8737QualType T = MD->getFunctionObjectParameterType();8738if (!T.isConstQualified()) {8739SourceLocation Loc, InsertLoc;8740if (MD->isExplicitObjectMemberFunction()) {8741Loc = MD->getParamDecl(0)->getBeginLoc();8742InsertLoc = getLocForEndOfToken(8743MD->getParamDecl(0)->getExplicitObjectParamThisLoc());8744} else {8745Loc = MD->getLocation();8746if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())8747InsertLoc = Loc.getRParenLoc();8748}8749// Don't diagnose an implicit 'operator=='; we will have diagnosed the8750// corresponding defaulted 'operator<=>' already.8751if (!MD->isImplicit()) {8752Diag(Loc, diag::err_defaulted_comparison_non_const)8753<< (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");8754}87558756// Add the 'const' to the type to recover.8757const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8758FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8759EPI.TypeQuals.addConst();8760MD->setType(Context.getFunctionType(FPT->getReturnType(),8761FPT->getParamTypes(), EPI));8762}87638764if (MD->isVolatile()) {8765Diag(MD->getLocation(), diag::err_volatile_comparison_operator);87668767// Remove the 'volatile' from the type to recover.8768const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8769FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8770EPI.TypeQuals.removeVolatile();8771MD->setType(Context.getFunctionType(FPT->getReturnType(),8772FPT->getParamTypes(), EPI));8773}8774}87758776if ((FD->getNumParams() -8777(unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=8778(IsMethod ? 1 : 2)) {8779// Let's not worry about using a variadic template pack here -- who would do8780// such a thing?8781Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)8782<< int(IsMethod) << int(DCK);8783return true;8784}87858786const ParmVarDecl *KnownParm = nullptr;8787for (const ParmVarDecl *Param : FD->parameters()) {8788if (Param->isExplicitObjectParameter())8789continue;8790QualType ParmTy = Param->getType();87918792if (!KnownParm) {8793auto CTy = ParmTy;8794// Is it `T const &`?8795bool Ok = !IsMethod;8796QualType ExpectedTy;8797if (RD)8798ExpectedTy = Context.getRecordType(RD);8799if (auto *Ref = CTy->getAs<ReferenceType>()) {8800CTy = Ref->getPointeeType();8801if (RD)8802ExpectedTy.addConst();8803Ok = true;8804}88058806// Is T a class?8807if (!Ok) {8808} else if (RD) {8809if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))8810Ok = false;8811} else if (auto *CRD = CTy->getAsRecordDecl()) {8812RD = cast<CXXRecordDecl>(CRD);8813} else {8814Ok = false;8815}88168817if (Ok) {8818KnownParm = Param;8819} else {8820// Don't diagnose an implicit 'operator=='; we will have diagnosed the8821// corresponding defaulted 'operator<=>' already.8822if (!FD->isImplicit()) {8823if (RD) {8824QualType PlainTy = Context.getRecordType(RD);8825QualType RefTy =8826Context.getLValueReferenceType(PlainTy.withConst());8827Diag(FD->getLocation(), diag::err_defaulted_comparison_param)8828<< int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy8829<< Param->getSourceRange();8830} else {8831assert(!IsMethod && "should know expected type for method");8832Diag(FD->getLocation(),8833diag::err_defaulted_comparison_param_unknown)8834<< int(DCK) << ParmTy << Param->getSourceRange();8835}8836}8837return true;8838}8839} else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {8840Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)8841<< int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()8842<< ParmTy << Param->getSourceRange();8843return true;8844}8845}88468847assert(RD && "must have determined class");8848if (IsMethod) {8849} else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {8850// In-class, must be a friend decl.8851assert(FD->getFriendObjectKind() && "expected a friend declaration");8852} else {8853// Out of class, require the defaulted comparison to be a friend (of a8854// complete type).8855if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),8856diag::err_defaulted_comparison_not_friend, int(DCK),8857int(1)))8858return true;88598860if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {8861return FD->getCanonicalDecl() ==8862F->getFriendDecl()->getCanonicalDecl();8863})) {8864Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)8865<< int(DCK) << int(0) << RD;8866Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);8867return true;8868}8869}88708871// C++2a [class.eq]p1, [class.rel]p1:8872// A [defaulted comparison other than <=>] shall have a declared return8873// type bool.8874if (DCK != DefaultedComparisonKind::ThreeWay &&8875!FD->getDeclaredReturnType()->isDependentType() &&8876!Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {8877Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)8878<< (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy8879<< FD->getReturnTypeSourceRange();8880return true;8881}8882// C++2a [class.spaceship]p2 [P2002R0]:8883// Let R be the declared return type [...]. If R is auto, [...]. Otherwise,8884// R shall not contain a placeholder type.8885if (QualType RT = FD->getDeclaredReturnType();8886DCK == DefaultedComparisonKind::ThreeWay &&8887RT->getContainedDeducedType() &&8888(!Context.hasSameType(RT, Context.getAutoDeductType()) ||8889RT->getContainedAutoType()->isConstrained())) {8890Diag(FD->getLocation(),8891diag::err_defaulted_comparison_deduced_return_type_not_auto)8892<< (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy8893<< FD->getReturnTypeSourceRange();8894return true;8895}88968897// For a defaulted function in a dependent class, defer all remaining checks8898// until instantiation.8899if (RD->isDependentType())8900return false;89018902// Determine whether the function should be defined as deleted.8903DefaultedComparisonInfo Info =8904DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();89058906bool First = FD == FD->getCanonicalDecl();89078908if (!First) {8909if (Info.Deleted) {8910// C++11 [dcl.fct.def.default]p4:8911// [For a] user-provided explicitly-defaulted function [...] if such a8912// function is implicitly defined as deleted, the program is ill-formed.8913//8914// This is really just a consequence of the general rule that you can8915// only delete a function on its first declaration.8916Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)8917<< FD->isImplicit() << (int)DCK;8918DefaultedComparisonAnalyzer(*this, RD, FD, DCK,8919DefaultedComparisonAnalyzer::ExplainDeleted)8920.visit();8921return true;8922}8923if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {8924// C++20 [class.compare.default]p1:8925// [...] A definition of a comparison operator as defaulted that appears8926// in a class shall be the first declaration of that function.8927Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)8928<< (int)DCK;8929Diag(FD->getCanonicalDecl()->getLocation(),8930diag::note_previous_declaration);8931return true;8932}8933}89348935// If we want to delete the function, then do so; there's nothing else to8936// check in that case.8937if (Info.Deleted) {8938SetDeclDeleted(FD, FD->getLocation());8939if (!inTemplateInstantiation() && !FD->isImplicit()) {8940Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)8941<< (int)DCK;8942DefaultedComparisonAnalyzer(*this, RD, FD, DCK,8943DefaultedComparisonAnalyzer::ExplainDeleted)8944.visit();8945if (FD->getDefaultLoc().isValid())8946Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)8947<< FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");8948}8949return false;8950}89518952// C++2a [class.spaceship]p2:8953// The return type is deduced as the common comparison type of R0, R1, ...8954if (DCK == DefaultedComparisonKind::ThreeWay &&8955FD->getDeclaredReturnType()->isUndeducedAutoType()) {8956SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();8957if (RetLoc.isInvalid())8958RetLoc = FD->getBeginLoc();8959// FIXME: Should we really care whether we have the complete type and the8960// 'enumerator' constants here? A forward declaration seems sufficient.8961QualType Cat = CheckComparisonCategoryType(8962Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);8963if (Cat.isNull())8964return true;8965Context.adjustDeducedFunctionResultType(8966FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));8967}89688969// C++2a [dcl.fct.def.default]p3 [P2002R0]:8970// An explicitly-defaulted function that is not defined as deleted may be8971// declared constexpr or consteval only if it is constexpr-compatible.8972// C++2a [class.compare.default]p3 [P2002R0]:8973// A defaulted comparison function is constexpr-compatible if it satisfies8974// the requirements for a constexpr function [...]8975// The only relevant requirements are that the parameter and return types are8976// literal types. The remaining conditions are checked by the analyzer.8977//8978// We support P2448R2 in language modes earlier than C++23 as an extension.8979// The concept of constexpr-compatible was removed.8980// C++23 [dcl.fct.def.default]p3 [P2448R2]8981// A function explicitly defaulted on its first declaration is implicitly8982// inline, and is implicitly constexpr if it is constexpr-suitable.8983// C++23 [dcl.constexpr]p38984// A function is constexpr-suitable if8985// - it is not a coroutine, and8986// - if the function is a constructor or destructor, its class does not8987// have any virtual base classes.8988if (FD->isConstexpr()) {8989if (!getLangOpts().CPlusPlus23 &&8990CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&8991CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&8992!Info.Constexpr) {8993Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)8994<< FD->isImplicit() << (int)DCK << FD->isConsteval();8995DefaultedComparisonAnalyzer(*this, RD, FD, DCK,8996DefaultedComparisonAnalyzer::ExplainConstexpr)8997.visit();8998}8999}90009001// C++2a [dcl.fct.def.default]p3 [P2002R0]:9002// If a constexpr-compatible function is explicitly defaulted on its first9003// declaration, it is implicitly considered to be constexpr.9004// FIXME: Only applying this to the first declaration seems problematic, as9005// simple reorderings can affect the meaning of the program.9006if (First && !FD->isConstexpr() && Info.Constexpr)9007FD->setConstexprKind(ConstexprSpecKind::Constexpr);90089009// C++2a [except.spec]p3:9010// If a declaration of a function does not have a noexcept-specifier9011// [and] is defaulted on its first declaration, [...] the exception9012// specification is as specified below9013if (FD->getExceptionSpecType() == EST_None) {9014auto *FPT = FD->getType()->castAs<FunctionProtoType>();9015FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();9016EPI.ExceptionSpec.Type = EST_Unevaluated;9017EPI.ExceptionSpec.SourceDecl = FD;9018FD->setType(Context.getFunctionType(FPT->getReturnType(),9019FPT->getParamTypes(), EPI));9020}90219022return false;9023}90249025void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,9026FunctionDecl *Spaceship) {9027Sema::CodeSynthesisContext Ctx;9028Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;9029Ctx.PointOfInstantiation = Spaceship->getEndLoc();9030Ctx.Entity = Spaceship;9031pushCodeSynthesisContext(Ctx);90329033if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))9034EqualEqual->setImplicit();90359036popCodeSynthesisContext();9037}90389039void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,9040DefaultedComparisonKind DCK) {9041assert(FD->isDefaulted() && !FD->isDeleted() &&9042!FD->doesThisDeclarationHaveABody());9043if (FD->willHaveBody() || FD->isInvalidDecl())9044return;90459046SynthesizedFunctionScope Scope(*this, FD);90479048// Add a context note for diagnostics produced after this point.9049Scope.addContextNote(UseLoc);90509051{9052// Build and set up the function body.9053// The first parameter has type maybe-ref-to maybe-const T, use that to get9054// the type of the class being compared.9055auto PT = FD->getParamDecl(0)->getType();9056CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();9057SourceLocation BodyLoc =9058FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();9059StmtResult Body =9060DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();9061if (Body.isInvalid()) {9062FD->setInvalidDecl();9063return;9064}9065FD->setBody(Body.get());9066FD->markUsed(Context);9067}90689069// The exception specification is needed because we are defining the9070// function. Note that this will reuse the body we just built.9071ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());90729073if (ASTMutationListener *L = getASTMutationListener())9074L->CompletedImplicitDefinition(FD);9075}90769077static Sema::ImplicitExceptionSpecification9078ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,9079FunctionDecl *FD,9080Sema::DefaultedComparisonKind DCK) {9081ComputingExceptionSpec CES(S, FD, Loc);9082Sema::ImplicitExceptionSpecification ExceptSpec(S);90839084if (FD->isInvalidDecl())9085return ExceptSpec;90869087// The common case is that we just defined the comparison function. In that9088// case, just look at whether the body can throw.9089if (FD->hasBody()) {9090ExceptSpec.CalledStmt(FD->getBody());9091} else {9092// Otherwise, build a body so we can check it. This should ideally only9093// happen when we're not actually marking the function referenced. (This is9094// only really important for efficiency: we don't want to build and throw9095// away bodies for comparison functions more than we strictly need to.)90969097// Pretend to synthesize the function body in an unevaluated context.9098// Note that we can't actually just go ahead and define the function here:9099// we are not permitted to mark its callees as referenced.9100Sema::SynthesizedFunctionScope Scope(S, FD);9101EnterExpressionEvaluationContext Context(9102S, Sema::ExpressionEvaluationContext::Unevaluated);91039104CXXRecordDecl *RD =9105cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None9106? FD->getDeclContext()9107: FD->getLexicalDeclContext());9108SourceLocation BodyLoc =9109FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();9110StmtResult Body =9111DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();9112if (!Body.isInvalid())9113ExceptSpec.CalledStmt(Body.get());91149115// FIXME: Can we hold onto this body and just transform it to potentially9116// evaluated when we're asked to define the function rather than rebuilding9117// it? Either that, or we should only build the bits of the body that we9118// need (the expressions, not the statements).9119}91209121return ExceptSpec;9122}91239124void Sema::CheckDelayedMemberExceptionSpecs() {9125decltype(DelayedOverridingExceptionSpecChecks) Overriding;9126decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;91279128std::swap(Overriding, DelayedOverridingExceptionSpecChecks);9129std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);91309131// Perform any deferred checking of exception specifications for virtual9132// destructors.9133for (auto &Check : Overriding)9134CheckOverridingFunctionExceptionSpec(Check.first, Check.second);91359136// Perform any deferred checking of exception specifications for befriended9137// special members.9138for (auto &Check : Equivalent)9139CheckEquivalentExceptionSpec(Check.second, Check.first);9140}91419142namespace {9143/// CRTP base class for visiting operations performed by a special member9144/// function (or inherited constructor).9145template<typename Derived>9146struct SpecialMemberVisitor {9147Sema &S;9148CXXMethodDecl *MD;9149CXXSpecialMemberKind CSM;9150Sema::InheritedConstructorInfo *ICI;91519152// Properties of the special member, computed for convenience.9153bool IsConstructor = false, IsAssignment = false, ConstArg = false;91549155SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,9156Sema::InheritedConstructorInfo *ICI)9157: S(S), MD(MD), CSM(CSM), ICI(ICI) {9158switch (CSM) {9159case CXXSpecialMemberKind::DefaultConstructor:9160case CXXSpecialMemberKind::CopyConstructor:9161case CXXSpecialMemberKind::MoveConstructor:9162IsConstructor = true;9163break;9164case CXXSpecialMemberKind::CopyAssignment:9165case CXXSpecialMemberKind::MoveAssignment:9166IsAssignment = true;9167break;9168case CXXSpecialMemberKind::Destructor:9169break;9170case CXXSpecialMemberKind::Invalid:9171llvm_unreachable("invalid special member kind");9172}91739174if (MD->getNumExplicitParams()) {9175if (const ReferenceType *RT =9176MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())9177ConstArg = RT->getPointeeType().isConstQualified();9178}9179}91809181Derived &getDerived() { return static_cast<Derived&>(*this); }91829183/// Is this a "move" special member?9184bool isMove() const {9185return CSM == CXXSpecialMemberKind::MoveConstructor ||9186CSM == CXXSpecialMemberKind::MoveAssignment;9187}91889189/// Look up the corresponding special member in the given class.9190Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,9191unsigned Quals, bool IsMutable) {9192return lookupCallFromSpecialMember(S, Class, CSM, Quals,9193ConstArg && !IsMutable);9194}91959196/// Look up the constructor for the specified base class to see if it's9197/// overridden due to this being an inherited constructor.9198Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {9199if (!ICI)9200return {};9201assert(CSM == CXXSpecialMemberKind::DefaultConstructor);9202auto *BaseCtor =9203cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();9204if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)9205return MD;9206return {};9207}92089209/// A base or member subobject.9210typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;92119212/// Get the location to use for a subobject in diagnostics.9213static SourceLocation getSubobjectLoc(Subobject Subobj) {9214// FIXME: For an indirect virtual base, the direct base leading to9215// the indirect virtual base would be a more useful choice.9216if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())9217return B->getBaseTypeLoc();9218else9219return Subobj.get<FieldDecl*>()->getLocation();9220}92219222enum BasesToVisit {9223/// Visit all non-virtual (direct) bases.9224VisitNonVirtualBases,9225/// Visit all direct bases, virtual or not.9226VisitDirectBases,9227/// Visit all non-virtual bases, and all virtual bases if the class9228/// is not abstract.9229VisitPotentiallyConstructedBases,9230/// Visit all direct or virtual bases.9231VisitAllBases9232};92339234// Visit the bases and members of the class.9235bool visit(BasesToVisit Bases) {9236CXXRecordDecl *RD = MD->getParent();92379238if (Bases == VisitPotentiallyConstructedBases)9239Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;92409241for (auto &B : RD->bases())9242if ((Bases == VisitDirectBases || !B.isVirtual()) &&9243getDerived().visitBase(&B))9244return true;92459246if (Bases == VisitAllBases)9247for (auto &B : RD->vbases())9248if (getDerived().visitBase(&B))9249return true;92509251for (auto *F : RD->fields())9252if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&9253getDerived().visitField(F))9254return true;92559256return false;9257}9258};9259}92609261namespace {9262struct SpecialMemberDeletionInfo9263: SpecialMemberVisitor<SpecialMemberDeletionInfo> {9264bool Diagnose;92659266SourceLocation Loc;92679268bool AllFieldsAreConst;92699270SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,9271CXXSpecialMemberKind CSM,9272Sema::InheritedConstructorInfo *ICI, bool Diagnose)9273: SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),9274Loc(MD->getLocation()), AllFieldsAreConst(true) {}92759276bool inUnion() const { return MD->getParent()->isUnion(); }92779278CXXSpecialMemberKind getEffectiveCSM() {9279return ICI ? CXXSpecialMemberKind::Invalid : CSM;9280}92819282bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);92839284bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }9285bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }92869287bool shouldDeleteForBase(CXXBaseSpecifier *Base);9288bool shouldDeleteForField(FieldDecl *FD);9289bool shouldDeleteForAllConstMembers();92909291bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,9292unsigned Quals);9293bool shouldDeleteForSubobjectCall(Subobject Subobj,9294Sema::SpecialMemberOverloadResult SMOR,9295bool IsDtorCallInCtor);92969297bool isAccessible(Subobject Subobj, CXXMethodDecl *D);9298};9299}93009301/// Is the given special member inaccessible when used on the given9302/// sub-object.9303bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,9304CXXMethodDecl *target) {9305/// If we're operating on a base class, the object type is the9306/// type of this special member.9307QualType objectTy;9308AccessSpecifier access = target->getAccess();9309if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {9310objectTy = S.Context.getTypeDeclType(MD->getParent());9311access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);93129313// If we're operating on a field, the object type is the type of the field.9314} else {9315objectTy = S.Context.getTypeDeclType(target->getParent());9316}93179318return S.isMemberAccessibleForDeletion(9319target->getParent(), DeclAccessPair::make(target, access), objectTy);9320}93219322/// Check whether we should delete a special member due to the implicit9323/// definition containing a call to a special member of a subobject.9324bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(9325Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,9326bool IsDtorCallInCtor) {9327CXXMethodDecl *Decl = SMOR.getMethod();9328FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();93299330int DiagKind = -1;93319332if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)9333DiagKind = !Decl ? 0 : 1;9334else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)9335DiagKind = 2;9336else if (!isAccessible(Subobj, Decl))9337DiagKind = 3;9338else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&9339!Decl->isTrivial()) {9340// A member of a union must have a trivial corresponding special member.9341// As a weird special case, a destructor call from a union's constructor9342// must be accessible and non-deleted, but need not be trivial. Such a9343// destructor is never actually called, but is semantically checked as9344// if it were.9345if (CSM == CXXSpecialMemberKind::DefaultConstructor) {9346// [class.default.ctor]p2:9347// A defaulted default constructor for class X is defined as deleted if9348// - X is a union that has a variant member with a non-trivial default9349// constructor and no variant member of X has a default member9350// initializer9351const auto *RD = cast<CXXRecordDecl>(Field->getParent());9352if (!RD->hasInClassInitializer())9353DiagKind = 4;9354} else {9355DiagKind = 4;9356}9357}93589359if (DiagKind == -1)9360return false;93619362if (Diagnose) {9363if (Field) {9364S.Diag(Field->getLocation(),9365diag::note_deleted_special_member_class_subobject)9366<< llvm::to_underlying(getEffectiveCSM()) << MD->getParent()9367<< /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor9368<< /*IsObjCPtr*/ false;9369} else {9370CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();9371S.Diag(Base->getBeginLoc(),9372diag::note_deleted_special_member_class_subobject)9373<< llvm::to_underlying(getEffectiveCSM()) << MD->getParent()9374<< /*IsField*/ false << Base->getType() << DiagKind9375<< IsDtorCallInCtor << /*IsObjCPtr*/ false;9376}93779378if (DiagKind == 1)9379S.NoteDeletedFunction(Decl);9380// FIXME: Explain inaccessibility if DiagKind == 3.9381}93829383return true;9384}93859386/// Check whether we should delete a special member function due to having a9387/// direct or virtual base class or non-static data member of class type M.9388bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(9389CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {9390FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();9391bool IsMutable = Field && Field->isMutable();93929393// C++11 [class.ctor]p5:9394// -- any direct or virtual base class, or non-static data member with no9395// brace-or-equal-initializer, has class type M (or array thereof) and9396// either M has no default constructor or overload resolution as applied9397// to M's default constructor results in an ambiguity or in a function9398// that is deleted or inaccessible9399// C++11 [class.copy]p11, C++11 [class.copy]p23:9400// -- a direct or virtual base class B that cannot be copied/moved because9401// overload resolution, as applied to B's corresponding special member,9402// results in an ambiguity or a function that is deleted or inaccessible9403// from the defaulted special member9404// C++11 [class.dtor]p5:9405// -- any direct or virtual base class [...] has a type with a destructor9406// that is deleted or inaccessible9407if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&9408Field->hasInClassInitializer()) &&9409shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),9410false))9411return true;94129413// C++11 [class.ctor]p5, C++11 [class.copy]p11:9414// -- any direct or virtual base class or non-static data member has a9415// type with a destructor that is deleted or inaccessible9416if (IsConstructor) {9417Sema::SpecialMemberOverloadResult SMOR =9418S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,9419false, false, false, false);9420if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))9421return true;9422}94239424return false;9425}94269427bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(9428FieldDecl *FD, QualType FieldType) {9429// The defaulted special functions are defined as deleted if this is a variant9430// member with a non-trivial ownership type, e.g., ObjC __strong or __weak9431// type under ARC.9432if (!FieldType.hasNonTrivialObjCLifetime())9433return false;94349435// Don't make the defaulted default constructor defined as deleted if the9436// member has an in-class initializer.9437if (CSM == CXXSpecialMemberKind::DefaultConstructor &&9438FD->hasInClassInitializer())9439return false;94409441if (Diagnose) {9442auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());9443S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)9444<< llvm::to_underlying(getEffectiveCSM()) << ParentClass9445<< /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false9446<< /*IsObjCPtr*/ true;9447}94489449return true;9450}94519452/// Check whether we should delete a special member function due to the class9453/// having a particular direct or virtual base class.9454bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {9455CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();9456// If program is correct, BaseClass cannot be null, but if it is, the error9457// must be reported elsewhere.9458if (!BaseClass)9459return false;9460// If we have an inheriting constructor, check whether we're calling an9461// inherited constructor instead of a default constructor.9462Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);9463if (auto *BaseCtor = SMOR.getMethod()) {9464// Note that we do not check access along this path; other than that,9465// this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);9466// FIXME: Check that the base has a usable destructor! Sink this into9467// shouldDeleteForClassSubobject.9468if (BaseCtor->isDeleted() && Diagnose) {9469S.Diag(Base->getBeginLoc(),9470diag::note_deleted_special_member_class_subobject)9471<< llvm::to_underlying(getEffectiveCSM()) << MD->getParent()9472<< /*IsField*/ false << Base->getType() << /*Deleted*/ 19473<< /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;9474S.NoteDeletedFunction(BaseCtor);9475}9476return BaseCtor->isDeleted();9477}9478return shouldDeleteForClassSubobject(BaseClass, Base, 0);9479}94809481/// Check whether we should delete a special member function due to the class9482/// having a particular non-static data member.9483bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {9484QualType FieldType = S.Context.getBaseElementType(FD->getType());9485CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();94869487if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))9488return true;94899490if (CSM == CXXSpecialMemberKind::DefaultConstructor) {9491// For a default constructor, all references must be initialized in-class9492// and, if a union, it must have a non-const member.9493if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {9494if (Diagnose)9495S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)9496<< !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;9497return true;9498}9499// C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static9500// data member of const-qualified type (or array thereof) with no9501// brace-or-equal-initializer is not const-default-constructible.9502if (!inUnion() && FieldType.isConstQualified() &&9503!FD->hasInClassInitializer() &&9504(!FieldRecord || !FieldRecord->allowConstDefaultInit())) {9505if (Diagnose)9506S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)9507<< !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;9508return true;9509}95109511if (inUnion() && !FieldType.isConstQualified())9512AllFieldsAreConst = false;9513} else if (CSM == CXXSpecialMemberKind::CopyConstructor) {9514// For a copy constructor, data members must not be of rvalue reference9515// type.9516if (FieldType->isRValueReferenceType()) {9517if (Diagnose)9518S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)9519<< MD->getParent() << FD << FieldType;9520return true;9521}9522} else if (IsAssignment) {9523// For an assignment operator, data members must not be of reference type.9524if (FieldType->isReferenceType()) {9525if (Diagnose)9526S.Diag(FD->getLocation(), diag::note_deleted_assign_field)9527<< isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;9528return true;9529}9530if (!FieldRecord && FieldType.isConstQualified()) {9531// C++11 [class.copy]p23:9532// -- a non-static data member of const non-class type (or array thereof)9533if (Diagnose)9534S.Diag(FD->getLocation(), diag::note_deleted_assign_field)9535<< isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;9536return true;9537}9538}95399540if (FieldRecord) {9541// Some additional restrictions exist on the variant members.9542if (!inUnion() && FieldRecord->isUnion() &&9543FieldRecord->isAnonymousStructOrUnion()) {9544bool AllVariantFieldsAreConst = true;95459546// FIXME: Handle anonymous unions declared within anonymous unions.9547for (auto *UI : FieldRecord->fields()) {9548QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());95499550if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))9551return true;95529553if (!UnionFieldType.isConstQualified())9554AllVariantFieldsAreConst = false;95559556CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();9557if (UnionFieldRecord &&9558shouldDeleteForClassSubobject(UnionFieldRecord, UI,9559UnionFieldType.getCVRQualifiers()))9560return true;9561}95629563// At least one member in each anonymous union must be non-const9564if (CSM == CXXSpecialMemberKind::DefaultConstructor &&9565AllVariantFieldsAreConst && !FieldRecord->field_empty()) {9566if (Diagnose)9567S.Diag(FieldRecord->getLocation(),9568diag::note_deleted_default_ctor_all_const)9569<< !!ICI << MD->getParent() << /*anonymous union*/1;9570return true;9571}95729573// Don't check the implicit member of the anonymous union type.9574// This is technically non-conformant but supported, and we have a9575// diagnostic for this elsewhere.9576return false;9577}95789579if (shouldDeleteForClassSubobject(FieldRecord, FD,9580FieldType.getCVRQualifiers()))9581return true;9582}95839584return false;9585}95869587/// C++11 [class.ctor] p5:9588/// A defaulted default constructor for a class X is defined as deleted if9589/// X is a union and all of its variant members are of const-qualified type.9590bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {9591// This is a silly definition, because it gives an empty union a deleted9592// default constructor. Don't do that.9593if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&9594AllFieldsAreConst) {9595bool AnyFields = false;9596for (auto *F : MD->getParent()->fields())9597if ((AnyFields = !F->isUnnamedBitField()))9598break;9599if (!AnyFields)9600return false;9601if (Diagnose)9602S.Diag(MD->getParent()->getLocation(),9603diag::note_deleted_default_ctor_all_const)9604<< !!ICI << MD->getParent() << /*not anonymous union*/0;9605return true;9606}9607return false;9608}96099610/// Determine whether a defaulted special member function should be defined as9611/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,9612/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.9613bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,9614CXXSpecialMemberKind CSM,9615InheritedConstructorInfo *ICI,9616bool Diagnose) {9617if (MD->isInvalidDecl())9618return false;9619CXXRecordDecl *RD = MD->getParent();9620assert(!RD->isDependentType() && "do deletion after instantiation");9621if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||9622RD->isInvalidDecl())9623return false;96249625// C++11 [expr.lambda.prim]p19:9626// The closure type associated with a lambda-expression has a9627// deleted (8.4.3) default constructor and a deleted copy9628// assignment operator.9629// C++2a adds back these operators if the lambda has no lambda-capture.9630if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&9631(CSM == CXXSpecialMemberKind::DefaultConstructor ||9632CSM == CXXSpecialMemberKind::CopyAssignment)) {9633if (Diagnose)9634Diag(RD->getLocation(), diag::note_lambda_decl);9635return true;9636}96379638// For an anonymous struct or union, the copy and assignment special members9639// will never be used, so skip the check. For an anonymous union declared at9640// namespace scope, the constructor and destructor are used.9641if (CSM != CXXSpecialMemberKind::DefaultConstructor &&9642CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())9643return false;96449645// C++11 [class.copy]p7, p18:9646// If the class definition declares a move constructor or move assignment9647// operator, an implicitly declared copy constructor or copy assignment9648// operator is defined as deleted.9649if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||9650CSM == CXXSpecialMemberKind::CopyAssignment)) {9651CXXMethodDecl *UserDeclaredMove = nullptr;96529653// In Microsoft mode up to MSVC 2013, a user-declared move only causes the9654// deletion of the corresponding copy operation, not both copy operations.9655// MSVC 2015 has adopted the standards conforming behavior.9656bool DeletesOnlyMatchingCopy =9657getLangOpts().MSVCCompat &&9658!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);96599660if (RD->hasUserDeclaredMoveConstructor() &&9661(!DeletesOnlyMatchingCopy ||9662CSM == CXXSpecialMemberKind::CopyConstructor)) {9663if (!Diagnose) return true;96649665// Find any user-declared move constructor.9666for (auto *I : RD->ctors()) {9667if (I->isMoveConstructor()) {9668UserDeclaredMove = I;9669break;9670}9671}9672assert(UserDeclaredMove);9673} else if (RD->hasUserDeclaredMoveAssignment() &&9674(!DeletesOnlyMatchingCopy ||9675CSM == CXXSpecialMemberKind::CopyAssignment)) {9676if (!Diagnose) return true;96779678// Find any user-declared move assignment operator.9679for (auto *I : RD->methods()) {9680if (I->isMoveAssignmentOperator()) {9681UserDeclaredMove = I;9682break;9683}9684}9685assert(UserDeclaredMove);9686}96879688if (UserDeclaredMove) {9689Diag(UserDeclaredMove->getLocation(),9690diag::note_deleted_copy_user_declared_move)9691<< (CSM == CXXSpecialMemberKind::CopyAssignment) << RD9692<< UserDeclaredMove->isMoveAssignmentOperator();9693return true;9694}9695}96969697// Do access control from the special member function9698ContextRAII MethodContext(*this, MD);96999700// C++11 [class.dtor]p5:9701// -- for a virtual destructor, lookup of the non-array deallocation function9702// results in an ambiguity or in a function that is deleted or inaccessible9703if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {9704FunctionDecl *OperatorDelete = nullptr;9705DeclarationName Name =9706Context.DeclarationNames.getCXXOperatorName(OO_Delete);9707if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,9708OperatorDelete, /*Diagnose*/false)) {9709if (Diagnose)9710Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);9711return true;9712}9713}97149715SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);97169717// Per DR1611, do not consider virtual bases of constructors of abstract9718// classes, since we are not going to construct them.9719// Per DR1658, do not consider virtual bases of destructors of abstract9720// classes either.9721// Per DR2180, for assignment operators we only assign (and thus only9722// consider) direct bases.9723if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases9724: SMI.VisitPotentiallyConstructedBases))9725return true;97269727if (SMI.shouldDeleteForAllConstMembers())9728return true;97299730if (getLangOpts().CUDA) {9731// We should delete the special member in CUDA mode if target inference9732// failed.9733// For inherited constructors (non-null ICI), CSM may be passed so that MD9734// is treated as certain special member, which may not reflect what special9735// member MD really is. However inferTargetForImplicitSpecialMember9736// expects CSM to match MD, therefore recalculate CSM.9737assert(ICI || CSM == getSpecialMember(MD));9738auto RealCSM = CSM;9739if (ICI)9740RealCSM = getSpecialMember(MD);97419742return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,9743SMI.ConstArg, Diagnose);9744}97459746return false;9747}97489749void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {9750DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);9751assert(DFK && "not a defaultable function");9752assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");97539754if (DFK.isSpecialMember()) {9755ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),9756nullptr, /*Diagnose=*/true);9757} else {9758DefaultedComparisonAnalyzer(9759*this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,9760DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)9761.visit();9762}9763}97649765/// Perform lookup for a special member of the specified kind, and determine9766/// whether it is trivial. If the triviality can be determined without the9767/// lookup, skip it. This is intended for use when determining whether a9768/// special member of a containing object is trivial, and thus does not ever9769/// perform overload resolution for default constructors.9770///9771/// If \p Selected is not \c NULL, \c *Selected will be filled in with the9772/// member that was most likely to be intended to be trivial, if any.9773///9774/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to9775/// determine whether the special member is trivial.9776static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,9777CXXSpecialMemberKind CSM, unsigned Quals,9778bool ConstRHS,9779Sema::TrivialABIHandling TAH,9780CXXMethodDecl **Selected) {9781if (Selected)9782*Selected = nullptr;97839784switch (CSM) {9785case CXXSpecialMemberKind::Invalid:9786llvm_unreachable("not a special member");97879788case CXXSpecialMemberKind::DefaultConstructor:9789// C++11 [class.ctor]p5:9790// A default constructor is trivial if:9791// - all the [direct subobjects] have trivial default constructors9792//9793// Note, no overload resolution is performed in this case.9794if (RD->hasTrivialDefaultConstructor())9795return true;97969797if (Selected) {9798// If there's a default constructor which could have been trivial, dig it9799// out. Otherwise, if there's any user-provided default constructor, point9800// to that as an example of why there's not a trivial one.9801CXXConstructorDecl *DefCtor = nullptr;9802if (RD->needsImplicitDefaultConstructor())9803S.DeclareImplicitDefaultConstructor(RD);9804for (auto *CI : RD->ctors()) {9805if (!CI->isDefaultConstructor())9806continue;9807DefCtor = CI;9808if (!DefCtor->isUserProvided())9809break;9810}98119812*Selected = DefCtor;9813}98149815return false;98169817case CXXSpecialMemberKind::Destructor:9818// C++11 [class.dtor]p5:9819// A destructor is trivial if:9820// - all the direct [subobjects] have trivial destructors9821if (RD->hasTrivialDestructor() ||9822(TAH == Sema::TAH_ConsiderTrivialABI &&9823RD->hasTrivialDestructorForCall()))9824return true;98259826if (Selected) {9827if (RD->needsImplicitDestructor())9828S.DeclareImplicitDestructor(RD);9829*Selected = RD->getDestructor();9830}98319832return false;98339834case CXXSpecialMemberKind::CopyConstructor:9835// C++11 [class.copy]p12:9836// A copy constructor is trivial if:9837// - the constructor selected to copy each direct [subobject] is trivial9838if (RD->hasTrivialCopyConstructor() ||9839(TAH == Sema::TAH_ConsiderTrivialABI &&9840RD->hasTrivialCopyConstructorForCall())) {9841if (Quals == Qualifiers::Const)9842// We must either select the trivial copy constructor or reach an9843// ambiguity; no need to actually perform overload resolution.9844return true;9845} else if (!Selected) {9846return false;9847}9848// In C++98, we are not supposed to perform overload resolution here, but we9849// treat that as a language defect, as suggested on cxx-abi-dev, to treat9850// cases like B as having a non-trivial copy constructor:9851// struct A { template<typename T> A(T&); };9852// struct B { mutable A a; };9853goto NeedOverloadResolution;98549855case CXXSpecialMemberKind::CopyAssignment:9856// C++11 [class.copy]p25:9857// A copy assignment operator is trivial if:9858// - the assignment operator selected to copy each direct [subobject] is9859// trivial9860if (RD->hasTrivialCopyAssignment()) {9861if (Quals == Qualifiers::Const)9862return true;9863} else if (!Selected) {9864return false;9865}9866// In C++98, we are not supposed to perform overload resolution here, but we9867// treat that as a language defect.9868goto NeedOverloadResolution;98699870case CXXSpecialMemberKind::MoveConstructor:9871case CXXSpecialMemberKind::MoveAssignment:9872NeedOverloadResolution:9873Sema::SpecialMemberOverloadResult SMOR =9874lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);98759876// The standard doesn't describe how to behave if the lookup is ambiguous.9877// We treat it as not making the member non-trivial, just like the standard9878// mandates for the default constructor. This should rarely matter, because9879// the member will also be deleted.9880if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)9881return true;98829883if (!SMOR.getMethod()) {9884assert(SMOR.getKind() ==9885Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);9886return false;9887}98889889// We deliberately don't check if we found a deleted special member. We're9890// not supposed to!9891if (Selected)9892*Selected = SMOR.getMethod();98939894if (TAH == Sema::TAH_ConsiderTrivialABI &&9895(CSM == CXXSpecialMemberKind::CopyConstructor ||9896CSM == CXXSpecialMemberKind::MoveConstructor))9897return SMOR.getMethod()->isTrivialForCall();9898return SMOR.getMethod()->isTrivial();9899}99009901llvm_unreachable("unknown special method kind");9902}99039904static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {9905for (auto *CI : RD->ctors())9906if (!CI->isImplicit())9907return CI;99089909// Look for constructor templates.9910typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;9911for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {9912if (CXXConstructorDecl *CD =9913dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))9914return CD;9915}99169917return nullptr;9918}99199920/// The kind of subobject we are checking for triviality. The values of this9921/// enumeration are used in diagnostics.9922enum TrivialSubobjectKind {9923/// The subobject is a base class.9924TSK_BaseClass,9925/// The subobject is a non-static data member.9926TSK_Field,9927/// The object is actually the complete object.9928TSK_CompleteObject9929};99309931/// Check whether the special member selected for a given type would be trivial.9932static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,9933QualType SubType, bool ConstRHS,9934CXXSpecialMemberKind CSM,9935TrivialSubobjectKind Kind,9936Sema::TrivialABIHandling TAH,9937bool Diagnose) {9938CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();9939if (!SubRD)9940return true;99419942CXXMethodDecl *Selected;9943if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),9944ConstRHS, TAH, Diagnose ? &Selected : nullptr))9945return true;99469947if (Diagnose) {9948if (ConstRHS)9949SubType.addConst();99509951if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {9952S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)9953<< Kind << SubType.getUnqualifiedType();9954if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))9955S.Diag(CD->getLocation(), diag::note_user_declared_ctor);9956} else if (!Selected)9957S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)9958<< Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)9959<< SubType;9960else if (Selected->isUserProvided()) {9961if (Kind == TSK_CompleteObject)9962S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)9963<< Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);9964else {9965S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)9966<< Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);9967S.Diag(Selected->getLocation(), diag::note_declared_at);9968}9969} else {9970if (Kind != TSK_CompleteObject)9971S.Diag(SubobjLoc, diag::note_nontrivial_subobject)9972<< Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);99739974// Explain why the defaulted or deleted special member isn't trivial.9975S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,9976Diagnose);9977}9978}99799980return false;9981}99829983/// Check whether the members of a class type allow a special member to be9984/// trivial.9985static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,9986CXXSpecialMemberKind CSM, bool ConstArg,9987Sema::TrivialABIHandling TAH,9988bool Diagnose) {9989for (const auto *FI : RD->fields()) {9990if (FI->isInvalidDecl() || FI->isUnnamedBitField())9991continue;99929993QualType FieldType = S.Context.getBaseElementType(FI->getType());99949995// Pretend anonymous struct or union members are members of this class.9996if (FI->isAnonymousStructOrUnion()) {9997if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),9998CSM, ConstArg, TAH, Diagnose))9999return false;10000continue;10001}1000210003// C++11 [class.ctor]p5:10004// A default constructor is trivial if [...]10005// -- no non-static data member of its class has a10006// brace-or-equal-initializer10007if (CSM == CXXSpecialMemberKind::DefaultConstructor &&10008FI->hasInClassInitializer()) {10009if (Diagnose)10010S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)10011<< FI;10012return false;10013}1001410015// Objective C ARC 4.3.5:10016// [...] nontrivally ownership-qualified types are [...] not trivially10017// default constructible, copy constructible, move constructible, copy10018// assignable, move assignable, or destructible [...]10019if (FieldType.hasNonTrivialObjCLifetime()) {10020if (Diagnose)10021S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)10022<< RD << FieldType.getObjCLifetime();10023return false;10024}1002510026bool ConstRHS = ConstArg && !FI->isMutable();10027if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,10028CSM, TSK_Field, TAH, Diagnose))10029return false;10030}1003110032return true;10033}1003410035void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,10036CXXSpecialMemberKind CSM) {10037QualType Ty = Context.getRecordType(RD);1003810039bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||10040CSM == CXXSpecialMemberKind::CopyAssignment);10041checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,10042TSK_CompleteObject, TAH_IgnoreTrivialABI,10043/*Diagnose*/true);10044}1004510046bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,10047TrivialABIHandling TAH, bool Diagnose) {10048assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&10049"not special enough");1005010051CXXRecordDecl *RD = MD->getParent();1005210053bool ConstArg = false;1005410055// C++11 [class.copy]p12, p25: [DR1593]10056// A [special member] is trivial if [...] its parameter-type-list is10057// equivalent to the parameter-type-list of an implicit declaration [...]10058switch (CSM) {10059case CXXSpecialMemberKind::DefaultConstructor:10060case CXXSpecialMemberKind::Destructor:10061// Trivial default constructors and destructors cannot have parameters.10062break;1006310064case CXXSpecialMemberKind::CopyConstructor:10065case CXXSpecialMemberKind::CopyAssignment: {10066const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);10067const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();1006810069// When ClangABICompat14 is true, CXX copy constructors will only be trivial10070// if they are not user-provided and their parameter-type-list is equivalent10071// to the parameter-type-list of an implicit declaration. This maintains the10072// behavior before dr2171 was implemented.10073//10074// Otherwise, if ClangABICompat14 is false, All copy constructors can be10075// trivial, if they are not user-provided, regardless of the qualifiers on10076// the reference type.10077const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=10078LangOptions::ClangABI::Ver14;10079if (!RT ||10080((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&10081ClangABICompat14)) {10082if (Diagnose)10083Diag(Param0->getLocation(), diag::note_nontrivial_param_type)10084<< Param0->getSourceRange() << Param0->getType()10085<< Context.getLValueReferenceType(10086Context.getRecordType(RD).withConst());10087return false;10088}1008910090ConstArg = RT->getPointeeType().isConstQualified();10091break;10092}1009310094case CXXSpecialMemberKind::MoveConstructor:10095case CXXSpecialMemberKind::MoveAssignment: {10096// Trivial move operations always have non-cv-qualified parameters.10097const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);10098const RValueReferenceType *RT =10099Param0->getType()->getAs<RValueReferenceType>();10100if (!RT || RT->getPointeeType().getCVRQualifiers()) {10101if (Diagnose)10102Diag(Param0->getLocation(), diag::note_nontrivial_param_type)10103<< Param0->getSourceRange() << Param0->getType()10104<< Context.getRValueReferenceType(Context.getRecordType(RD));10105return false;10106}10107break;10108}1010910110case CXXSpecialMemberKind::Invalid:10111llvm_unreachable("not a special member");10112}1011310114if (MD->getMinRequiredArguments() < MD->getNumParams()) {10115if (Diagnose)10116Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),10117diag::note_nontrivial_default_arg)10118<< MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();10119return false;10120}10121if (MD->isVariadic()) {10122if (Diagnose)10123Diag(MD->getLocation(), diag::note_nontrivial_variadic);10124return false;10125}1012610127// C++11 [class.ctor]p5, C++11 [class.dtor]p5:10128// A copy/move [constructor or assignment operator] is trivial if10129// -- the [member] selected to copy/move each direct base class subobject10130// is trivial10131//10132// C++11 [class.copy]p12, C++11 [class.copy]p25:10133// A [default constructor or destructor] is trivial if10134// -- all the direct base classes have trivial [default constructors or10135// destructors]10136for (const auto &BI : RD->bases())10137if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),10138ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))10139return false;1014010141// C++11 [class.ctor]p5, C++11 [class.dtor]p5:10142// A copy/move [constructor or assignment operator] for a class X is10143// trivial if10144// -- for each non-static data member of X that is of class type (or array10145// thereof), the constructor selected to copy/move that member is10146// trivial10147//10148// C++11 [class.copy]p12, C++11 [class.copy]p25:10149// A [default constructor or destructor] is trivial if10150// -- for all of the non-static data members of its class that are of class10151// type (or array thereof), each such class has a trivial [default10152// constructor or destructor]10153if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))10154return false;1015510156// C++11 [class.dtor]p5:10157// A destructor is trivial if [...]10158// -- the destructor is not virtual10159if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {10160if (Diagnose)10161Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;10162return false;10163}1016410165// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:10166// A [special member] for class X is trivial if [...]10167// -- class X has no virtual functions and no virtual base classes10168if (CSM != CXXSpecialMemberKind::Destructor &&10169MD->getParent()->isDynamicClass()) {10170if (!Diagnose)10171return false;1017210173if (RD->getNumVBases()) {10174// Check for virtual bases. We already know that the corresponding10175// member in all bases is trivial, so vbases must all be direct.10176CXXBaseSpecifier &BS = *RD->vbases_begin();10177assert(BS.isVirtual());10178Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;10179return false;10180}1018110182// Must have a virtual method.10183for (const auto *MI : RD->methods()) {10184if (MI->isVirtual()) {10185SourceLocation MLoc = MI->getBeginLoc();10186Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;10187return false;10188}10189}1019010191llvm_unreachable("dynamic class with no vbases and no virtual functions");10192}1019310194// Looks like it's trivial!10195return true;10196}1019710198namespace {10199struct FindHiddenVirtualMethod {10200Sema *S;10201CXXMethodDecl *Method;10202llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;10203SmallVector<CXXMethodDecl *, 8> OverloadedMethods;1020410205private:10206/// Check whether any most overridden method from MD in Methods10207static bool CheckMostOverridenMethods(10208const CXXMethodDecl *MD,10209const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {10210if (MD->size_overridden_methods() == 0)10211return Methods.count(MD->getCanonicalDecl());10212for (const CXXMethodDecl *O : MD->overridden_methods())10213if (CheckMostOverridenMethods(O, Methods))10214return true;10215return false;10216}1021710218public:10219/// Member lookup function that determines whether a given C++10220/// method overloads virtual methods in a base class without overriding any,10221/// to be used with CXXRecordDecl::lookupInBases().10222bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {10223RecordDecl *BaseRecord =10224Specifier->getType()->castAs<RecordType>()->getDecl();1022510226DeclarationName Name = Method->getDeclName();10227assert(Name.getNameKind() == DeclarationName::Identifier);1022810229bool foundSameNameMethod = false;10230SmallVector<CXXMethodDecl *, 8> overloadedMethods;10231for (Path.Decls = BaseRecord->lookup(Name).begin();10232Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {10233NamedDecl *D = *Path.Decls;10234if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {10235MD = MD->getCanonicalDecl();10236foundSameNameMethod = true;10237// Interested only in hidden virtual methods.10238if (!MD->isVirtual())10239continue;10240// If the method we are checking overrides a method from its base10241// don't warn about the other overloaded methods. Clang deviates from10242// GCC by only diagnosing overloads of inherited virtual functions that10243// do not override any other virtual functions in the base. GCC's10244// -Woverloaded-virtual diagnoses any derived function hiding a virtual10245// function from a base class. These cases may be better served by a10246// warning (not specific to virtual functions) on call sites when the10247// call would select a different function from the base class, were it10248// visible.10249// See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.10250if (!S->IsOverload(Method, MD, false))10251return true;10252// Collect the overload only if its hidden.10253if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))10254overloadedMethods.push_back(MD);10255}10256}1025710258if (foundSameNameMethod)10259OverloadedMethods.append(overloadedMethods.begin(),10260overloadedMethods.end());10261return foundSameNameMethod;10262}10263};10264} // end anonymous namespace1026510266/// Add the most overridden methods from MD to Methods10267static void AddMostOverridenMethods(const CXXMethodDecl *MD,10268llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {10269if (MD->size_overridden_methods() == 0)10270Methods.insert(MD->getCanonicalDecl());10271else10272for (const CXXMethodDecl *O : MD->overridden_methods())10273AddMostOverridenMethods(O, Methods);10274}1027510276void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,10277SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {10278if (!MD->getDeclName().isIdentifier())10279return;1028010281CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.10282/*bool RecordPaths=*/false,10283/*bool DetectVirtual=*/false);10284FindHiddenVirtualMethod FHVM;10285FHVM.Method = MD;10286FHVM.S = this;1028710288// Keep the base methods that were overridden or introduced in the subclass10289// by 'using' in a set. A base method not in this set is hidden.10290CXXRecordDecl *DC = MD->getParent();10291DeclContext::lookup_result R = DC->lookup(MD->getDeclName());10292for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {10293NamedDecl *ND = *I;10294if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))10295ND = shad->getTargetDecl();10296if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))10297AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);10298}1029910300if (DC->lookupInBases(FHVM, Paths))10301OverloadedMethods = FHVM.OverloadedMethods;10302}1030310304void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,10305SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {10306for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {10307CXXMethodDecl *overloadedMD = OverloadedMethods[i];10308PartialDiagnostic PD = PDiag(10309diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;10310HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());10311Diag(overloadedMD->getLocation(), PD);10312}10313}1031410315void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {10316if (MD->isInvalidDecl())10317return;1031810319if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))10320return;1032110322SmallVector<CXXMethodDecl *, 8> OverloadedMethods;10323FindHiddenVirtualMethods(MD, OverloadedMethods);10324if (!OverloadedMethods.empty()) {10325Diag(MD->getLocation(), diag::warn_overloaded_virtual)10326<< MD << (OverloadedMethods.size() > 1);1032710328NoteHiddenVirtualMethods(MD, OverloadedMethods);10329}10330}1033110332void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {10333auto PrintDiagAndRemoveAttr = [&](unsigned N) {10334// No diagnostics if this is a template instantiation.10335if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {10336Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),10337diag::ext_cannot_use_trivial_abi) << &RD;10338Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),10339diag::note_cannot_use_trivial_abi_reason) << &RD << N;10340}10341RD.dropAttr<TrivialABIAttr>();10342};1034310344// Ill-formed if the copy and move constructors are deleted.10345auto HasNonDeletedCopyOrMoveConstructor = [&]() {10346// If the type is dependent, then assume it might have10347// implicit copy or move ctor because we won't know yet at this point.10348if (RD.isDependentType())10349return true;10350if (RD.needsImplicitCopyConstructor() &&10351!RD.defaultedCopyConstructorIsDeleted())10352return true;10353if (RD.needsImplicitMoveConstructor() &&10354!RD.defaultedMoveConstructorIsDeleted())10355return true;10356for (const CXXConstructorDecl *CD : RD.ctors())10357if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())10358return true;10359return false;10360};1036110362if (!HasNonDeletedCopyOrMoveConstructor()) {10363PrintDiagAndRemoveAttr(0);10364return;10365}1036610367// Ill-formed if the struct has virtual functions.10368if (RD.isPolymorphic()) {10369PrintDiagAndRemoveAttr(1);10370return;10371}1037210373for (const auto &B : RD.bases()) {10374// Ill-formed if the base class is non-trivial for the purpose of calls or a10375// virtual base.10376if (!B.getType()->isDependentType() &&10377!B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {10378PrintDiagAndRemoveAttr(2);10379return;10380}1038110382if (B.isVirtual()) {10383PrintDiagAndRemoveAttr(3);10384return;10385}10386}1038710388for (const auto *FD : RD.fields()) {10389// Ill-formed if the field is an ObjectiveC pointer or of a type that is10390// non-trivial for the purpose of calls.10391QualType FT = FD->getType();10392if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {10393PrintDiagAndRemoveAttr(4);10394return;10395}1039610397if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())10398if (!RT->isDependentType() &&10399!cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {10400PrintDiagAndRemoveAttr(5);10401return;10402}10403}10404}1040510406void Sema::checkIncorrectVTablePointerAuthenticationAttribute(10407CXXRecordDecl &RD) {10408if (RequireCompleteType(RD.getLocation(), Context.getRecordType(&RD),10409diag::err_incomplete_type_vtable_pointer_auth))10410return;1041110412const CXXRecordDecl *PrimaryBase = &RD;10413if (PrimaryBase->hasAnyDependentBases())10414return;1041510416while (1) {10417assert(PrimaryBase);10418const CXXRecordDecl *Base = nullptr;10419for (auto BasePtr : PrimaryBase->bases()) {10420if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())10421continue;10422Base = BasePtr.getType()->getAsCXXRecordDecl();10423break;10424}10425if (!Base || Base == PrimaryBase || !Base->isPolymorphic())10426break;10427Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),10428diag::err_non_top_level_vtable_pointer_auth)10429<< &RD << Base;10430PrimaryBase = Base;10431}1043210433if (!RD.isPolymorphic())10434Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),10435diag::err_non_polymorphic_vtable_pointer_auth)10436<< &RD;10437}1043810439void Sema::ActOnFinishCXXMemberSpecification(10440Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,10441SourceLocation RBrac, const ParsedAttributesView &AttrList) {10442if (!TagDecl)10443return;1044410445AdjustDeclIfTemplate(TagDecl);1044610447for (const ParsedAttr &AL : AttrList) {10448if (AL.getKind() != ParsedAttr::AT_Visibility)10449continue;10450AL.setInvalid();10451Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;10452}1045310454ActOnFields(S, RLoc, TagDecl,10455llvm::ArrayRef(10456// strict aliasing violation!10457reinterpret_cast<Decl **>(FieldCollector->getCurFields()),10458FieldCollector->getCurNumFields()),10459LBrac, RBrac, AttrList);1046010461CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));10462}1046310464/// Find the equality comparison functions that should be implicitly declared10465/// in a given class definition, per C++2a [class.compare.default]p3.10466static void findImplicitlyDeclaredEqualityComparisons(10467ASTContext &Ctx, CXXRecordDecl *RD,10468llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {10469DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);10470if (!RD->lookup(EqEq).empty())10471// Member operator== explicitly declared: no implicit operator==s.10472return;1047310474// Traverse friends looking for an '==' or a '<=>'.10475for (FriendDecl *Friend : RD->friends()) {10476FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());10477if (!FD) continue;1047810479if (FD->getOverloadedOperator() == OO_EqualEqual) {10480// Friend operator== explicitly declared: no implicit operator==s.10481Spaceships.clear();10482return;10483}1048410485if (FD->getOverloadedOperator() == OO_Spaceship &&10486FD->isExplicitlyDefaulted())10487Spaceships.push_back(FD);10488}1048910490// Look for members named 'operator<=>'.10491DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);10492for (NamedDecl *ND : RD->lookup(Cmp)) {10493// Note that we could find a non-function here (either a function template10494// or a using-declaration). Neither case results in an implicit10495// 'operator=='.10496if (auto *FD = dyn_cast<FunctionDecl>(ND))10497if (FD->isExplicitlyDefaulted())10498Spaceships.push_back(FD);10499}10500}1050110502void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {10503// Don't add implicit special members to templated classes.10504// FIXME: This means unqualified lookups for 'operator=' within a class10505// template don't work properly.10506if (!ClassDecl->isDependentType()) {10507if (ClassDecl->needsImplicitDefaultConstructor()) {10508++getASTContext().NumImplicitDefaultConstructors;1050910510if (ClassDecl->hasInheritedConstructor())10511DeclareImplicitDefaultConstructor(ClassDecl);10512}1051310514if (ClassDecl->needsImplicitCopyConstructor()) {10515++getASTContext().NumImplicitCopyConstructors;1051610517// If the properties or semantics of the copy constructor couldn't be10518// determined while the class was being declared, force a declaration10519// of it now.10520if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||10521ClassDecl->hasInheritedConstructor())10522DeclareImplicitCopyConstructor(ClassDecl);10523// For the MS ABI we need to know whether the copy ctor is deleted. A10524// prerequisite for deleting the implicit copy ctor is that the class has10525// a move ctor or move assignment that is either user-declared or whose10526// semantics are inherited from a subobject. FIXME: We should provide a10527// more direct way for CodeGen to ask whether the constructor was deleted.10528else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&10529(ClassDecl->hasUserDeclaredMoveConstructor() ||10530ClassDecl->needsOverloadResolutionForMoveConstructor() ||10531ClassDecl->hasUserDeclaredMoveAssignment() ||10532ClassDecl->needsOverloadResolutionForMoveAssignment()))10533DeclareImplicitCopyConstructor(ClassDecl);10534}1053510536if (getLangOpts().CPlusPlus11 &&10537ClassDecl->needsImplicitMoveConstructor()) {10538++getASTContext().NumImplicitMoveConstructors;1053910540if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||10541ClassDecl->hasInheritedConstructor())10542DeclareImplicitMoveConstructor(ClassDecl);10543}1054410545if (ClassDecl->needsImplicitCopyAssignment()) {10546++getASTContext().NumImplicitCopyAssignmentOperators;1054710548// If we have a dynamic class, then the copy assignment operator may be10549// virtual, so we have to declare it immediately. This ensures that, e.g.,10550// it shows up in the right place in the vtable and that we diagnose10551// problems with the implicit exception specification.10552if (ClassDecl->isDynamicClass() ||10553ClassDecl->needsOverloadResolutionForCopyAssignment() ||10554ClassDecl->hasInheritedAssignment())10555DeclareImplicitCopyAssignment(ClassDecl);10556}1055710558if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {10559++getASTContext().NumImplicitMoveAssignmentOperators;1056010561// Likewise for the move assignment operator.10562if (ClassDecl->isDynamicClass() ||10563ClassDecl->needsOverloadResolutionForMoveAssignment() ||10564ClassDecl->hasInheritedAssignment())10565DeclareImplicitMoveAssignment(ClassDecl);10566}1056710568if (ClassDecl->needsImplicitDestructor()) {10569++getASTContext().NumImplicitDestructors;1057010571// If we have a dynamic class, then the destructor may be virtual, so we10572// have to declare the destructor immediately. This ensures that, e.g., it10573// shows up in the right place in the vtable and that we diagnose problems10574// with the implicit exception specification.10575if (ClassDecl->isDynamicClass() ||10576ClassDecl->needsOverloadResolutionForDestructor())10577DeclareImplicitDestructor(ClassDecl);10578}10579}1058010581// C++2a [class.compare.default]p3:10582// If the member-specification does not explicitly declare any member or10583// friend named operator==, an == operator function is declared implicitly10584// for each defaulted three-way comparison operator function defined in10585// the member-specification10586// FIXME: Consider doing this lazily.10587// We do this during the initial parse for a class template, not during10588// instantiation, so that we can handle unqualified lookups for 'operator=='10589// when parsing the template.10590if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {10591llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;10592findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,10593DefaultedSpaceships);10594for (auto *FD : DefaultedSpaceships)10595DeclareImplicitEqualityComparison(ClassDecl, FD);10596}10597}1059810599unsigned10600Sema::ActOnReenterTemplateScope(Decl *D,10601llvm::function_ref<Scope *()> EnterScope) {10602if (!D)10603return 0;10604AdjustDeclIfTemplate(D);1060510606// In order to get name lookup right, reenter template scopes in order from10607// outermost to innermost.10608SmallVector<TemplateParameterList *, 4> ParameterLists;10609DeclContext *LookupDC = dyn_cast<DeclContext>(D);1061010611if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {10612for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)10613ParameterLists.push_back(DD->getTemplateParameterList(i));1061410615if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {10616if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())10617ParameterLists.push_back(FTD->getTemplateParameters());10618} else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {10619LookupDC = VD->getDeclContext();1062010621if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())10622ParameterLists.push_back(VTD->getTemplateParameters());10623else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))10624ParameterLists.push_back(PSD->getTemplateParameters());10625}10626} else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {10627for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)10628ParameterLists.push_back(TD->getTemplateParameterList(i));1062910630if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {10631if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())10632ParameterLists.push_back(CTD->getTemplateParameters());10633else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))10634ParameterLists.push_back(PSD->getTemplateParameters());10635}10636}10637// FIXME: Alias declarations and concepts.1063810639unsigned Count = 0;10640Scope *InnermostTemplateScope = nullptr;10641for (TemplateParameterList *Params : ParameterLists) {10642// Ignore explicit specializations; they don't contribute to the template10643// depth.10644if (Params->size() == 0)10645continue;1064610647InnermostTemplateScope = EnterScope();10648for (NamedDecl *Param : *Params) {10649if (Param->getDeclName()) {10650InnermostTemplateScope->AddDecl(Param);10651IdResolver.AddDecl(Param);10652}10653}10654++Count;10655}1065610657// Associate the new template scopes with the corresponding entities.10658if (InnermostTemplateScope) {10659assert(LookupDC && "no enclosing DeclContext for template lookup");10660EnterTemplatedContext(InnermostTemplateScope, LookupDC);10661}1066210663return Count;10664}1066510666void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {10667if (!RecordD) return;10668AdjustDeclIfTemplate(RecordD);10669CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);10670PushDeclContext(S, Record);10671}1067210673void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {10674if (!RecordD) return;10675PopDeclContext();10676}1067710678void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {10679if (!Param)10680return;1068110682S->AddDecl(Param);10683if (Param->getDeclName())10684IdResolver.AddDecl(Param);10685}1068610687void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {10688}1068910690/// ActOnDelayedCXXMethodParameter - We've already started a delayed10691/// C++ method declaration. We're (re-)introducing the given10692/// function parameter into scope for use in parsing later parts of10693/// the method declaration. For example, we could see an10694/// ActOnParamDefaultArgument event for this parameter.10695void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {10696if (!ParamD)10697return;1069810699ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);1070010701S->AddDecl(Param);10702if (Param->getDeclName())10703IdResolver.AddDecl(Param);10704}1070510706void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {10707if (!MethodD)10708return;1070910710AdjustDeclIfTemplate(MethodD);1071110712FunctionDecl *Method = cast<FunctionDecl>(MethodD);1071310714// Now that we have our default arguments, check the constructor10715// again. It could produce additional diagnostics or affect whether10716// the class has implicitly-declared destructors, among other10717// things.10718if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))10719CheckConstructor(Constructor);1072010721// Check the default arguments, which we may have added.10722if (!Method->isInvalidDecl())10723CheckCXXDefaultArguments(Method);10724}1072510726// Emit the given diagnostic for each non-address-space qualifier.10727// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.10728static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {10729const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();10730if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {10731bool DiagOccured = false;10732FTI.MethodQualifiers->forEachQualifier(10733[DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,10734SourceLocation SL) {10735// This diagnostic should be emitted on any qualifier except an addr10736// space qualifier. However, forEachQualifier currently doesn't visit10737// addr space qualifiers, so there's no way to write this condition10738// right now; we just diagnose on everything.10739S.Diag(SL, DiagID) << QualName << SourceRange(SL);10740DiagOccured = true;10741});10742if (DiagOccured)10743D.setInvalidType();10744}10745}1074610747QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,10748StorageClass &SC) {10749bool isVirtual = D.getDeclSpec().isVirtualSpecified();1075010751// C++ [class.ctor]p3:10752// A constructor shall not be virtual (10.3) or static (9.4). A10753// constructor can be invoked for a const, volatile or const10754// volatile object. A constructor shall not be declared const,10755// volatile, or const volatile (9.3.2).10756if (isVirtual) {10757if (!D.isInvalidType())10758Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)10759<< "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())10760<< SourceRange(D.getIdentifierLoc());10761D.setInvalidType();10762}10763if (SC == SC_Static) {10764if (!D.isInvalidType())10765Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)10766<< "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())10767<< SourceRange(D.getIdentifierLoc());10768D.setInvalidType();10769SC = SC_None;10770}1077110772if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {10773diagnoseIgnoredQualifiers(10774diag::err_constructor_return_type, TypeQuals, SourceLocation(),10775D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),10776D.getDeclSpec().getRestrictSpecLoc(),10777D.getDeclSpec().getAtomicSpecLoc());10778D.setInvalidType();10779}1078010781checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);1078210783// C++0x [class.ctor]p4:10784// A constructor shall not be declared with a ref-qualifier.10785DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();10786if (FTI.hasRefQualifier()) {10787Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)10788<< FTI.RefQualifierIsLValueRef10789<< FixItHint::CreateRemoval(FTI.getRefQualifierLoc());10790D.setInvalidType();10791}1079210793// Rebuild the function type "R" without any type qualifiers (in10794// case any of the errors above fired) and with "void" as the10795// return type, since constructors don't have return types.10796const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();10797if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())10798return R;1079910800FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();10801EPI.TypeQuals = Qualifiers();10802EPI.RefQualifier = RQ_None;1080310804return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);10805}1080610807void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {10808CXXRecordDecl *ClassDecl10809= dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());10810if (!ClassDecl)10811return Constructor->setInvalidDecl();1081210813// C++ [class.copy]p3:10814// A declaration of a constructor for a class X is ill-formed if10815// its first parameter is of type (optionally cv-qualified) X and10816// either there are no other parameters or else all other10817// parameters have default arguments.10818if (!Constructor->isInvalidDecl() &&10819Constructor->hasOneParamOrDefaultArgs() &&10820Constructor->getTemplateSpecializationKind() !=10821TSK_ImplicitInstantiation) {10822QualType ParamType = Constructor->getParamDecl(0)->getType();10823QualType ClassTy = Context.getTagDeclType(ClassDecl);10824if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {10825SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();10826const char *ConstRef10827= Constructor->getParamDecl(0)->getIdentifier() ? "const &"10828: " const &";10829Diag(ParamLoc, diag::err_constructor_byvalue_arg)10830<< FixItHint::CreateInsertion(ParamLoc, ConstRef);1083110832// FIXME: Rather that making the constructor invalid, we should endeavor10833// to fix the type.10834Constructor->setInvalidDecl();10835}10836}10837}1083810839bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {10840CXXRecordDecl *RD = Destructor->getParent();1084110842if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {10843SourceLocation Loc;1084410845if (!Destructor->isImplicit())10846Loc = Destructor->getLocation();10847else10848Loc = RD->getLocation();1084910850// If we have a virtual destructor, look up the deallocation function10851if (FunctionDecl *OperatorDelete =10852FindDeallocationFunctionForDestructor(Loc, RD)) {10853Expr *ThisArg = nullptr;1085410855// If the notional 'delete this' expression requires a non-trivial10856// conversion from 'this' to the type of a destroying operator delete's10857// first parameter, perform that conversion now.10858if (OperatorDelete->isDestroyingOperatorDelete()) {10859QualType ParamType = OperatorDelete->getParamDecl(0)->getType();10860if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {10861// C++ [class.dtor]p13:10862// ... as if for the expression 'delete this' appearing in a10863// non-virtual destructor of the destructor's class.10864ContextRAII SwitchContext(*this, Destructor);10865ExprResult This =10866ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());10867assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");10868This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);10869if (This.isInvalid()) {10870// FIXME: Register this as a context note so that it comes out10871// in the right order.10872Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);10873return true;10874}10875ThisArg = This.get();10876}10877}1087810879DiagnoseUseOfDecl(OperatorDelete, Loc);10880MarkFunctionReferenced(Loc, OperatorDelete);10881Destructor->setOperatorDelete(OperatorDelete, ThisArg);10882}10883}1088410885return false;10886}1088710888QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,10889StorageClass& SC) {10890// C++ [class.dtor]p1:10891// [...] A typedef-name that names a class is a class-name10892// (7.1.3); however, a typedef-name that names a class shall not10893// be used as the identifier in the declarator for a destructor10894// declaration.10895QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);10896if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())10897Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)10898<< DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());10899else if (const TemplateSpecializationType *TST =10900DeclaratorType->getAs<TemplateSpecializationType>())10901if (TST->isTypeAlias())10902Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)10903<< DeclaratorType << 1;1090410905// C++ [class.dtor]p2:10906// A destructor is used to destroy objects of its class type. A10907// destructor takes no parameters, and no return type can be10908// specified for it (not even void). The address of a destructor10909// shall not be taken. A destructor shall not be static. A10910// destructor can be invoked for a const, volatile or const10911// volatile object. A destructor shall not be declared const,10912// volatile or const volatile (9.3.2).10913if (SC == SC_Static) {10914if (!D.isInvalidType())10915Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)10916<< "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())10917<< SourceRange(D.getIdentifierLoc())10918<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());1091910920SC = SC_None;10921}10922if (!D.isInvalidType()) {10923// Destructors don't have return types, but the parser will10924// happily parse something like:10925//10926// class X {10927// float ~X();10928// };10929//10930// The return type will be eliminated later.10931if (D.getDeclSpec().hasTypeSpecifier())10932Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)10933<< SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())10934<< SourceRange(D.getIdentifierLoc());10935else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {10936diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,10937SourceLocation(),10938D.getDeclSpec().getConstSpecLoc(),10939D.getDeclSpec().getVolatileSpecLoc(),10940D.getDeclSpec().getRestrictSpecLoc(),10941D.getDeclSpec().getAtomicSpecLoc());10942D.setInvalidType();10943}10944}1094510946checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);1094710948// C++0x [class.dtor]p2:10949// A destructor shall not be declared with a ref-qualifier.10950DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();10951if (FTI.hasRefQualifier()) {10952Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)10953<< FTI.RefQualifierIsLValueRef10954<< FixItHint::CreateRemoval(FTI.getRefQualifierLoc());10955D.setInvalidType();10956}1095710958// Make sure we don't have any parameters.10959if (FTIHasNonVoidParameters(FTI)) {10960Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);1096110962// Delete the parameters.10963FTI.freeParams();10964D.setInvalidType();10965}1096610967// Make sure the destructor isn't variadic.10968if (FTI.isVariadic) {10969Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);10970D.setInvalidType();10971}1097210973// Rebuild the function type "R" without any type qualifiers or10974// parameters (in case any of the errors above fired) and with10975// "void" as the return type, since destructors don't have return10976// types.10977if (!D.isInvalidType())10978return R;1097910980const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();10981FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();10982EPI.Variadic = false;10983EPI.TypeQuals = Qualifiers();10984EPI.RefQualifier = RQ_None;10985return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);10986}1098710988static void extendLeft(SourceRange &R, SourceRange Before) {10989if (Before.isInvalid())10990return;10991R.setBegin(Before.getBegin());10992if (R.getEnd().isInvalid())10993R.setEnd(Before.getEnd());10994}1099510996static void extendRight(SourceRange &R, SourceRange After) {10997if (After.isInvalid())10998return;10999if (R.getBegin().isInvalid())11000R.setBegin(After.getBegin());11001R.setEnd(After.getEnd());11002}1100311004void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,11005StorageClass& SC) {11006// C++ [class.conv.fct]p1:11007// Neither parameter types nor return type can be specified. The11008// type of a conversion function (8.3.5) is "function taking no11009// parameter returning conversion-type-id."11010if (SC == SC_Static) {11011if (!D.isInvalidType())11012Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)11013<< SourceRange(D.getDeclSpec().getStorageClassSpecLoc())11014<< D.getName().getSourceRange();11015D.setInvalidType();11016SC = SC_None;11017}1101811019TypeSourceInfo *ConvTSI = nullptr;11020QualType ConvType =11021GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);1102211023const DeclSpec &DS = D.getDeclSpec();11024if (DS.hasTypeSpecifier() && !D.isInvalidType()) {11025// Conversion functions don't have return types, but the parser will11026// happily parse something like:11027//11028// class X {11029// float operator bool();11030// };11031//11032// The return type will be changed later anyway.11033Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)11034<< SourceRange(DS.getTypeSpecTypeLoc())11035<< SourceRange(D.getIdentifierLoc());11036D.setInvalidType();11037} else if (DS.getTypeQualifiers() && !D.isInvalidType()) {11038// It's also plausible that the user writes type qualifiers in the wrong11039// place, such as:11040// struct S { const operator int(); };11041// FIXME: we could provide a fixit to move the qualifiers onto the11042// conversion type.11043Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)11044<< SourceRange(D.getIdentifierLoc()) << 0;11045D.setInvalidType();11046}11047const auto *Proto = R->castAs<FunctionProtoType>();11048// Make sure we don't have any parameters.11049DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11050unsigned NumParam = Proto->getNumParams();1105111052// [C++2b]11053// A conversion function shall have no non-object parameters.11054if (NumParam == 1) {11055DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11056if (const auto *First =11057dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);11058First && First->isExplicitObjectParameter())11059NumParam--;11060}1106111062if (NumParam != 0) {11063Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);11064// Delete the parameters.11065FTI.freeParams();11066D.setInvalidType();11067} else if (Proto->isVariadic()) {11068Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);11069D.setInvalidType();11070}1107111072// Diagnose "&operator bool()" and other such nonsense. This11073// is actually a gcc extension which we don't support.11074if (Proto->getReturnType() != ConvType) {11075bool NeedsTypedef = false;11076SourceRange Before, After;1107711078// Walk the chunks and extract information on them for our diagnostic.11079bool PastFunctionChunk = false;11080for (auto &Chunk : D.type_objects()) {11081switch (Chunk.Kind) {11082case DeclaratorChunk::Function:11083if (!PastFunctionChunk) {11084if (Chunk.Fun.HasTrailingReturnType) {11085TypeSourceInfo *TRT = nullptr;11086GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);11087if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());11088}11089PastFunctionChunk = true;11090break;11091}11092[[fallthrough]];11093case DeclaratorChunk::Array:11094NeedsTypedef = true;11095extendRight(After, Chunk.getSourceRange());11096break;1109711098case DeclaratorChunk::Pointer:11099case DeclaratorChunk::BlockPointer:11100case DeclaratorChunk::Reference:11101case DeclaratorChunk::MemberPointer:11102case DeclaratorChunk::Pipe:11103extendLeft(Before, Chunk.getSourceRange());11104break;1110511106case DeclaratorChunk::Paren:11107extendLeft(Before, Chunk.Loc);11108extendRight(After, Chunk.EndLoc);11109break;11110}11111}1111211113SourceLocation Loc = Before.isValid() ? Before.getBegin() :11114After.isValid() ? After.getBegin() :11115D.getIdentifierLoc();11116auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);11117DB << Before << After;1111811119if (!NeedsTypedef) {11120DB << /*don't need a typedef*/0;1112111122// If we can provide a correct fix-it hint, do so.11123if (After.isInvalid() && ConvTSI) {11124SourceLocation InsertLoc =11125getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());11126DB << FixItHint::CreateInsertion(InsertLoc, " ")11127<< FixItHint::CreateInsertionFromRange(11128InsertLoc, CharSourceRange::getTokenRange(Before))11129<< FixItHint::CreateRemoval(Before);11130}11131} else if (!Proto->getReturnType()->isDependentType()) {11132DB << /*typedef*/1 << Proto->getReturnType();11133} else if (getLangOpts().CPlusPlus11) {11134DB << /*alias template*/2 << Proto->getReturnType();11135} else {11136DB << /*might not be fixable*/3;11137}1113811139// Recover by incorporating the other type chunks into the result type.11140// Note, this does *not* change the name of the function. This is compatible11141// with the GCC extension:11142// struct S { &operator int(); } s;11143// int &r = s.operator int(); // ok in GCC11144// S::operator int&() {} // error in GCC, function name is 'operator int'.11145ConvType = Proto->getReturnType();11146}1114711148// C++ [class.conv.fct]p4:11149// The conversion-type-id shall not represent a function type nor11150// an array type.11151if (ConvType->isArrayType()) {11152Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);11153ConvType = Context.getPointerType(ConvType);11154D.setInvalidType();11155} else if (ConvType->isFunctionType()) {11156Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);11157ConvType = Context.getPointerType(ConvType);11158D.setInvalidType();11159}1116011161// Rebuild the function type "R" without any parameters (in case any11162// of the errors above fired) and with the conversion type as the11163// return type.11164if (D.isInvalidType())11165R = Context.getFunctionType(ConvType, std::nullopt,11166Proto->getExtProtoInfo());1116711168// C++0x explicit conversion operators.11169if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)11170Diag(DS.getExplicitSpecLoc(),11171getLangOpts().CPlusPlus1111172? diag::warn_cxx98_compat_explicit_conversion_functions11173: diag::ext_explicit_conversion_functions)11174<< SourceRange(DS.getExplicitSpecRange());11175}1117611177Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {11178assert(Conversion && "Expected to receive a conversion function declaration");1117911180CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());1118111182// Make sure we aren't redeclaring the conversion function.11183QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());11184// C++ [class.conv.fct]p1:11185// [...] A conversion function is never used to convert a11186// (possibly cv-qualified) object to the (possibly cv-qualified)11187// same object type (or a reference to it), to a (possibly11188// cv-qualified) base class of that type (or a reference to it),11189// or to (possibly cv-qualified) void.11190QualType ClassType11191= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));11192if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())11193ConvType = ConvTypeRef->getPointeeType();11194if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&11195Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)11196/* Suppress diagnostics for instantiations. */;11197else if (Conversion->size_overridden_methods() != 0)11198/* Suppress diagnostics for overriding virtual function in a base class. */;11199else if (ConvType->isRecordType()) {11200ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();11201if (ConvType == ClassType)11202Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)11203<< ClassType;11204else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))11205Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)11206<< ClassType << ConvType;11207} else if (ConvType->isVoidType()) {11208Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)11209<< ClassType << ConvType;11210}1121111212if (FunctionTemplateDecl *ConversionTemplate =11213Conversion->getDescribedFunctionTemplate()) {11214if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {11215ConvType = ConvTypePtr->getPointeeType();11216}11217if (ConvType->isUndeducedAutoType()) {11218Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)11219<< getReturnTypeLoc(Conversion).getSourceRange()11220<< llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())11221<< /* in declaration of conversion function template= */ 24;11222}1122311224return ConversionTemplate;11225}1122611227return Conversion;11228}1122911230void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,11231DeclarationName Name, QualType R) {11232CheckExplicitObjectMemberFunction(D, Name, R, false, DC);11233}1123411235void Sema::CheckExplicitObjectLambda(Declarator &D) {11236CheckExplicitObjectMemberFunction(D, {}, {}, true);11237}1123811239void Sema::CheckExplicitObjectMemberFunction(Declarator &D,11240DeclarationName Name, QualType R,11241bool IsLambda, DeclContext *DC) {11242if (!D.isFunctionDeclarator())11243return;1124411245DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11246if (FTI.NumParams == 0)11247return;11248ParmVarDecl *ExplicitObjectParam = nullptr;11249for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {11250const auto &ParamInfo = FTI.Params[Idx];11251if (!ParamInfo.Param)11252continue;11253ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);11254if (!Param->isExplicitObjectParameter())11255continue;11256if (Idx == 0) {11257ExplicitObjectParam = Param;11258continue;11259} else {11260Diag(Param->getLocation(),11261diag::err_explicit_object_parameter_must_be_first)11262<< IsLambda << Param->getSourceRange();11263}11264}11265if (!ExplicitObjectParam)11266return;1126711268if (ExplicitObjectParam->hasDefaultArg()) {11269Diag(ExplicitObjectParam->getLocation(),11270diag::err_explicit_object_default_arg)11271<< ExplicitObjectParam->getSourceRange();11272}1127311274if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||11275(D.getContext() == clang::DeclaratorContext::Member &&11276D.isStaticMember())) {11277Diag(ExplicitObjectParam->getBeginLoc(),11278diag::err_explicit_object_parameter_nonmember)11279<< D.getSourceRange() << /*static=*/0 << IsLambda;11280D.setInvalidType();11281}1128211283if (D.getDeclSpec().isVirtualSpecified()) {11284Diag(ExplicitObjectParam->getBeginLoc(),11285diag::err_explicit_object_parameter_nonmember)11286<< D.getSourceRange() << /*virtual=*/1 << IsLambda;11287D.setInvalidType();11288}1128911290// Friend declarations require some care. Consider:11291//11292// namespace N {11293// struct A{};11294// int f(A);11295// }11296//11297// struct S {11298// struct T {11299// int f(this T);11300// };11301//11302// friend int T::f(this T); // Allow this.11303// friend int f(this S); // But disallow this.11304// friend int N::f(this A); // And disallow this.11305// };11306//11307// Here, it seems to suffice to check whether the scope11308// specifier designates a class type.11309if (D.getDeclSpec().isFriendSpecified() &&11310!isa_and_present<CXXRecordDecl>(11311computeDeclContext(D.getCXXScopeSpec()))) {11312Diag(ExplicitObjectParam->getBeginLoc(),11313diag::err_explicit_object_parameter_nonmember)11314<< D.getSourceRange() << /*non-member=*/2 << IsLambda;11315D.setInvalidType();11316}1131711318if (IsLambda && FTI.hasMutableQualifier()) {11319Diag(ExplicitObjectParam->getBeginLoc(),11320diag::err_explicit_object_parameter_mutable)11321<< D.getSourceRange();11322}1132311324if (IsLambda)11325return;1132611327if (!DC || !DC->isRecord()) {11328assert(D.isInvalidType() && "Explicit object parameter in non-member "11329"should have been diagnosed already");11330return;11331}1133211333// CWG2674: constructors and destructors cannot have explicit parameters.11334if (Name.getNameKind() == DeclarationName::CXXConstructorName ||11335Name.getNameKind() == DeclarationName::CXXDestructorName) {11336Diag(ExplicitObjectParam->getBeginLoc(),11337diag::err_explicit_object_parameter_constructor)11338<< (Name.getNameKind() == DeclarationName::CXXDestructorName)11339<< D.getSourceRange();11340D.setInvalidType();11341}11342}1134311344namespace {11345/// Utility class to accumulate and print a diagnostic listing the invalid11346/// specifier(s) on a declaration.11347struct BadSpecifierDiagnoser {11348BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)11349: S(S), Diagnostic(S.Diag(Loc, DiagID)) {}11350~BadSpecifierDiagnoser() {11351Diagnostic << Specifiers;11352}1135311354template<typename T> void check(SourceLocation SpecLoc, T Spec) {11355return check(SpecLoc, DeclSpec::getSpecifierName(Spec));11356}11357void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {11358return check(SpecLoc,11359DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));11360}11361void check(SourceLocation SpecLoc, const char *Spec) {11362if (SpecLoc.isInvalid()) return;11363Diagnostic << SourceRange(SpecLoc, SpecLoc);11364if (!Specifiers.empty()) Specifiers += " ";11365Specifiers += Spec;11366}1136711368Sema &S;11369Sema::SemaDiagnosticBuilder Diagnostic;11370std::string Specifiers;11371};11372}1137311374bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,11375StorageClass &SC) {11376TemplateName GuidedTemplate = D.getName().TemplateName.get().get();11377TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();11378assert(GuidedTemplateDecl && "missing template decl for deduction guide");1137911380// C++ [temp.deduct.guide]p3:11381// A deduction-gide shall be declared in the same scope as the11382// corresponding class template.11383if (!CurContext->getRedeclContext()->Equals(11384GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {11385Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)11386<< GuidedTemplateDecl;11387NoteTemplateLocation(*GuidedTemplateDecl);11388}1138911390auto &DS = D.getMutableDeclSpec();11391// We leave 'friend' and 'virtual' to be rejected in the normal way.11392if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||11393DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||11394DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {11395BadSpecifierDiagnoser Diagnoser(11396*this, D.getIdentifierLoc(),11397diag::err_deduction_guide_invalid_specifier);1139811399Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());11400DS.ClearStorageClassSpecs();11401SC = SC_None;1140211403// 'explicit' is permitted.11404Diagnoser.check(DS.getInlineSpecLoc(), "inline");11405Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");11406Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");11407DS.ClearConstexprSpec();1140811409Diagnoser.check(DS.getConstSpecLoc(), "const");11410Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");11411Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");11412Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");11413Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");11414DS.ClearTypeQualifiers();1141511416Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());11417Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());11418Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());11419Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());11420DS.ClearTypeSpecType();11421}1142211423if (D.isInvalidType())11424return true;1142511426// Check the declarator is simple enough.11427bool FoundFunction = false;11428for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {11429if (Chunk.Kind == DeclaratorChunk::Paren)11430continue;11431if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {11432Diag(D.getDeclSpec().getBeginLoc(),11433diag::err_deduction_guide_with_complex_decl)11434<< D.getSourceRange();11435break;11436}11437if (!Chunk.Fun.hasTrailingReturnType())11438return Diag(D.getName().getBeginLoc(),11439diag::err_deduction_guide_no_trailing_return_type);1144011441// Check that the return type is written as a specialization of11442// the template specified as the deduction-guide's name.11443// The template name may not be qualified. [temp.deduct.guide]11444ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();11445TypeSourceInfo *TSI = nullptr;11446QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);11447assert(TSI && "deduction guide has valid type but invalid return type?");11448bool AcceptableReturnType = false;11449bool MightInstantiateToSpecialization = false;11450if (auto RetTST =11451TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {11452TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();11453bool TemplateMatches =11454Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);1145511456const QualifiedTemplateName *Qualifiers =11457SpecifiedName.getAsQualifiedTemplateName();11458assert(Qualifiers && "expected QualifiedTemplate");11459bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&11460Qualifiers->getQualifier() == nullptr;11461if (SimplyWritten && TemplateMatches)11462AcceptableReturnType = true;11463else {11464// This could still instantiate to the right type, unless we know it11465// names the wrong class template.11466auto *TD = SpecifiedName.getAsTemplateDecl();11467MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&11468!TemplateMatches);11469}11470} else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {11471MightInstantiateToSpecialization = true;11472}1147311474if (!AcceptableReturnType)11475return Diag(TSI->getTypeLoc().getBeginLoc(),11476diag::err_deduction_guide_bad_trailing_return_type)11477<< GuidedTemplate << TSI->getType()11478<< MightInstantiateToSpecialization11479<< TSI->getTypeLoc().getSourceRange();1148011481// Keep going to check that we don't have any inner declarator pieces (we11482// could still have a function returning a pointer to a function).11483FoundFunction = true;11484}1148511486if (D.isFunctionDefinition())11487// we can still create a valid deduction guide here.11488Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);11489return false;11490}1149111492//===----------------------------------------------------------------------===//11493// Namespace Handling11494//===----------------------------------------------------------------------===//1149511496/// Diagnose a mismatch in 'inline' qualifiers when a namespace is11497/// reopened.11498static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,11499SourceLocation Loc,11500IdentifierInfo *II, bool *IsInline,11501NamespaceDecl *PrevNS) {11502assert(*IsInline != PrevNS->isInline());1150311504// 'inline' must appear on the original definition, but not necessarily11505// on all extension definitions, so the note should point to the first11506// definition to avoid confusion.11507PrevNS = PrevNS->getFirstDecl();1150811509if (PrevNS->isInline())11510// The user probably just forgot the 'inline', so suggest that it11511// be added back.11512S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)11513<< FixItHint::CreateInsertion(KeywordLoc, "inline ");11514else11515S.Diag(Loc, diag::err_inline_namespace_mismatch);1151611517S.Diag(PrevNS->getLocation(), diag::note_previous_definition);11518*IsInline = PrevNS->isInline();11519}1152011521/// ActOnStartNamespaceDef - This is called at the start of a namespace11522/// definition.11523Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,11524SourceLocation InlineLoc,11525SourceLocation NamespaceLoc,11526SourceLocation IdentLoc, IdentifierInfo *II,11527SourceLocation LBrace,11528const ParsedAttributesView &AttrList,11529UsingDirectiveDecl *&UD, bool IsNested) {11530SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;11531// For anonymous namespace, take the location of the left brace.11532SourceLocation Loc = II ? IdentLoc : LBrace;11533bool IsInline = InlineLoc.isValid();11534bool IsInvalid = false;11535bool IsStd = false;11536bool AddToKnown = false;11537Scope *DeclRegionScope = NamespcScope->getParent();1153811539NamespaceDecl *PrevNS = nullptr;11540if (II) {11541// C++ [namespace.std]p7:11542// A translation unit shall not declare namespace std to be an inline11543// namespace (9.8.2).11544//11545// Precondition: the std namespace is in the file scope and is declared to11546// be inline11547auto DiagnoseInlineStdNS = [&]() {11548assert(IsInline && II->isStr("std") &&11549CurContext->getRedeclContext()->isTranslationUnit() &&11550"Precondition of DiagnoseInlineStdNS not met");11551Diag(InlineLoc, diag::err_inline_namespace_std)11552<< SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));11553IsInline = false;11554};11555// C++ [namespace.def]p2:11556// The identifier in an original-namespace-definition shall not11557// have been previously defined in the declarative region in11558// which the original-namespace-definition appears. The11559// identifier in an original-namespace-definition is the name of11560// the namespace. Subsequently in that declarative region, it is11561// treated as an original-namespace-name.11562//11563// Since namespace names are unique in their scope, and we don't11564// look through using directives, just look for any ordinary names11565// as if by qualified name lookup.11566LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,11567RedeclarationKind::ForExternalRedeclaration);11568LookupQualifiedName(R, CurContext->getRedeclContext());11569NamedDecl *PrevDecl =11570R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;11571PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);1157211573if (PrevNS) {11574// This is an extended namespace definition.11575if (IsInline && II->isStr("std") &&11576CurContext->getRedeclContext()->isTranslationUnit())11577DiagnoseInlineStdNS();11578else if (IsInline != PrevNS->isInline())11579DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,11580&IsInline, PrevNS);11581} else if (PrevDecl) {11582// This is an invalid name redefinition.11583Diag(Loc, diag::err_redefinition_different_kind)11584<< II;11585Diag(PrevDecl->getLocation(), diag::note_previous_definition);11586IsInvalid = true;11587// Continue on to push Namespc as current DeclContext and return it.11588} else if (II->isStr("std") &&11589CurContext->getRedeclContext()->isTranslationUnit()) {11590if (IsInline)11591DiagnoseInlineStdNS();11592// This is the first "real" definition of the namespace "std", so update11593// our cache of the "std" namespace to point at this definition.11594PrevNS = getStdNamespace();11595IsStd = true;11596AddToKnown = !IsInline;11597} else {11598// We've seen this namespace for the first time.11599AddToKnown = !IsInline;11600}11601} else {11602// Anonymous namespaces.1160311604// Determine whether the parent already has an anonymous namespace.11605DeclContext *Parent = CurContext->getRedeclContext();11606if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {11607PrevNS = TU->getAnonymousNamespace();11608} else {11609NamespaceDecl *ND = cast<NamespaceDecl>(Parent);11610PrevNS = ND->getAnonymousNamespace();11611}1161211613if (PrevNS && IsInline != PrevNS->isInline())11614DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,11615&IsInline, PrevNS);11616}1161711618NamespaceDecl *Namespc = NamespaceDecl::Create(11619Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);11620if (IsInvalid)11621Namespc->setInvalidDecl();1162211623ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);11624AddPragmaAttributes(DeclRegionScope, Namespc);11625ProcessAPINotes(Namespc);1162611627// FIXME: Should we be merging attributes?11628if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())11629PushNamespaceVisibilityAttr(Attr, Loc);1163011631if (IsStd)11632StdNamespace = Namespc;11633if (AddToKnown)11634KnownNamespaces[Namespc] = false;1163511636if (II) {11637PushOnScopeChains(Namespc, DeclRegionScope);11638} else {11639// Link the anonymous namespace into its parent.11640DeclContext *Parent = CurContext->getRedeclContext();11641if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {11642TU->setAnonymousNamespace(Namespc);11643} else {11644cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);11645}1164611647CurContext->addDecl(Namespc);1164811649// C++ [namespace.unnamed]p1. An unnamed-namespace-definition11650// behaves as if it were replaced by11651// namespace unique { /* empty body */ }11652// using namespace unique;11653// namespace unique { namespace-body }11654// where all occurrences of 'unique' in a translation unit are11655// replaced by the same identifier and this identifier differs11656// from all other identifiers in the entire program.1165711658// We just create the namespace with an empty name and then add an11659// implicit using declaration, just like the standard suggests.11660//11661// CodeGen enforces the "universally unique" aspect by giving all11662// declarations semantically contained within an anonymous11663// namespace internal linkage.1166411665if (!PrevNS) {11666UD = UsingDirectiveDecl::Create(Context, Parent,11667/* 'using' */ LBrace,11668/* 'namespace' */ SourceLocation(),11669/* qualifier */ NestedNameSpecifierLoc(),11670/* identifier */ SourceLocation(),11671Namespc,11672/* Ancestor */ Parent);11673UD->setImplicit();11674Parent->addDecl(UD);11675}11676}1167711678ActOnDocumentableDecl(Namespc);1167911680// Although we could have an invalid decl (i.e. the namespace name is a11681// redefinition), push it as current DeclContext and try to continue parsing.11682// FIXME: We should be able to push Namespc here, so that the each DeclContext11683// for the namespace has the declarations that showed up in that particular11684// namespace definition.11685PushDeclContext(NamespcScope, Namespc);11686return Namespc;11687}1168811689/// getNamespaceDecl - Returns the namespace a decl represents. If the decl11690/// is a namespace alias, returns the namespace it points to.11691static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {11692if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))11693return AD->getNamespace();11694return dyn_cast_or_null<NamespaceDecl>(D);11695}1169611697void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {11698NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);11699assert(Namespc && "Invalid parameter, expected NamespaceDecl");11700Namespc->setRBraceLoc(RBrace);11701PopDeclContext();11702if (Namespc->hasAttr<VisibilityAttr>())11703PopPragmaVisibility(true, RBrace);11704// If this namespace contains an export-declaration, export it now.11705if (DeferredExportedNamespaces.erase(Namespc))11706Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);11707}1170811709CXXRecordDecl *Sema::getStdBadAlloc() const {11710return cast_or_null<CXXRecordDecl>(11711StdBadAlloc.get(Context.getExternalSource()));11712}1171311714EnumDecl *Sema::getStdAlignValT() const {11715return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));11716}1171711718NamespaceDecl *Sema::getStdNamespace() const {11719return cast_or_null<NamespaceDecl>(11720StdNamespace.get(Context.getExternalSource()));11721}11722namespace {1172311724enum UnsupportedSTLSelect {11725USS_InvalidMember,11726USS_MissingMember,11727USS_NonTrivial,11728USS_Other11729};1173011731struct InvalidSTLDiagnoser {11732Sema &S;11733SourceLocation Loc;11734QualType TyForDiags;1173511736QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",11737const VarDecl *VD = nullptr) {11738{11739auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)11740<< TyForDiags << ((int)Sel);11741if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {11742assert(!Name.empty());11743D << Name;11744}11745}11746if (Sel == USS_InvalidMember) {11747S.Diag(VD->getLocation(), diag::note_var_declared_here)11748<< VD << VD->getSourceRange();11749}11750return QualType();11751}11752};11753} // namespace1175411755QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,11756SourceLocation Loc,11757ComparisonCategoryUsage Usage) {11758assert(getLangOpts().CPlusPlus &&11759"Looking for comparison category type outside of C++.");1176011761// Use an elaborated type for diagnostics which has a name containing the11762// prepended 'std' namespace but not any inline namespace names.11763auto TyForDiags = [&](ComparisonCategoryInfo *Info) {11764auto *NNS =11765NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());11766return Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,11767Info->getType());11768};1176911770// Check if we've already successfully checked the comparison category type11771// before. If so, skip checking it again.11772ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);11773if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {11774// The only thing we need to check is that the type has a reachable11775// definition in the current context.11776if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))11777return QualType();1177811779return Info->getType();11780}1178111782// If lookup failed11783if (!Info) {11784std::string NameForDiags = "std::";11785NameForDiags += ComparisonCategories::getCategoryString(Kind);11786Diag(Loc, diag::err_implied_comparison_category_type_not_found)11787<< NameForDiags << (int)Usage;11788return QualType();11789}1179011791assert(Info->Kind == Kind);11792assert(Info->Record);1179311794// Update the Record decl in case we encountered a forward declaration on our11795// first pass. FIXME: This is a bit of a hack.11796if (Info->Record->hasDefinition())11797Info->Record = Info->Record->getDefinition();1179811799if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))11800return QualType();1180111802InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};1180311804if (!Info->Record->isTriviallyCopyable())11805return UnsupportedSTLError(USS_NonTrivial);1180611807for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {11808CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();11809// Tolerate empty base classes.11810if (Base->isEmpty())11811continue;11812// Reject STL implementations which have at least one non-empty base.11813return UnsupportedSTLError();11814}1181511816// Check that the STL has implemented the types using a single integer field.11817// This expectation allows better codegen for builtin operators. We require:11818// (1) The class has exactly one field.11819// (2) The field is an integral or enumeration type.11820auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();11821if (std::distance(FIt, FEnd) != 1 ||11822!FIt->getType()->isIntegralOrEnumerationType()) {11823return UnsupportedSTLError();11824}1182511826// Build each of the require values and store them in Info.11827for (ComparisonCategoryResult CCR :11828ComparisonCategories::getPossibleResultsForType(Kind)) {11829StringRef MemName = ComparisonCategories::getResultString(CCR);11830ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);1183111832if (!ValInfo)11833return UnsupportedSTLError(USS_MissingMember, MemName);1183411835VarDecl *VD = ValInfo->VD;11836assert(VD && "should not be null!");1183711838// Attempt to diagnose reasons why the STL definition of this type11839// might be foobar, including it failing to be a constant expression.11840// TODO Handle more ways the lookup or result can be invalid.11841if (!VD->isStaticDataMember() ||11842!VD->isUsableInConstantExpressions(Context))11843return UnsupportedSTLError(USS_InvalidMember, MemName, VD);1184411845// Attempt to evaluate the var decl as a constant expression and extract11846// the value of its first field as a ICE. If this fails, the STL11847// implementation is not supported.11848if (!ValInfo->hasValidIntValue())11849return UnsupportedSTLError();1185011851MarkVariableReferenced(Loc, VD);11852}1185311854// We've successfully built the required types and expressions. Update11855// the cache and return the newly cached value.11856FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;11857return Info->getType();11858}1185911860NamespaceDecl *Sema::getOrCreateStdNamespace() {11861if (!StdNamespace) {11862// The "std" namespace has not yet been defined, so build one implicitly.11863StdNamespace = NamespaceDecl::Create(11864Context, Context.getTranslationUnitDecl(),11865/*Inline=*/false, SourceLocation(), SourceLocation(),11866&PP.getIdentifierTable().get("std"),11867/*PrevDecl=*/nullptr, /*Nested=*/false);11868getStdNamespace()->setImplicit(true);11869// We want the created NamespaceDecl to be available for redeclaration11870// lookups, but not for regular name lookups.11871Context.getTranslationUnitDecl()->addDecl(getStdNamespace());11872getStdNamespace()->clearIdentifierNamespace();11873}1187411875return getStdNamespace();11876}1187711878bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {11879assert(getLangOpts().CPlusPlus &&11880"Looking for std::initializer_list outside of C++.");1188111882// We're looking for implicit instantiations of11883// template <typename E> class std::initializer_list.1188411885if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.11886return false;1188711888ClassTemplateDecl *Template = nullptr;11889const TemplateArgument *Arguments = nullptr;1189011891if (const RecordType *RT = Ty->getAs<RecordType>()) {1189211893ClassTemplateSpecializationDecl *Specialization =11894dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());11895if (!Specialization)11896return false;1189711898Template = Specialization->getSpecializedTemplate();11899Arguments = Specialization->getTemplateArgs().data();11900} else {11901const TemplateSpecializationType *TST = nullptr;11902if (auto *ICN = Ty->getAs<InjectedClassNameType>())11903TST = ICN->getInjectedTST();11904else11905TST = Ty->getAs<TemplateSpecializationType>();11906if (TST) {11907Template = dyn_cast_or_null<ClassTemplateDecl>(11908TST->getTemplateName().getAsTemplateDecl());11909Arguments = TST->template_arguments().begin();11910}11911}11912if (!Template)11913return false;1191411915if (!StdInitializerList) {11916// Haven't recognized std::initializer_list yet, maybe this is it.11917CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();11918if (TemplateClass->getIdentifier() !=11919&PP.getIdentifierTable().get("initializer_list") ||11920!getStdNamespace()->InEnclosingNamespaceSetOf(11921TemplateClass->getNonTransparentDeclContext()))11922return false;11923// This is a template called std::initializer_list, but is it the right11924// template?11925TemplateParameterList *Params = Template->getTemplateParameters();11926if (Params->getMinRequiredArguments() != 1)11927return false;11928if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))11929return false;1193011931// It's the right template.11932StdInitializerList = Template;11933}1193411935if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())11936return false;1193711938// This is an instance of std::initializer_list. Find the argument type.11939if (Element)11940*Element = Arguments[0].getAsType();11941return true;11942}1194311944static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){11945NamespaceDecl *Std = S.getStdNamespace();11946if (!Std) {11947S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);11948return nullptr;11949}1195011951LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),11952Loc, Sema::LookupOrdinaryName);11953if (!S.LookupQualifiedName(Result, Std)) {11954S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);11955return nullptr;11956}11957ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();11958if (!Template) {11959Result.suppressDiagnostics();11960// We found something weird. Complain about the first thing we found.11961NamedDecl *Found = *Result.begin();11962S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);11963return nullptr;11964}1196511966// We found some template called std::initializer_list. Now verify that it's11967// correct.11968TemplateParameterList *Params = Template->getTemplateParameters();11969if (Params->getMinRequiredArguments() != 1 ||11970!isa<TemplateTypeParmDecl>(Params->getParam(0))) {11971S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);11972return nullptr;11973}1197411975return Template;11976}1197711978QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {11979if (!StdInitializerList) {11980StdInitializerList = LookupStdInitializerList(*this, Loc);11981if (!StdInitializerList)11982return QualType();11983}1198411985TemplateArgumentListInfo Args(Loc, Loc);11986Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),11987Context.getTrivialTypeSourceInfo(Element,11988Loc)));11989return Context.getElaboratedType(11990ElaboratedTypeKeyword::None,11991NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),11992CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));11993}1199411995bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {11996// C++ [dcl.init.list]p2:11997// A constructor is an initializer-list constructor if its first parameter11998// is of type std::initializer_list<E> or reference to possibly cv-qualified11999// std::initializer_list<E> for some type E, and either there are no other12000// parameters or else all other parameters have default arguments.12001if (!Ctor->hasOneParamOrDefaultArgs())12002return false;1200312004QualType ArgType = Ctor->getParamDecl(0)->getType();12005if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())12006ArgType = RT->getPointeeType().getUnqualifiedType();1200712008return isStdInitializerList(ArgType, nullptr);12009}1201012011/// Determine whether a using statement is in a context where it will be12012/// apply in all contexts.12013static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {12014switch (CurContext->getDeclKind()) {12015case Decl::TranslationUnit:12016return true;12017case Decl::LinkageSpec:12018return IsUsingDirectiveInToplevelContext(CurContext->getParent());12019default:12020return false;12021}12022}1202312024namespace {1202512026// Callback to only accept typo corrections that are namespaces.12027class NamespaceValidatorCCC final : public CorrectionCandidateCallback {12028public:12029bool ValidateCandidate(const TypoCorrection &candidate) override {12030if (NamedDecl *ND = candidate.getCorrectionDecl())12031return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);12032return false;12033}1203412035std::unique_ptr<CorrectionCandidateCallback> clone() override {12036return std::make_unique<NamespaceValidatorCCC>(*this);12037}12038};1203912040}1204112042static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,12043Sema &S) {12044auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());12045Module *M = ND->getOwningModule();12046assert(M && "hidden namespace definition not in a module?");1204712048if (M->isExplicitGlobalModule())12049S.Diag(Corrected.getCorrectionRange().getBegin(),12050diag::err_module_unimported_use_header)12051<< (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()12052<< /*Header Name*/ false;12053else12054S.Diag(Corrected.getCorrectionRange().getBegin(),12055diag::err_module_unimported_use)12056<< (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()12057<< M->getTopLevelModuleName();12058}1205912060static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,12061CXXScopeSpec &SS,12062SourceLocation IdentLoc,12063IdentifierInfo *Ident) {12064R.clear();12065NamespaceValidatorCCC CCC{};12066if (TypoCorrection Corrected =12067S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,12068Sema::CTK_ErrorRecovery)) {12069// Generally we find it is confusing more than helpful to diagnose the12070// invisible namespace.12071// See https://github.com/llvm/llvm-project/issues/73893.12072//12073// However, we should diagnose when the users are trying to using an12074// invisible namespace. So we handle the case specially here.12075if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&12076Corrected.requiresImport()) {12077DiagnoseInvisibleNamespace(Corrected, S);12078} else if (DeclContext *DC = S.computeDeclContext(SS, false)) {12079std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));12080bool DroppedSpecifier =12081Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;12082S.diagnoseTypo(Corrected,12083S.PDiag(diag::err_using_directive_member_suggest)12084<< Ident << DC << DroppedSpecifier << SS.getRange(),12085S.PDiag(diag::note_namespace_defined_here));12086} else {12087S.diagnoseTypo(Corrected,12088S.PDiag(diag::err_using_directive_suggest) << Ident,12089S.PDiag(diag::note_namespace_defined_here));12090}12091R.addDecl(Corrected.getFoundDecl());12092return true;12093}12094return false;12095}1209612097Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,12098SourceLocation NamespcLoc, CXXScopeSpec &SS,12099SourceLocation IdentLoc,12100IdentifierInfo *NamespcName,12101const ParsedAttributesView &AttrList) {12102assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");12103assert(NamespcName && "Invalid NamespcName.");12104assert(IdentLoc.isValid() && "Invalid NamespceName location.");1210512106// Get the innermost enclosing declaration scope.12107S = S->getDeclParent();1210812109UsingDirectiveDecl *UDir = nullptr;12110NestedNameSpecifier *Qualifier = nullptr;12111if (SS.isSet())12112Qualifier = SS.getScopeRep();1211312114// Lookup namespace name.12115LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);12116LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());12117if (R.isAmbiguous())12118return nullptr;1211912120if (R.empty()) {12121R.clear();12122// Allow "using namespace std;" or "using namespace ::std;" even if12123// "std" hasn't been defined yet, for GCC compatibility.12124if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&12125NamespcName->isStr("std")) {12126Diag(IdentLoc, diag::ext_using_undefined_std);12127R.addDecl(getOrCreateStdNamespace());12128R.resolveKind();12129}12130// Otherwise, attempt typo correction.12131else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);12132}1213312134if (!R.empty()) {12135NamedDecl *Named = R.getRepresentativeDecl();12136NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();12137assert(NS && "expected namespace decl");1213812139// The use of a nested name specifier may trigger deprecation warnings.12140DiagnoseUseOfDecl(Named, IdentLoc);1214112142// C++ [namespace.udir]p1:12143// A using-directive specifies that the names in the nominated12144// namespace can be used in the scope in which the12145// using-directive appears after the using-directive. During12146// unqualified name lookup (3.4.1), the names appear as if they12147// were declared in the nearest enclosing namespace which12148// contains both the using-directive and the nominated12149// namespace. [Note: in this context, "contains" means "contains12150// directly or indirectly". ]1215112152// Find enclosing context containing both using-directive and12153// nominated namespace.12154DeclContext *CommonAncestor = NS;12155while (CommonAncestor && !CommonAncestor->Encloses(CurContext))12156CommonAncestor = CommonAncestor->getParent();1215712158UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,12159SS.getWithLocInContext(Context),12160IdentLoc, Named, CommonAncestor);1216112162if (IsUsingDirectiveInToplevelContext(CurContext) &&12163!SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {12164Diag(IdentLoc, diag::warn_using_directive_in_header);12165}1216612167PushUsingDirective(S, UDir);12168} else {12169Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();12170}1217112172if (UDir) {12173ProcessDeclAttributeList(S, UDir, AttrList);12174ProcessAPINotes(UDir);12175}1217612177return UDir;12178}1217912180void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {12181// If the scope has an associated entity and the using directive is at12182// namespace or translation unit scope, add the UsingDirectiveDecl into12183// its lookup structure so qualified name lookup can find it.12184DeclContext *Ctx = S->getEntity();12185if (Ctx && !Ctx->isFunctionOrMethod())12186Ctx->addDecl(UDir);12187else12188// Otherwise, it is at block scope. The using-directives will affect lookup12189// only to the end of the scope.12190S->PushUsingDirective(UDir);12191}1219212193Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,12194SourceLocation UsingLoc,12195SourceLocation TypenameLoc, CXXScopeSpec &SS,12196UnqualifiedId &Name,12197SourceLocation EllipsisLoc,12198const ParsedAttributesView &AttrList) {12199assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");1220012201if (SS.isEmpty()) {12202Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);12203return nullptr;12204}1220512206switch (Name.getKind()) {12207case UnqualifiedIdKind::IK_ImplicitSelfParam:12208case UnqualifiedIdKind::IK_Identifier:12209case UnqualifiedIdKind::IK_OperatorFunctionId:12210case UnqualifiedIdKind::IK_LiteralOperatorId:12211case UnqualifiedIdKind::IK_ConversionFunctionId:12212break;1221312214case UnqualifiedIdKind::IK_ConstructorName:12215case UnqualifiedIdKind::IK_ConstructorTemplateId:12216// C++11 inheriting constructors.12217Diag(Name.getBeginLoc(),12218getLangOpts().CPlusPlus1112219? diag::warn_cxx98_compat_using_decl_constructor12220: diag::err_using_decl_constructor)12221<< SS.getRange();1222212223if (getLangOpts().CPlusPlus11) break;1222412225return nullptr;1222612227case UnqualifiedIdKind::IK_DestructorName:12228Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();12229return nullptr;1223012231case UnqualifiedIdKind::IK_TemplateId:12232Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)12233<< SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);12234return nullptr;1223512236case UnqualifiedIdKind::IK_DeductionGuideName:12237llvm_unreachable("cannot parse qualified deduction guide name");12238}1223912240DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);12241DeclarationName TargetName = TargetNameInfo.getName();12242if (!TargetName)12243return nullptr;1224412245// Warn about access declarations.12246if (UsingLoc.isInvalid()) {12247Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus1112248? diag::err_access_decl12249: diag::warn_access_decl_deprecated)12250<< FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");12251}1225212253if (EllipsisLoc.isInvalid()) {12254if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||12255DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))12256return nullptr;12257} else {12258if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&12259!TargetNameInfo.containsUnexpandedParameterPack()) {12260Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)12261<< SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());12262EllipsisLoc = SourceLocation();12263}12264}1226512266NamedDecl *UD =12267BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,12268SS, TargetNameInfo, EllipsisLoc, AttrList,12269/*IsInstantiation*/ false,12270AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));12271if (UD)12272PushOnScopeChains(UD, S, /*AddToContext*/ false);1227312274return UD;12275}1227612277Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,12278SourceLocation UsingLoc,12279SourceLocation EnumLoc, SourceRange TyLoc,12280const IdentifierInfo &II, ParsedType Ty,12281CXXScopeSpec *SS) {12282assert(!SS->isInvalid() && "ScopeSpec is invalid");12283TypeSourceInfo *TSI = nullptr;12284SourceLocation IdentLoc = TyLoc.getBegin();12285QualType EnumTy = GetTypeFromParser(Ty, &TSI);12286if (EnumTy.isNull()) {12287Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)12288? diag::err_using_enum_is_dependent12289: diag::err_unknown_typename)12290<< II.getName()12291<< SourceRange(SS ? SS->getBeginLoc() : IdentLoc, TyLoc.getEnd());12292return nullptr;12293}1229412295if (EnumTy->isDependentType()) {12296Diag(IdentLoc, diag::err_using_enum_is_dependent);12297return nullptr;12298}1229912300auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());12301if (!Enum) {12302Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;12303return nullptr;12304}1230512306if (auto *Def = Enum->getDefinition())12307Enum = Def;1230812309if (TSI == nullptr)12310TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);1231112312auto *UD =12313BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);1231412315if (UD)12316PushOnScopeChains(UD, S, /*AddToContext*/ false);1231712318return UD;12319}1232012321/// Determine whether a using declaration considers the given12322/// declarations as "equivalent", e.g., if they are redeclarations of12323/// the same entity or are both typedefs of the same type.12324static bool12325IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {12326if (D1->getCanonicalDecl() == D2->getCanonicalDecl())12327return true;1232812329if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))12330if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))12331return Context.hasSameType(TD1->getUnderlyingType(),12332TD2->getUnderlyingType());1233312334// Two using_if_exists using-declarations are equivalent if both are12335// unresolved.12336if (isa<UnresolvedUsingIfExistsDecl>(D1) &&12337isa<UnresolvedUsingIfExistsDecl>(D2))12338return true;1233912340return false;12341}1234212343bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,12344const LookupResult &Previous,12345UsingShadowDecl *&PrevShadow) {12346// Diagnose finding a decl which is not from a base class of the12347// current class. We do this now because there are cases where this12348// function will silently decide not to build a shadow decl, which12349// will pre-empt further diagnostics.12350//12351// We don't need to do this in C++11 because we do the check once on12352// the qualifier.12353//12354// FIXME: diagnose the following if we care enough:12355// struct A { int foo; };12356// struct B : A { using A::foo; };12357// template <class T> struct C : A {};12358// template <class T> struct D : C<T> { using B::foo; } // <---12359// This is invalid (during instantiation) in C++03 because B::foo12360// resolves to the using decl in B, which is not a base class of D<T>.12361// We can't diagnose it immediately because C<T> is an unknown12362// specialization. The UsingShadowDecl in D<T> then points directly12363// to A::foo, which will look well-formed when we instantiate.12364// The right solution is to not collapse the shadow-decl chain.12365if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())12366if (auto *Using = dyn_cast<UsingDecl>(BUD)) {12367DeclContext *OrigDC = Orig->getDeclContext();1236812369// Handle enums and anonymous structs.12370if (isa<EnumDecl>(OrigDC))12371OrigDC = OrigDC->getParent();12372CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);12373while (OrigRec->isAnonymousStructOrUnion())12374OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());1237512376if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {12377if (OrigDC == CurContext) {12378Diag(Using->getLocation(),12379diag::err_using_decl_nested_name_specifier_is_current_class)12380<< Using->getQualifierLoc().getSourceRange();12381Diag(Orig->getLocation(), diag::note_using_decl_target);12382Using->setInvalidDecl();12383return true;12384}1238512386Diag(Using->getQualifierLoc().getBeginLoc(),12387diag::err_using_decl_nested_name_specifier_is_not_base_class)12388<< Using->getQualifier() << cast<CXXRecordDecl>(CurContext)12389<< Using->getQualifierLoc().getSourceRange();12390Diag(Orig->getLocation(), diag::note_using_decl_target);12391Using->setInvalidDecl();12392return true;12393}12394}1239512396if (Previous.empty()) return false;1239712398NamedDecl *Target = Orig;12399if (isa<UsingShadowDecl>(Target))12400Target = cast<UsingShadowDecl>(Target)->getTargetDecl();1240112402// If the target happens to be one of the previous declarations, we12403// don't have a conflict.12404//12405// FIXME: but we might be increasing its access, in which case we12406// should redeclare it.12407NamedDecl *NonTag = nullptr, *Tag = nullptr;12408bool FoundEquivalentDecl = false;12409for (LookupResult::iterator I = Previous.begin(), E = Previous.end();12410I != E; ++I) {12411NamedDecl *D = (*I)->getUnderlyingDecl();12412// We can have UsingDecls in our Previous results because we use the same12413// LookupResult for checking whether the UsingDecl itself is a valid12414// redeclaration.12415if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))12416continue;1241712418if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {12419// C++ [class.mem]p19:12420// If T is the name of a class, then [every named member other than12421// a non-static data member] shall have a name different from T12422if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&12423!isa<IndirectFieldDecl>(Target) &&12424!isa<UnresolvedUsingValueDecl>(Target) &&12425DiagnoseClassNameShadow(12426CurContext,12427DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))12428return true;12429}1243012431if (IsEquivalentForUsingDecl(Context, D, Target)) {12432if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))12433PrevShadow = Shadow;12434FoundEquivalentDecl = true;12435} else if (isEquivalentInternalLinkageDeclaration(D, Target)) {12436// We don't conflict with an existing using shadow decl of an equivalent12437// declaration, but we're not a redeclaration of it.12438FoundEquivalentDecl = true;12439}1244012441if (isVisible(D))12442(isa<TagDecl>(D) ? Tag : NonTag) = D;12443}1244412445if (FoundEquivalentDecl)12446return false;1244712448// Always emit a diagnostic for a mismatch between an unresolved12449// using_if_exists and a resolved using declaration in either direction.12450if (isa<UnresolvedUsingIfExistsDecl>(Target) !=12451(isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {12452if (!NonTag && !Tag)12453return false;12454Diag(BUD->getLocation(), diag::err_using_decl_conflict);12455Diag(Target->getLocation(), diag::note_using_decl_target);12456Diag((NonTag ? NonTag : Tag)->getLocation(),12457diag::note_using_decl_conflict);12458BUD->setInvalidDecl();12459return true;12460}1246112462if (FunctionDecl *FD = Target->getAsFunction()) {12463NamedDecl *OldDecl = nullptr;12464switch (CheckOverload(nullptr, FD, Previous, OldDecl,12465/*IsForUsingDecl*/ true)) {12466case Ovl_Overload:12467return false;1246812469case Ovl_NonFunction:12470Diag(BUD->getLocation(), diag::err_using_decl_conflict);12471break;1247212473// We found a decl with the exact signature.12474case Ovl_Match:12475// If we're in a record, we want to hide the target, so we12476// return true (without a diagnostic) to tell the caller not to12477// build a shadow decl.12478if (CurContext->isRecord())12479return true;1248012481// If we're not in a record, this is an error.12482Diag(BUD->getLocation(), diag::err_using_decl_conflict);12483break;12484}1248512486Diag(Target->getLocation(), diag::note_using_decl_target);12487Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);12488BUD->setInvalidDecl();12489return true;12490}1249112492// Target is not a function.1249312494if (isa<TagDecl>(Target)) {12495// No conflict between a tag and a non-tag.12496if (!Tag) return false;1249712498Diag(BUD->getLocation(), diag::err_using_decl_conflict);12499Diag(Target->getLocation(), diag::note_using_decl_target);12500Diag(Tag->getLocation(), diag::note_using_decl_conflict);12501BUD->setInvalidDecl();12502return true;12503}1250412505// No conflict between a tag and a non-tag.12506if (!NonTag) return false;1250712508Diag(BUD->getLocation(), diag::err_using_decl_conflict);12509Diag(Target->getLocation(), diag::note_using_decl_target);12510Diag(NonTag->getLocation(), diag::note_using_decl_conflict);12511BUD->setInvalidDecl();12512return true;12513}1251412515/// Determine whether a direct base class is a virtual base class.12516static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {12517if (!Derived->getNumVBases())12518return false;12519for (auto &B : Derived->bases())12520if (B.getType()->getAsCXXRecordDecl() == Base)12521return B.isVirtual();12522llvm_unreachable("not a direct base class");12523}1252412525UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,12526NamedDecl *Orig,12527UsingShadowDecl *PrevDecl) {12528// If we resolved to another shadow declaration, just coalesce them.12529NamedDecl *Target = Orig;12530if (isa<UsingShadowDecl>(Target)) {12531Target = cast<UsingShadowDecl>(Target)->getTargetDecl();12532assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");12533}1253412535NamedDecl *NonTemplateTarget = Target;12536if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))12537NonTemplateTarget = TargetTD->getTemplatedDecl();1253812539UsingShadowDecl *Shadow;12540if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {12541UsingDecl *Using = cast<UsingDecl>(BUD);12542bool IsVirtualBase =12543isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),12544Using->getQualifier()->getAsRecordDecl());12545Shadow = ConstructorUsingShadowDecl::Create(12546Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);12547} else {12548Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),12549Target->getDeclName(), BUD, Target);12550}12551BUD->addShadowDecl(Shadow);1255212553Shadow->setAccess(BUD->getAccess());12554if (Orig->isInvalidDecl() || BUD->isInvalidDecl())12555Shadow->setInvalidDecl();1255612557Shadow->setPreviousDecl(PrevDecl);1255812559if (S)12560PushOnScopeChains(Shadow, S);12561else12562CurContext->addDecl(Shadow);125631256412565return Shadow;12566}1256712568void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {12569if (Shadow->getDeclName().getNameKind() ==12570DeclarationName::CXXConversionFunctionName)12571cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);1257212573// Remove it from the DeclContext...12574Shadow->getDeclContext()->removeDecl(Shadow);1257512576// ...and the scope, if applicable...12577if (S) {12578S->RemoveDecl(Shadow);12579IdResolver.RemoveDecl(Shadow);12580}1258112582// ...and the using decl.12583Shadow->getIntroducer()->removeShadowDecl(Shadow);1258412585// TODO: complain somehow if Shadow was used. It shouldn't12586// be possible for this to happen, because...?12587}1258812589/// Find the base specifier for a base class with the given type.12590static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,12591QualType DesiredBase,12592bool &AnyDependentBases) {12593// Check whether the named type is a direct base class.12594CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()12595.getUnqualifiedType();12596for (auto &Base : Derived->bases()) {12597CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();12598if (CanonicalDesiredBase == BaseType)12599return &Base;12600if (BaseType->isDependentType())12601AnyDependentBases = true;12602}12603return nullptr;12604}1260512606namespace {12607class UsingValidatorCCC final : public CorrectionCandidateCallback {12608public:12609UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,12610NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)12611: HasTypenameKeyword(HasTypenameKeyword),12612IsInstantiation(IsInstantiation), OldNNS(NNS),12613RequireMemberOf(RequireMemberOf) {}1261412615bool ValidateCandidate(const TypoCorrection &Candidate) override {12616NamedDecl *ND = Candidate.getCorrectionDecl();1261712618// Keywords are not valid here.12619if (!ND || isa<NamespaceDecl>(ND))12620return false;1262112622// Completely unqualified names are invalid for a 'using' declaration.12623if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())12624return false;1262512626// FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would12627// reject.1262812629if (RequireMemberOf) {12630auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);12631if (FoundRecord && FoundRecord->isInjectedClassName()) {12632// No-one ever wants a using-declaration to name an injected-class-name12633// of a base class, unless they're declaring an inheriting constructor.12634ASTContext &Ctx = ND->getASTContext();12635if (!Ctx.getLangOpts().CPlusPlus11)12636return false;12637QualType FoundType = Ctx.getRecordType(FoundRecord);1263812639// Check that the injected-class-name is named as a member of its own12640// type; we don't want to suggest 'using Derived::Base;', since that12641// means something else.12642NestedNameSpecifier *Specifier =12643Candidate.WillReplaceSpecifier()12644? Candidate.getCorrectionSpecifier()12645: OldNNS;12646if (!Specifier->getAsType() ||12647!Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))12648return false;1264912650// Check that this inheriting constructor declaration actually names a12651// direct base class of the current class.12652bool AnyDependentBases = false;12653if (!findDirectBaseWithType(RequireMemberOf,12654Ctx.getRecordType(FoundRecord),12655AnyDependentBases) &&12656!AnyDependentBases)12657return false;12658} else {12659auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());12660if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))12661return false;1266212663// FIXME: Check that the base class member is accessible?12664}12665} else {12666auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);12667if (FoundRecord && FoundRecord->isInjectedClassName())12668return false;12669}1267012671if (isa<TypeDecl>(ND))12672return HasTypenameKeyword || !IsInstantiation;1267312674return !HasTypenameKeyword;12675}1267612677std::unique_ptr<CorrectionCandidateCallback> clone() override {12678return std::make_unique<UsingValidatorCCC>(*this);12679}1268012681private:12682bool HasTypenameKeyword;12683bool IsInstantiation;12684NestedNameSpecifier *OldNNS;12685CXXRecordDecl *RequireMemberOf;12686};12687} // end anonymous namespace1268812689void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {12690// It is really dumb that we have to do this.12691LookupResult::Filter F = Previous.makeFilter();12692while (F.hasNext()) {12693NamedDecl *D = F.next();12694if (!isDeclInScope(D, CurContext, S))12695F.erase();12696// If we found a local extern declaration that's not ordinarily visible,12697// and this declaration is being added to a non-block scope, ignore it.12698// We're only checking for scope conflicts here, not also for violations12699// of the linkage rules.12700else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&12701!(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))12702F.erase();12703}12704F.done();12705}1270612707NamedDecl *Sema::BuildUsingDeclaration(12708Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,12709bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,12710DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,12711const ParsedAttributesView &AttrList, bool IsInstantiation,12712bool IsUsingIfExists) {12713assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");12714SourceLocation IdentLoc = NameInfo.getLoc();12715assert(IdentLoc.isValid() && "Invalid TargetName location.");1271612717// FIXME: We ignore attributes for now.1271812719// For an inheriting constructor declaration, the name of the using12720// declaration is the name of a constructor in this class, not in the12721// base class.12722DeclarationNameInfo UsingName = NameInfo;12723if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)12724if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))12725UsingName.setName(Context.DeclarationNames.getCXXConstructorName(12726Context.getCanonicalType(Context.getRecordType(RD))));1272712728// Do the redeclaration lookup in the current scope.12729LookupResult Previous(*this, UsingName, LookupUsingDeclName,12730RedeclarationKind::ForVisibleRedeclaration);12731Previous.setHideTags(false);12732if (S) {12733LookupName(Previous, S);1273412735FilterUsingLookup(S, Previous);12736} else {12737assert(IsInstantiation && "no scope in non-instantiation");12738if (CurContext->isRecord())12739LookupQualifiedName(Previous, CurContext);12740else {12741// No redeclaration check is needed here; in non-member contexts we12742// diagnosed all possible conflicts with other using-declarations when12743// building the template:12744//12745// For a dependent non-type using declaration, the only valid case is12746// if we instantiate to a single enumerator. We check for conflicts12747// between shadow declarations we introduce, and we check in the template12748// definition for conflicts between a non-type using declaration and any12749// other declaration, which together covers all cases.12750//12751// A dependent typename using declaration will never successfully12752// instantiate, since it will always name a class member, so we reject12753// that in the template definition.12754}12755}1275612757// Check for invalid redeclarations.12758if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,12759SS, IdentLoc, Previous))12760return nullptr;1276112762// 'using_if_exists' doesn't make sense on an inherited constructor.12763if (IsUsingIfExists && UsingName.getName().getNameKind() ==12764DeclarationName::CXXConstructorName) {12765Diag(UsingLoc, diag::err_using_if_exists_on_ctor);12766return nullptr;12767}1276812769DeclContext *LookupContext = computeDeclContext(SS);12770NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);12771if (!LookupContext || EllipsisLoc.isValid()) {12772NamedDecl *D;12773// Dependent scope, or an unexpanded pack12774if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,12775SS, NameInfo, IdentLoc))12776return nullptr;1277712778if (HasTypenameKeyword) {12779// FIXME: not all declaration name kinds are legal here12780D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,12781UsingLoc, TypenameLoc,12782QualifierLoc,12783IdentLoc, NameInfo.getName(),12784EllipsisLoc);12785} else {12786D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,12787QualifierLoc, NameInfo, EllipsisLoc);12788}12789D->setAccess(AS);12790CurContext->addDecl(D);12791ProcessDeclAttributeList(S, D, AttrList);12792return D;12793}1279412795auto Build = [&](bool Invalid) {12796UsingDecl *UD =12797UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,12798UsingName, HasTypenameKeyword);12799UD->setAccess(AS);12800CurContext->addDecl(UD);12801ProcessDeclAttributeList(S, UD, AttrList);12802UD->setInvalidDecl(Invalid);12803return UD;12804};12805auto BuildInvalid = [&]{ return Build(true); };12806auto BuildValid = [&]{ return Build(false); };1280712808if (RequireCompleteDeclContext(SS, LookupContext))12809return BuildInvalid();1281012811// Look up the target name.12812LookupResult R(*this, NameInfo, LookupOrdinaryName);1281312814// Unlike most lookups, we don't always want to hide tag12815// declarations: tag names are visible through the using declaration12816// even if hidden by ordinary names, *except* in a dependent context12817// where they may be used by two-phase lookup.12818if (!IsInstantiation)12819R.setHideTags(false);1282012821// For the purposes of this lookup, we have a base object type12822// equal to that of the current context.12823if (CurContext->isRecord()) {12824R.setBaseObjectType(12825Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));12826}1282712828LookupQualifiedName(R, LookupContext);1282912830// Validate the context, now we have a lookup12831if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,12832IdentLoc, &R))12833return nullptr;1283412835if (R.empty() && IsUsingIfExists)12836R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,12837UsingName.getName()),12838AS_public);1283912840// Try to correct typos if possible. If constructor name lookup finds no12841// results, that means the named class has no explicit constructors, and we12842// suppressed declaring implicit ones (probably because it's dependent or12843// invalid).12844if (R.empty() &&12845NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {12846// HACK 2017-01-08: Work around an issue with libstdc++'s detection of12847// ::gets. Sometimes it believes that glibc provides a ::gets in cases where12848// it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.12849auto *II = NameInfo.getName().getAsIdentifierInfo();12850if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&12851CurContext->isStdNamespace() &&12852isa<TranslationUnitDecl>(LookupContext) &&12853getSourceManager().isInSystemHeader(UsingLoc))12854return nullptr;12855UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),12856dyn_cast<CXXRecordDecl>(CurContext));12857if (TypoCorrection Corrected =12858CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,12859CTK_ErrorRecovery)) {12860// We reject candidates where DroppedSpecifier == true, hence the12861// literal '0' below.12862diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)12863<< NameInfo.getName() << LookupContext << 012864<< SS.getRange());1286512866// If we picked a correction with no attached Decl we can't do anything12867// useful with it, bail out.12868NamedDecl *ND = Corrected.getCorrectionDecl();12869if (!ND)12870return BuildInvalid();1287112872// If we corrected to an inheriting constructor, handle it as one.12873auto *RD = dyn_cast<CXXRecordDecl>(ND);12874if (RD && RD->isInjectedClassName()) {12875// The parent of the injected class name is the class itself.12876RD = cast<CXXRecordDecl>(RD->getParent());1287712878// Fix up the information we'll use to build the using declaration.12879if (Corrected.WillReplaceSpecifier()) {12880NestedNameSpecifierLocBuilder Builder;12881Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),12882QualifierLoc.getSourceRange());12883QualifierLoc = Builder.getWithLocInContext(Context);12884}1288512886// In this case, the name we introduce is the name of a derived class12887// constructor.12888auto *CurClass = cast<CXXRecordDecl>(CurContext);12889UsingName.setName(Context.DeclarationNames.getCXXConstructorName(12890Context.getCanonicalType(Context.getRecordType(CurClass))));12891UsingName.setNamedTypeInfo(nullptr);12892for (auto *Ctor : LookupConstructors(RD))12893R.addDecl(Ctor);12894R.resolveKind();12895} else {12896// FIXME: Pick up all the declarations if we found an overloaded12897// function.12898UsingName.setName(ND->getDeclName());12899R.addDecl(ND);12900}12901} else {12902Diag(IdentLoc, diag::err_no_member)12903<< NameInfo.getName() << LookupContext << SS.getRange();12904return BuildInvalid();12905}12906}1290712908if (R.isAmbiguous())12909return BuildInvalid();1291012911if (HasTypenameKeyword) {12912// If we asked for a typename and got a non-type decl, error out.12913if (!R.getAsSingle<TypeDecl>() &&12914!R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {12915Diag(IdentLoc, diag::err_using_typename_non_type);12916for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)12917Diag((*I)->getUnderlyingDecl()->getLocation(),12918diag::note_using_decl_target);12919return BuildInvalid();12920}12921} else {12922// If we asked for a non-typename and we got a type, error out,12923// but only if this is an instantiation of an unresolved using12924// decl. Otherwise just silently find the type name.12925if (IsInstantiation && R.getAsSingle<TypeDecl>()) {12926Diag(IdentLoc, diag::err_using_dependent_value_is_type);12927Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);12928return BuildInvalid();12929}12930}1293112932// C++14 [namespace.udecl]p6:12933// A using-declaration shall not name a namespace.12934if (R.getAsSingle<NamespaceDecl>()) {12935Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)12936<< SS.getRange();12937// Suggest using 'using namespace ...' instead.12938Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)12939<< FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");12940return BuildInvalid();12941}1294212943UsingDecl *UD = BuildValid();1294412945// Some additional rules apply to inheriting constructors.12946if (UsingName.getName().getNameKind() ==12947DeclarationName::CXXConstructorName) {12948// Suppress access diagnostics; the access check is instead performed at the12949// point of use for an inheriting constructor.12950R.suppressDiagnostics();12951if (CheckInheritingConstructorUsingDecl(UD))12952return UD;12953}1295412955for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {12956UsingShadowDecl *PrevDecl = nullptr;12957if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))12958BuildUsingShadowDecl(S, UD, *I, PrevDecl);12959}1296012961return UD;12962}1296312964NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,12965SourceLocation UsingLoc,12966SourceLocation EnumLoc,12967SourceLocation NameLoc,12968TypeSourceInfo *EnumType,12969EnumDecl *ED) {12970bool Invalid = false;1297112972if (CurContext->getRedeclContext()->isRecord()) {12973/// In class scope, check if this is a duplicate, for better a diagnostic.12974DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);12975LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,12976RedeclarationKind::ForVisibleRedeclaration);1297712978LookupName(Previous, S);1297912980for (NamedDecl *D : Previous)12981if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))12982if (UED->getEnumDecl() == ED) {12983Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)12984<< SourceRange(EnumLoc, NameLoc);12985Diag(D->getLocation(), diag::note_using_enum_decl) << 1;12986Invalid = true;12987break;12988}12989}1299012991if (RequireCompleteEnumDecl(ED, NameLoc))12992Invalid = true;1299312994UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,12995EnumLoc, NameLoc, EnumType);12996UD->setAccess(AS);12997CurContext->addDecl(UD);1299812999if (Invalid) {13000UD->setInvalidDecl();13001return UD;13002}1300313004// Create the shadow decls for each enumerator13005for (EnumConstantDecl *EC : ED->enumerators()) {13006UsingShadowDecl *PrevDecl = nullptr;13007DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());13008LookupResult Previous(*this, DNI, LookupOrdinaryName,13009RedeclarationKind::ForVisibleRedeclaration);13010LookupName(Previous, S);13011FilterUsingLookup(S, Previous);1301213013if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))13014BuildUsingShadowDecl(S, UD, EC, PrevDecl);13015}1301613017return UD;13018}1301913020NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,13021ArrayRef<NamedDecl *> Expansions) {13022assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||13023isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||13024isa<UsingPackDecl>(InstantiatedFrom));1302513026auto *UPD =13027UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);13028UPD->setAccess(InstantiatedFrom->getAccess());13029CurContext->addDecl(UPD);13030return UPD;13031}1303213033bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {13034assert(!UD->hasTypename() && "expecting a constructor name");1303513036const Type *SourceType = UD->getQualifier()->getAsType();13037assert(SourceType &&13038"Using decl naming constructor doesn't have type in scope spec.");13039CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);1304013041// Check whether the named type is a direct base class.13042bool AnyDependentBases = false;13043auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),13044AnyDependentBases);13045if (!Base && !AnyDependentBases) {13046Diag(UD->getUsingLoc(),13047diag::err_using_decl_constructor_not_in_direct_base)13048<< UD->getNameInfo().getSourceRange()13049<< QualType(SourceType, 0) << TargetClass;13050UD->setInvalidDecl();13051return true;13052}1305313054if (Base)13055Base->setInheritConstructors();1305613057return false;13058}1305913060bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,13061bool HasTypenameKeyword,13062const CXXScopeSpec &SS,13063SourceLocation NameLoc,13064const LookupResult &Prev) {13065NestedNameSpecifier *Qual = SS.getScopeRep();1306613067// C++03 [namespace.udecl]p8:13068// C++0x [namespace.udecl]p10:13069// A using-declaration is a declaration and can therefore be used13070// repeatedly where (and only where) multiple declarations are13071// allowed.13072//13073// That's in non-member contexts.13074if (!CurContext->getRedeclContext()->isRecord()) {13075// A dependent qualifier outside a class can only ever resolve to an13076// enumeration type. Therefore it conflicts with any other non-type13077// declaration in the same scope.13078// FIXME: How should we check for dependent type-type conflicts at block13079// scope?13080if (Qual->isDependent() && !HasTypenameKeyword) {13081for (auto *D : Prev) {13082if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {13083bool OldCouldBeEnumerator =13084isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);13085Diag(NameLoc,13086OldCouldBeEnumerator ? diag::err_redefinition13087: diag::err_redefinition_different_kind)13088<< Prev.getLookupName();13089Diag(D->getLocation(), diag::note_previous_definition);13090return true;13091}13092}13093}13094return false;13095}1309613097const NestedNameSpecifier *CNNS =13098Context.getCanonicalNestedNameSpecifier(Qual);13099for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {13100NamedDecl *D = *I;1310113102bool DTypename;13103NestedNameSpecifier *DQual;13104if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {13105DTypename = UD->hasTypename();13106DQual = UD->getQualifier();13107} else if (UnresolvedUsingValueDecl *UD13108= dyn_cast<UnresolvedUsingValueDecl>(D)) {13109DTypename = false;13110DQual = UD->getQualifier();13111} else if (UnresolvedUsingTypenameDecl *UD13112= dyn_cast<UnresolvedUsingTypenameDecl>(D)) {13113DTypename = true;13114DQual = UD->getQualifier();13115} else continue;1311613117// using decls differ if one says 'typename' and the other doesn't.13118// FIXME: non-dependent using decls?13119if (HasTypenameKeyword != DTypename) continue;1312013121// using decls differ if they name different scopes (but note that13122// template instantiation can cause this check to trigger when it13123// didn't before instantiation).13124if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))13125continue;1312613127Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();13128Diag(D->getLocation(), diag::note_using_decl) << 1;13129return true;13130}1313113132return false;13133}1313413135bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,13136const CXXScopeSpec &SS,13137const DeclarationNameInfo &NameInfo,13138SourceLocation NameLoc,13139const LookupResult *R, const UsingDecl *UD) {13140DeclContext *NamedContext = computeDeclContext(SS);13141assert(bool(NamedContext) == (R || UD) && !(R && UD) &&13142"resolvable context must have exactly one set of decls");1314313144// C++ 20 permits using an enumerator that does not have a class-hierarchy13145// relationship.13146bool Cxx20Enumerator = false;13147if (NamedContext) {13148EnumConstantDecl *EC = nullptr;13149if (R)13150EC = R->getAsSingle<EnumConstantDecl>();13151else if (UD && UD->shadow_size() == 1)13152EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());13153if (EC)13154Cxx20Enumerator = getLangOpts().CPlusPlus20;1315513156if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {13157// C++14 [namespace.udecl]p7:13158// A using-declaration shall not name a scoped enumerator.13159// C++20 p1099 permits enumerators.13160if (EC && R && ED->isScoped())13161Diag(SS.getBeginLoc(),13162getLangOpts().CPlusPlus2013163? diag::warn_cxx17_compat_using_decl_scoped_enumerator13164: diag::ext_using_decl_scoped_enumerator)13165<< SS.getRange();1316613167// We want to consider the scope of the enumerator13168NamedContext = ED->getDeclContext();13169}13170}1317113172if (!CurContext->isRecord()) {13173// C++03 [namespace.udecl]p3:13174// C++0x [namespace.udecl]p8:13175// A using-declaration for a class member shall be a member-declaration.13176// C++20 [namespace.udecl]p713177// ... other than an enumerator ...1317813179// If we weren't able to compute a valid scope, it might validly be a13180// dependent class or enumeration scope. If we have a 'typename' keyword,13181// the scope must resolve to a class type.13182if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()13183: !HasTypename)13184return false; // OK1318513186Diag(NameLoc,13187Cxx20Enumerator13188? diag::warn_cxx17_compat_using_decl_class_member_enumerator13189: diag::err_using_decl_can_not_refer_to_class_member)13190<< SS.getRange();1319113192if (Cxx20Enumerator)13193return false; // OK1319413195auto *RD = NamedContext13196? cast<CXXRecordDecl>(NamedContext->getRedeclContext())13197: nullptr;13198if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {13199// See if there's a helpful fixit1320013201if (!R) {13202// We will have already diagnosed the problem on the template13203// definition, Maybe we should do so again?13204} else if (R->getAsSingle<TypeDecl>()) {13205if (getLangOpts().CPlusPlus11) {13206// Convert 'using X::Y;' to 'using Y = X::Y;'.13207Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)13208<< 0 // alias declaration13209<< FixItHint::CreateInsertion(SS.getBeginLoc(),13210NameInfo.getName().getAsString() +13211" = ");13212} else {13213// Convert 'using X::Y;' to 'typedef X::Y Y;'.13214SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());13215Diag(InsertLoc, diag::note_using_decl_class_member_workaround)13216<< 1 // typedef declaration13217<< FixItHint::CreateReplacement(UsingLoc, "typedef")13218<< FixItHint::CreateInsertion(13219InsertLoc, " " + NameInfo.getName().getAsString());13220}13221} else if (R->getAsSingle<VarDecl>()) {13222// Don't provide a fixit outside C++11 mode; we don't want to suggest13223// repeating the type of the static data member here.13224FixItHint FixIt;13225if (getLangOpts().CPlusPlus11) {13226// Convert 'using X::Y;' to 'auto &Y = X::Y;'.13227FixIt = FixItHint::CreateReplacement(13228UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");13229}1323013231Diag(UsingLoc, diag::note_using_decl_class_member_workaround)13232<< 2 // reference declaration13233<< FixIt;13234} else if (R->getAsSingle<EnumConstantDecl>()) {13235// Don't provide a fixit outside C++11 mode; we don't want to suggest13236// repeating the type of the enumeration here, and we can't do so if13237// the type is anonymous.13238FixItHint FixIt;13239if (getLangOpts().CPlusPlus11) {13240// Convert 'using X::Y;' to 'auto &Y = X::Y;'.13241FixIt = FixItHint::CreateReplacement(13242UsingLoc,13243"constexpr auto " + NameInfo.getName().getAsString() + " = ");13244}1324513246Diag(UsingLoc, diag::note_using_decl_class_member_workaround)13247<< (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable13248<< FixIt;13249}13250}1325113252return true; // Fail13253}1325413255// If the named context is dependent, we can't decide much.13256if (!NamedContext) {13257// FIXME: in C++0x, we can diagnose if we can prove that the13258// nested-name-specifier does not refer to a base class, which is13259// still possible in some cases.1326013261// Otherwise we have to conservatively report that things might be13262// okay.13263return false;13264}1326513266// The current scope is a record.13267if (!NamedContext->isRecord()) {13268// Ideally this would point at the last name in the specifier,13269// but we don't have that level of source info.13270Diag(SS.getBeginLoc(),13271Cxx20Enumerator13272? diag::warn_cxx17_compat_using_decl_non_member_enumerator13273: diag::err_using_decl_nested_name_specifier_is_not_class)13274<< SS.getScopeRep() << SS.getRange();1327513276if (Cxx20Enumerator)13277return false; // OK1327813279return true;13280}1328113282if (!NamedContext->isDependentContext() &&13283RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))13284return true;1328513286if (getLangOpts().CPlusPlus11) {13287// C++11 [namespace.udecl]p3:13288// In a using-declaration used as a member-declaration, the13289// nested-name-specifier shall name a base class of the class13290// being defined.1329113292if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(13293cast<CXXRecordDecl>(NamedContext))) {1329413295if (Cxx20Enumerator) {13296Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)13297<< SS.getRange();13298return false;13299}1330013301if (CurContext == NamedContext) {13302Diag(SS.getBeginLoc(),13303diag::err_using_decl_nested_name_specifier_is_current_class)13304<< SS.getRange();13305return !getLangOpts().CPlusPlus20;13306}1330713308if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {13309Diag(SS.getBeginLoc(),13310diag::err_using_decl_nested_name_specifier_is_not_base_class)13311<< SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)13312<< SS.getRange();13313}13314return true;13315}1331613317return false;13318}1331913320// C++03 [namespace.udecl]p4:13321// A using-declaration used as a member-declaration shall refer13322// to a member of a base class of the class being defined [etc.].1332313324// Salient point: SS doesn't have to name a base class as long as13325// lookup only finds members from base classes. Therefore we can13326// diagnose here only if we can prove that can't happen,13327// i.e. if the class hierarchies provably don't intersect.1332813329// TODO: it would be nice if "definitely valid" results were cached13330// in the UsingDecl and UsingShadowDecl so that these checks didn't13331// need to be repeated.1333213333llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;13334auto Collect = [&Bases](const CXXRecordDecl *Base) {13335Bases.insert(Base);13336return true;13337};1333813339// Collect all bases. Return false if we find a dependent base.13340if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))13341return false;1334213343// Returns true if the base is dependent or is one of the accumulated base13344// classes.13345auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {13346return !Bases.count(Base);13347};1334813349// Return false if the class has a dependent base or if it or one13350// of its bases is present in the base set of the current context.13351if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||13352!cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))13353return false;1335413355Diag(SS.getRange().getBegin(),13356diag::err_using_decl_nested_name_specifier_is_not_base_class)13357<< SS.getScopeRep()13358<< cast<CXXRecordDecl>(CurContext)13359<< SS.getRange();1336013361return true;13362}1336313364Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,13365MultiTemplateParamsArg TemplateParamLists,13366SourceLocation UsingLoc, UnqualifiedId &Name,13367const ParsedAttributesView &AttrList,13368TypeResult Type, Decl *DeclFromDeclSpec) {13369// Get the innermost enclosing declaration scope.13370S = S->getDeclParent();1337113372if (Type.isInvalid())13373return nullptr;1337413375bool Invalid = false;13376DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);13377TypeSourceInfo *TInfo = nullptr;13378GetTypeFromParser(Type.get(), &TInfo);1337913380if (DiagnoseClassNameShadow(CurContext, NameInfo))13381return nullptr;1338213383if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,13384UPPC_DeclarationType)) {13385Invalid = true;13386TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,13387TInfo->getTypeLoc().getBeginLoc());13388}1338913390LookupResult Previous(*this, NameInfo, LookupOrdinaryName,13391TemplateParamLists.size()13392? forRedeclarationInCurContext()13393: RedeclarationKind::ForVisibleRedeclaration);13394LookupName(Previous, S);1339513396// Warn about shadowing the name of a template parameter.13397if (Previous.isSingleResult() &&13398Previous.getFoundDecl()->isTemplateParameter()) {13399DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());13400Previous.clear();13401}1340213403assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&13404"name in alias declaration must be an identifier");13405TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,13406Name.StartLocation,13407Name.Identifier, TInfo);1340813409NewTD->setAccess(AS);1341013411if (Invalid)13412NewTD->setInvalidDecl();1341313414ProcessDeclAttributeList(S, NewTD, AttrList);13415AddPragmaAttributes(S, NewTD);13416ProcessAPINotes(NewTD);1341713418CheckTypedefForVariablyModifiedType(S, NewTD);13419Invalid |= NewTD->isInvalidDecl();1342013421bool Redeclaration = false;1342213423NamedDecl *NewND;13424if (TemplateParamLists.size()) {13425TypeAliasTemplateDecl *OldDecl = nullptr;13426TemplateParameterList *OldTemplateParams = nullptr;1342713428if (TemplateParamLists.size() != 1) {13429Diag(UsingLoc, diag::err_alias_template_extra_headers)13430<< SourceRange(TemplateParamLists[1]->getTemplateLoc(),13431TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());13432Invalid = true;13433}13434TemplateParameterList *TemplateParams = TemplateParamLists[0];1343513436// Check that we can declare a template here.13437if (CheckTemplateDeclScope(S, TemplateParams))13438return nullptr;1343913440// Only consider previous declarations in the same scope.13441FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,13442/*ExplicitInstantiationOrSpecialization*/false);13443if (!Previous.empty()) {13444Redeclaration = true;1344513446OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();13447if (!OldDecl && !Invalid) {13448Diag(UsingLoc, diag::err_redefinition_different_kind)13449<< Name.Identifier;1345013451NamedDecl *OldD = Previous.getRepresentativeDecl();13452if (OldD->getLocation().isValid())13453Diag(OldD->getLocation(), diag::note_previous_definition);1345413455Invalid = true;13456}1345713458if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {13459if (TemplateParameterListsAreEqual(TemplateParams,13460OldDecl->getTemplateParameters(),13461/*Complain=*/true,13462TPL_TemplateMatch))13463OldTemplateParams =13464OldDecl->getMostRecentDecl()->getTemplateParameters();13465else13466Invalid = true;1346713468TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();13469if (!Invalid &&13470!Context.hasSameType(OldTD->getUnderlyingType(),13471NewTD->getUnderlyingType())) {13472// FIXME: The C++0x standard does not clearly say this is ill-formed,13473// but we can't reasonably accept it.13474Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)13475<< 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();13476if (OldTD->getLocation().isValid())13477Diag(OldTD->getLocation(), diag::note_previous_definition);13478Invalid = true;13479}13480}13481}1348213483// Merge any previous default template arguments into our parameters,13484// and check the parameter list.13485if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,13486TPC_TypeAliasTemplate))13487return nullptr;1348813489TypeAliasTemplateDecl *NewDecl =13490TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,13491Name.Identifier, TemplateParams,13492NewTD);13493NewTD->setDescribedAliasTemplate(NewDecl);1349413495NewDecl->setAccess(AS);1349613497if (Invalid)13498NewDecl->setInvalidDecl();13499else if (OldDecl) {13500NewDecl->setPreviousDecl(OldDecl);13501CheckRedeclarationInModule(NewDecl, OldDecl);13502}1350313504NewND = NewDecl;13505} else {13506if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {13507setTagNameForLinkagePurposes(TD, NewTD);13508handleTagNumbering(TD, S);13509}13510ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);13511NewND = NewTD;13512}1351313514PushOnScopeChains(NewND, S);13515ActOnDocumentableDecl(NewND);13516return NewND;13517}1351813519Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,13520SourceLocation AliasLoc,13521IdentifierInfo *Alias, CXXScopeSpec &SS,13522SourceLocation IdentLoc,13523IdentifierInfo *Ident) {1352413525// Lookup the namespace name.13526LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);13527LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());1352813529if (R.isAmbiguous())13530return nullptr;1353113532if (R.empty()) {13533if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {13534Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();13535return nullptr;13536}13537}13538assert(!R.isAmbiguous() && !R.empty());13539NamedDecl *ND = R.getRepresentativeDecl();1354013541// Check if we have a previous declaration with the same name.13542LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,13543RedeclarationKind::ForVisibleRedeclaration);13544LookupName(PrevR, S);1354513546// Check we're not shadowing a template parameter.13547if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {13548DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());13549PrevR.clear();13550}1355113552// Filter out any other lookup result from an enclosing scope.13553FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,13554/*AllowInlineNamespace*/false);1355513556// Find the previous declaration and check that we can redeclare it.13557NamespaceAliasDecl *Prev = nullptr;13558if (PrevR.isSingleResult()) {13559NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();13560if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {13561// We already have an alias with the same name that points to the same13562// namespace; check that it matches.13563if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {13564Prev = AD;13565} else if (isVisible(PrevDecl)) {13566Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)13567<< Alias;13568Diag(AD->getLocation(), diag::note_previous_namespace_alias)13569<< AD->getNamespace();13570return nullptr;13571}13572} else if (isVisible(PrevDecl)) {13573unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())13574? diag::err_redefinition13575: diag::err_redefinition_different_kind;13576Diag(AliasLoc, DiagID) << Alias;13577Diag(PrevDecl->getLocation(), diag::note_previous_definition);13578return nullptr;13579}13580}1358113582// The use of a nested name specifier may trigger deprecation warnings.13583DiagnoseUseOfDecl(ND, IdentLoc);1358413585NamespaceAliasDecl *AliasDecl =13586NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,13587Alias, SS.getWithLocInContext(Context),13588IdentLoc, ND);13589if (Prev)13590AliasDecl->setPreviousDecl(Prev);1359113592PushOnScopeChains(AliasDecl, S);13593return AliasDecl;13594}1359513596namespace {13597struct SpecialMemberExceptionSpecInfo13598: SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {13599SourceLocation Loc;13600Sema::ImplicitExceptionSpecification ExceptSpec;1360113602SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,13603CXXSpecialMemberKind CSM,13604Sema::InheritedConstructorInfo *ICI,13605SourceLocation Loc)13606: SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}1360713608bool visitBase(CXXBaseSpecifier *Base);13609bool visitField(FieldDecl *FD);1361013611void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,13612unsigned Quals);1361313614void visitSubobjectCall(Subobject Subobj,13615Sema::SpecialMemberOverloadResult SMOR);13616};13617}1361813619bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {13620auto *RT = Base->getType()->getAs<RecordType>();13621if (!RT)13622return false;1362313624auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());13625Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);13626if (auto *BaseCtor = SMOR.getMethod()) {13627visitSubobjectCall(Base, BaseCtor);13628return false;13629}1363013631visitClassSubobject(BaseClass, Base, 0);13632return false;13633}1363413635bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {13636if (CSM == CXXSpecialMemberKind::DefaultConstructor &&13637FD->hasInClassInitializer()) {13638Expr *E = FD->getInClassInitializer();13639if (!E)13640// FIXME: It's a little wasteful to build and throw away a13641// CXXDefaultInitExpr here.13642// FIXME: We should have a single context note pointing at Loc, and13643// this location should be MD->getLocation() instead, since that's13644// the location where we actually use the default init expression.13645E = S.BuildCXXDefaultInitExpr(Loc, FD).get();13646if (E)13647ExceptSpec.CalledExpr(E);13648} else if (auto *RT = S.Context.getBaseElementType(FD->getType())13649->getAs<RecordType>()) {13650visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,13651FD->getType().getCVRQualifiers());13652}13653return false;13654}1365513656void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,13657Subobject Subobj,13658unsigned Quals) {13659FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();13660bool IsMutable = Field && Field->isMutable();13661visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));13662}1366313664void SpecialMemberExceptionSpecInfo::visitSubobjectCall(13665Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {13666// Note, if lookup fails, it doesn't matter what exception specification we13667// choose because the special member will be deleted.13668if (CXXMethodDecl *MD = SMOR.getMethod())13669ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);13670}1367113672bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {13673llvm::APSInt Result;13674ExprResult Converted = CheckConvertedConstantExpression(13675ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);13676ExplicitSpec.setExpr(Converted.get());13677if (Converted.isUsable() && !Converted.get()->isValueDependent()) {13678ExplicitSpec.setKind(Result.getBoolValue()13679? ExplicitSpecKind::ResolvedTrue13680: ExplicitSpecKind::ResolvedFalse);13681return true;13682}13683ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);13684return false;13685}1368613687ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {13688ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);13689if (!ExplicitExpr->isTypeDependent())13690tryResolveExplicitSpecifier(ES);13691return ES;13692}1369313694static Sema::ImplicitExceptionSpecification13695ComputeDefaultedSpecialMemberExceptionSpec(13696Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,13697Sema::InheritedConstructorInfo *ICI) {13698ComputingExceptionSpec CES(S, MD, Loc);1369913700CXXRecordDecl *ClassDecl = MD->getParent();1370113702// C++ [except.spec]p14:13703// An implicitly declared special member function (Clause 12) shall have an13704// exception-specification. [...]13705SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());13706if (ClassDecl->isInvalidDecl())13707return Info.ExceptSpec;1370813709// FIXME: If this diagnostic fires, we're probably missing a check for13710// attempting to resolve an exception specification before it's known13711// at a higher level.13712if (S.RequireCompleteType(MD->getLocation(),13713S.Context.getRecordType(ClassDecl),13714diag::err_exception_spec_incomplete_type))13715return Info.ExceptSpec;1371613717// C++1z [except.spec]p7:13718// [Look for exceptions thrown by] a constructor selected [...] to13719// initialize a potentially constructed subobject,13720// C++1z [except.spec]p8:13721// The exception specification for an implicitly-declared destructor, or a13722// destructor without a noexcept-specifier, is potentially-throwing if and13723// only if any of the destructors for any of its potentially constructed13724// subojects is potentially throwing.13725// FIXME: We respect the first rule but ignore the "potentially constructed"13726// in the second rule to resolve a core issue (no number yet) that would have13727// us reject:13728// struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };13729// struct B : A {};13730// struct C : B { void f(); };13731// ... due to giving B::~B() a non-throwing exception specification.13732Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases13733: Info.VisitAllBases);1373413735return Info.ExceptSpec;13736}1373713738namespace {13739/// RAII object to register a special member as being currently declared.13740struct DeclaringSpecialMember {13741Sema &S;13742Sema::SpecialMemberDecl D;13743Sema::ContextRAII SavedContext;13744bool WasAlreadyBeingDeclared;1374513746DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)13747: S(S), D(RD, CSM), SavedContext(S, RD) {13748WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;13749if (WasAlreadyBeingDeclared)13750// This almost never happens, but if it does, ensure that our cache13751// doesn't contain a stale result.13752S.SpecialMemberCache.clear();13753else {13754// Register a note to be produced if we encounter an error while13755// declaring the special member.13756Sema::CodeSynthesisContext Ctx;13757Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;13758// FIXME: We don't have a location to use here. Using the class's13759// location maintains the fiction that we declare all special members13760// with the class, but (1) it's not clear that lying about that helps our13761// users understand what's going on, and (2) there may be outer contexts13762// on the stack (some of which are relevant) and printing them exposes13763// our lies.13764Ctx.PointOfInstantiation = RD->getLocation();13765Ctx.Entity = RD;13766Ctx.SpecialMember = CSM;13767S.pushCodeSynthesisContext(Ctx);13768}13769}13770~DeclaringSpecialMember() {13771if (!WasAlreadyBeingDeclared) {13772S.SpecialMembersBeingDeclared.erase(D);13773S.popCodeSynthesisContext();13774}13775}1377613777/// Are we already trying to declare this special member?13778bool isAlreadyBeingDeclared() const {13779return WasAlreadyBeingDeclared;13780}13781};13782}1378313784void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {13785// Look up any existing declarations, but don't trigger declaration of all13786// implicit special members with this name.13787DeclarationName Name = FD->getDeclName();13788LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,13789RedeclarationKind::ForExternalRedeclaration);13790for (auto *D : FD->getParent()->lookup(Name))13791if (auto *Acceptable = R.getAcceptableDecl(D))13792R.addDecl(Acceptable);13793R.resolveKind();13794R.suppressDiagnostics();1379513796CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,13797FD->isThisDeclarationADefinition());13798}1379913800void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,13801QualType ResultTy,13802ArrayRef<QualType> Args) {13803// Build an exception specification pointing back at this constructor.13804FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);1380513806LangAS AS = getDefaultCXXMethodAddrSpace();13807if (AS != LangAS::Default) {13808EPI.TypeQuals.addAddressSpace(AS);13809}1381013811auto QT = Context.getFunctionType(ResultTy, Args, EPI);13812SpecialMem->setType(QT);1381313814// During template instantiation of implicit special member functions we need13815// a reliable TypeSourceInfo for the function prototype in order to allow13816// functions to be substituted.13817if (inTemplateInstantiation() &&13818cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {13819TypeSourceInfo *TSI =13820Context.getTrivialTypeSourceInfo(SpecialMem->getType());13821SpecialMem->setTypeSourceInfo(TSI);13822}13823}1382413825CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(13826CXXRecordDecl *ClassDecl) {13827// C++ [class.ctor]p5:13828// A default constructor for a class X is a constructor of class X13829// that can be called without an argument. If there is no13830// user-declared constructor for class X, a default constructor is13831// implicitly declared. An implicitly-declared default constructor13832// is an inline public member of its class.13833assert(ClassDecl->needsImplicitDefaultConstructor() &&13834"Should not build implicit default constructor!");1383513836DeclaringSpecialMember DSM(*this, ClassDecl,13837CXXSpecialMemberKind::DefaultConstructor);13838if (DSM.isAlreadyBeingDeclared())13839return nullptr;1384013841bool Constexpr = defaultedSpecialMemberIsConstexpr(13842*this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);1384313844// Create the actual constructor declaration.13845CanQualType ClassType13846= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));13847SourceLocation ClassLoc = ClassDecl->getLocation();13848DeclarationName Name13849= Context.DeclarationNames.getCXXConstructorName(ClassType);13850DeclarationNameInfo NameInfo(Name, ClassLoc);13851CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(13852Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),13853/*TInfo=*/nullptr, ExplicitSpecifier(),13854getCurFPFeatures().isFPConstrained(),13855/*isInline=*/true, /*isImplicitlyDeclared=*/true,13856Constexpr ? ConstexprSpecKind::Constexpr13857: ConstexprSpecKind::Unspecified);13858DefaultCon->setAccess(AS_public);13859DefaultCon->setDefaulted();1386013861setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);1386213863if (getLangOpts().CUDA)13864CUDA().inferTargetForImplicitSpecialMember(13865ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,13866/* ConstRHS */ false,13867/* Diagnose */ false);1386813869// We don't need to use SpecialMemberIsTrivial here; triviality for default13870// constructors is easy to compute.13871DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());1387213873// Note that we have declared this constructor.13874++getASTContext().NumImplicitDefaultConstructorsDeclared;1387513876Scope *S = getScopeForContext(ClassDecl);13877CheckImplicitSpecialMemberDeclaration(S, DefaultCon);1387813879if (ShouldDeleteSpecialMember(DefaultCon,13880CXXSpecialMemberKind::DefaultConstructor))13881SetDeclDeleted(DefaultCon, ClassLoc);1388213883if (S)13884PushOnScopeChains(DefaultCon, S, false);13885ClassDecl->addDecl(DefaultCon);1388613887return DefaultCon;13888}1388913890void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,13891CXXConstructorDecl *Constructor) {13892assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&13893!Constructor->doesThisDeclarationHaveABody() &&13894!Constructor->isDeleted()) &&13895"DefineImplicitDefaultConstructor - call it for implicit default ctor");13896if (Constructor->willHaveBody() || Constructor->isInvalidDecl())13897return;1389813899CXXRecordDecl *ClassDecl = Constructor->getParent();13900assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");13901if (ClassDecl->isInvalidDecl()) {13902return;13903}1390413905SynthesizedFunctionScope Scope(*this, Constructor);1390613907// The exception specification is needed because we are defining the13908// function.13909ResolveExceptionSpec(CurrentLocation,13910Constructor->getType()->castAs<FunctionProtoType>());13911MarkVTableUsed(CurrentLocation, ClassDecl);1391213913// Add a context note for diagnostics produced after this point.13914Scope.addContextNote(CurrentLocation);1391513916if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {13917Constructor->setInvalidDecl();13918return;13919}1392013921SourceLocation Loc = Constructor->getEndLoc().isValid()13922? Constructor->getEndLoc()13923: Constructor->getLocation();13924Constructor->setBody(new (Context) CompoundStmt(Loc));13925Constructor->markUsed(Context);1392613927if (ASTMutationListener *L = getASTMutationListener()) {13928L->CompletedImplicitDefinition(Constructor);13929}1393013931DiagnoseUninitializedFields(*this, Constructor);13932}1393313934void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {13935// Perform any delayed checks on exception specifications.13936CheckDelayedMemberExceptionSpecs();13937}1393813939/// Find or create the fake constructor we synthesize to model constructing an13940/// object of a derived class via a constructor of a base class.13941CXXConstructorDecl *13942Sema::findInheritingConstructor(SourceLocation Loc,13943CXXConstructorDecl *BaseCtor,13944ConstructorUsingShadowDecl *Shadow) {13945CXXRecordDecl *Derived = Shadow->getParent();13946SourceLocation UsingLoc = Shadow->getLocation();1394713948// FIXME: Add a new kind of DeclarationName for an inherited constructor.13949// For now we use the name of the base class constructor as a member of the13950// derived class to indicate a (fake) inherited constructor name.13951DeclarationName Name = BaseCtor->getDeclName();1395213953// Check to see if we already have a fake constructor for this inherited13954// constructor call.13955for (NamedDecl *Ctor : Derived->lookup(Name))13956if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)13957->getInheritedConstructor()13958.getConstructor(),13959BaseCtor))13960return cast<CXXConstructorDecl>(Ctor);1396113962DeclarationNameInfo NameInfo(Name, UsingLoc);13963TypeSourceInfo *TInfo =13964Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);13965FunctionProtoTypeLoc ProtoLoc =13966TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();1396713968// Check the inherited constructor is valid and find the list of base classes13969// from which it was inherited.13970InheritedConstructorInfo ICI(*this, Loc, Shadow);1397113972bool Constexpr = BaseCtor->isConstexpr() &&13973defaultedSpecialMemberIsConstexpr(13974*this, Derived, CXXSpecialMemberKind::DefaultConstructor,13975false, BaseCtor, &ICI);1397613977CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(13978Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,13979BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),13980/*isInline=*/true,13981/*isImplicitlyDeclared=*/true,13982Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,13983InheritedConstructor(Shadow, BaseCtor),13984BaseCtor->getTrailingRequiresClause());13985if (Shadow->isInvalidDecl())13986DerivedCtor->setInvalidDecl();1398713988// Build an unevaluated exception specification for this fake constructor.13989const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();13990FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();13991EPI.ExceptionSpec.Type = EST_Unevaluated;13992EPI.ExceptionSpec.SourceDecl = DerivedCtor;13993DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),13994FPT->getParamTypes(), EPI));1399513996// Build the parameter declarations.13997SmallVector<ParmVarDecl *, 16> ParamDecls;13998for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {13999TypeSourceInfo *TInfo =14000Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);14001ParmVarDecl *PD = ParmVarDecl::Create(14002Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,14003FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);14004PD->setScopeInfo(0, I);14005PD->setImplicit();14006// Ensure attributes are propagated onto parameters (this matters for14007// format, pass_object_size, ...).14008mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));14009ParamDecls.push_back(PD);14010ProtoLoc.setParam(I, PD);14011}1401214013// Set up the new constructor.14014assert(!BaseCtor->isDeleted() && "should not use deleted constructor");14015DerivedCtor->setAccess(BaseCtor->getAccess());14016DerivedCtor->setParams(ParamDecls);14017Derived->addDecl(DerivedCtor);1401814019if (ShouldDeleteSpecialMember(DerivedCtor,14020CXXSpecialMemberKind::DefaultConstructor, &ICI))14021SetDeclDeleted(DerivedCtor, UsingLoc);1402214023return DerivedCtor;14024}1402514026void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {14027InheritedConstructorInfo ICI(*this, Ctor->getLocation(),14028Ctor->getInheritedConstructor().getShadowDecl());14029ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,14030&ICI,14031/*Diagnose*/ true);14032}1403314034void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,14035CXXConstructorDecl *Constructor) {14036CXXRecordDecl *ClassDecl = Constructor->getParent();14037assert(Constructor->getInheritedConstructor() &&14038!Constructor->doesThisDeclarationHaveABody() &&14039!Constructor->isDeleted());14040if (Constructor->willHaveBody() || Constructor->isInvalidDecl())14041return;1404214043// Initializations are performed "as if by a defaulted default constructor",14044// so enter the appropriate scope.14045SynthesizedFunctionScope Scope(*this, Constructor);1404614047// The exception specification is needed because we are defining the14048// function.14049ResolveExceptionSpec(CurrentLocation,14050Constructor->getType()->castAs<FunctionProtoType>());14051MarkVTableUsed(CurrentLocation, ClassDecl);1405214053// Add a context note for diagnostics produced after this point.14054Scope.addContextNote(CurrentLocation);1405514056ConstructorUsingShadowDecl *Shadow =14057Constructor->getInheritedConstructor().getShadowDecl();14058CXXConstructorDecl *InheritedCtor =14059Constructor->getInheritedConstructor().getConstructor();1406014061// [class.inhctor.init]p1:14062// initialization proceeds as if a defaulted default constructor is used to14063// initialize the D object and each base class subobject from which the14064// constructor was inherited1406514066InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);14067CXXRecordDecl *RD = Shadow->getParent();14068SourceLocation InitLoc = Shadow->getLocation();1406914070// Build explicit initializers for all base classes from which the14071// constructor was inherited.14072SmallVector<CXXCtorInitializer*, 8> Inits;14073for (bool VBase : {false, true}) {14074for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {14075if (B.isVirtual() != VBase)14076continue;1407714078auto *BaseRD = B.getType()->getAsCXXRecordDecl();14079if (!BaseRD)14080continue;1408114082auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);14083if (!BaseCtor.first)14084continue;1408514086MarkFunctionReferenced(CurrentLocation, BaseCtor.first);14087ExprResult Init = new (Context) CXXInheritedCtorInitExpr(14088InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);1408914090auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);14091Inits.push_back(new (Context) CXXCtorInitializer(14092Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,14093SourceLocation()));14094}14095}1409614097// We now proceed as if for a defaulted default constructor, with the relevant14098// initializers replaced.1409914100if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {14101Constructor->setInvalidDecl();14102return;14103}1410414105Constructor->setBody(new (Context) CompoundStmt(InitLoc));14106Constructor->markUsed(Context);1410714108if (ASTMutationListener *L = getASTMutationListener()) {14109L->CompletedImplicitDefinition(Constructor);14110}1411114112DiagnoseUninitializedFields(*this, Constructor);14113}1411414115CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {14116// C++ [class.dtor]p2:14117// If a class has no user-declared destructor, a destructor is14118// declared implicitly. An implicitly-declared destructor is an14119// inline public member of its class.14120assert(ClassDecl->needsImplicitDestructor());1412114122DeclaringSpecialMember DSM(*this, ClassDecl,14123CXXSpecialMemberKind::Destructor);14124if (DSM.isAlreadyBeingDeclared())14125return nullptr;1412614127bool Constexpr = defaultedSpecialMemberIsConstexpr(14128*this, ClassDecl, CXXSpecialMemberKind::Destructor, false);1412914130// Create the actual destructor declaration.14131CanQualType ClassType14132= Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));14133SourceLocation ClassLoc = ClassDecl->getLocation();14134DeclarationName Name14135= Context.DeclarationNames.getCXXDestructorName(ClassType);14136DeclarationNameInfo NameInfo(Name, ClassLoc);14137CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(14138Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,14139getCurFPFeatures().isFPConstrained(),14140/*isInline=*/true,14141/*isImplicitlyDeclared=*/true,14142Constexpr ? ConstexprSpecKind::Constexpr14143: ConstexprSpecKind::Unspecified);14144Destructor->setAccess(AS_public);14145Destructor->setDefaulted();1414614147setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);1414814149if (getLangOpts().CUDA)14150CUDA().inferTargetForImplicitSpecialMember(14151ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,14152/* ConstRHS */ false,14153/* Diagnose */ false);1415414155// We don't need to use SpecialMemberIsTrivial here; triviality for14156// destructors is easy to compute.14157Destructor->setTrivial(ClassDecl->hasTrivialDestructor());14158Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||14159ClassDecl->hasTrivialDestructorForCall());1416014161// Note that we have declared this destructor.14162++getASTContext().NumImplicitDestructorsDeclared;1416314164Scope *S = getScopeForContext(ClassDecl);14165CheckImplicitSpecialMemberDeclaration(S, Destructor);1416614167// We can't check whether an implicit destructor is deleted before we complete14168// the definition of the class, because its validity depends on the alignment14169// of the class. We'll check this from ActOnFields once the class is complete.14170if (ClassDecl->isCompleteDefinition() &&14171ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))14172SetDeclDeleted(Destructor, ClassLoc);1417314174// Introduce this destructor into its scope.14175if (S)14176PushOnScopeChains(Destructor, S, false);14177ClassDecl->addDecl(Destructor);1417814179return Destructor;14180}1418114182void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,14183CXXDestructorDecl *Destructor) {14184assert((Destructor->isDefaulted() &&14185!Destructor->doesThisDeclarationHaveABody() &&14186!Destructor->isDeleted()) &&14187"DefineImplicitDestructor - call it for implicit default dtor");14188if (Destructor->willHaveBody() || Destructor->isInvalidDecl())14189return;1419014191CXXRecordDecl *ClassDecl = Destructor->getParent();14192assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");1419314194SynthesizedFunctionScope Scope(*this, Destructor);1419514196// The exception specification is needed because we are defining the14197// function.14198ResolveExceptionSpec(CurrentLocation,14199Destructor->getType()->castAs<FunctionProtoType>());14200MarkVTableUsed(CurrentLocation, ClassDecl);1420114202// Add a context note for diagnostics produced after this point.14203Scope.addContextNote(CurrentLocation);1420414205MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),14206Destructor->getParent());1420714208if (CheckDestructor(Destructor)) {14209Destructor->setInvalidDecl();14210return;14211}1421214213SourceLocation Loc = Destructor->getEndLoc().isValid()14214? Destructor->getEndLoc()14215: Destructor->getLocation();14216Destructor->setBody(new (Context) CompoundStmt(Loc));14217Destructor->markUsed(Context);1421814219if (ASTMutationListener *L = getASTMutationListener()) {14220L->CompletedImplicitDefinition(Destructor);14221}14222}1422314224void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,14225CXXDestructorDecl *Destructor) {14226if (Destructor->isInvalidDecl())14227return;1422814229CXXRecordDecl *ClassDecl = Destructor->getParent();14230assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&14231"implicit complete dtors unneeded outside MS ABI");14232assert(ClassDecl->getNumVBases() > 0 &&14233"complete dtor only exists for classes with vbases");1423414235SynthesizedFunctionScope Scope(*this, Destructor);1423614237// Add a context note for diagnostics produced after this point.14238Scope.addContextNote(CurrentLocation);1423914240MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);14241}1424214243void Sema::ActOnFinishCXXMemberDecls() {14244// If the context is an invalid C++ class, just suppress these checks.14245if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {14246if (Record->isInvalidDecl()) {14247DelayedOverridingExceptionSpecChecks.clear();14248DelayedEquivalentExceptionSpecChecks.clear();14249return;14250}14251checkForMultipleExportedDefaultConstructors(*this, Record);14252}14253}1425414255void Sema::ActOnFinishCXXNonNestedClass() {14256referenceDLLExportedClassMethods();1425714258if (!DelayedDllExportMemberFunctions.empty()) {14259SmallVector<CXXMethodDecl*, 4> WorkList;14260std::swap(DelayedDllExportMemberFunctions, WorkList);14261for (CXXMethodDecl *M : WorkList) {14262DefineDefaultedFunction(*this, M, M->getLocation());1426314264// Pass the method to the consumer to get emitted. This is not necessary14265// for explicit instantiation definitions, as they will get emitted14266// anyway.14267if (M->getParent()->getTemplateSpecializationKind() !=14268TSK_ExplicitInstantiationDefinition)14269ActOnFinishInlineFunctionDef(M);14270}14271}14272}1427314274void Sema::referenceDLLExportedClassMethods() {14275if (!DelayedDllExportClasses.empty()) {14276// Calling ReferenceDllExportedMembers might cause the current function to14277// be called again, so use a local copy of DelayedDllExportClasses.14278SmallVector<CXXRecordDecl *, 4> WorkList;14279std::swap(DelayedDllExportClasses, WorkList);14280for (CXXRecordDecl *Class : WorkList)14281ReferenceDllExportedMembers(*this, Class);14282}14283}1428414285void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {14286assert(getLangOpts().CPlusPlus11 &&14287"adjusting dtor exception specs was introduced in c++11");1428814289if (Destructor->isDependentContext())14290return;1429114292// C++11 [class.dtor]p3:14293// A declaration of a destructor that does not have an exception-14294// specification is implicitly considered to have the same exception-14295// specification as an implicit declaration.14296const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();14297if (DtorType->hasExceptionSpec())14298return;1429914300// Replace the destructor's type, building off the existing one. Fortunately,14301// the only thing of interest in the destructor type is its extended info.14302// The return and arguments are fixed.14303FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();14304EPI.ExceptionSpec.Type = EST_Unevaluated;14305EPI.ExceptionSpec.SourceDecl = Destructor;14306Destructor->setType(14307Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));1430814309// FIXME: If the destructor has a body that could throw, and the newly created14310// spec doesn't allow exceptions, we should emit a warning, because this14311// change in behavior can break conforming C++03 programs at runtime.14312// However, we don't have a body or an exception specification yet, so it14313// needs to be done somewhere else.14314}1431514316namespace {14317/// An abstract base class for all helper classes used in building the14318// copy/move operators. These classes serve as factory functions and help us14319// avoid using the same Expr* in the AST twice.14320class ExprBuilder {14321ExprBuilder(const ExprBuilder&) = delete;14322ExprBuilder &operator=(const ExprBuilder&) = delete;1432314324protected:14325static Expr *assertNotNull(Expr *E) {14326assert(E && "Expression construction must not fail.");14327return E;14328}1432914330public:14331ExprBuilder() {}14332virtual ~ExprBuilder() {}1433314334virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;14335};1433614337class RefBuilder: public ExprBuilder {14338VarDecl *Var;14339QualType VarType;1434014341public:14342Expr *build(Sema &S, SourceLocation Loc) const override {14343return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));14344}1434514346RefBuilder(VarDecl *Var, QualType VarType)14347: Var(Var), VarType(VarType) {}14348};1434914350class ThisBuilder: public ExprBuilder {14351public:14352Expr *build(Sema &S, SourceLocation Loc) const override {14353return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());14354}14355};1435614357class CastBuilder: public ExprBuilder {14358const ExprBuilder &Builder;14359QualType Type;14360ExprValueKind Kind;14361const CXXCastPath &Path;1436214363public:14364Expr *build(Sema &S, SourceLocation Loc) const override {14365return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,14366CK_UncheckedDerivedToBase, Kind,14367&Path).get());14368}1436914370CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,14371const CXXCastPath &Path)14372: Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}14373};1437414375class DerefBuilder: public ExprBuilder {14376const ExprBuilder &Builder;1437714378public:14379Expr *build(Sema &S, SourceLocation Loc) const override {14380return assertNotNull(14381S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());14382}1438314384DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14385};1438614387class MemberBuilder: public ExprBuilder {14388const ExprBuilder &Builder;14389QualType Type;14390CXXScopeSpec SS;14391bool IsArrow;14392LookupResult &MemberLookup;1439314394public:14395Expr *build(Sema &S, SourceLocation Loc) const override {14396return assertNotNull(S.BuildMemberReferenceExpr(14397Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),14398nullptr, MemberLookup, nullptr, nullptr).get());14399}1440014401MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,14402LookupResult &MemberLookup)14403: Builder(Builder), Type(Type), IsArrow(IsArrow),14404MemberLookup(MemberLookup) {}14405};1440614407class MoveCastBuilder: public ExprBuilder {14408const ExprBuilder &Builder;1440914410public:14411Expr *build(Sema &S, SourceLocation Loc) const override {14412return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));14413}1441414415MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14416};1441714418class LvalueConvBuilder: public ExprBuilder {14419const ExprBuilder &Builder;1442014421public:14422Expr *build(Sema &S, SourceLocation Loc) const override {14423return assertNotNull(14424S.DefaultLvalueConversion(Builder.build(S, Loc)).get());14425}1442614427LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14428};1442914430class SubscriptBuilder: public ExprBuilder {14431const ExprBuilder &Base;14432const ExprBuilder &Index;1443314434public:14435Expr *build(Sema &S, SourceLocation Loc) const override {14436return assertNotNull(S.CreateBuiltinArraySubscriptExpr(14437Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());14438}1443914440SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)14441: Base(Base), Index(Index) {}14442};1444314444} // end anonymous namespace1444514446/// When generating a defaulted copy or move assignment operator, if a field14447/// should be copied with __builtin_memcpy rather than via explicit assignments,14448/// do so. This optimization only applies for arrays of scalars, and for arrays14449/// of class type where the selected copy/move-assignment operator is trivial.14450static StmtResult14451buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,14452const ExprBuilder &ToB, const ExprBuilder &FromB) {14453// Compute the size of the memory buffer to be copied.14454QualType SizeType = S.Context.getSizeType();14455llvm::APInt Size(S.Context.getTypeSize(SizeType),14456S.Context.getTypeSizeInChars(T).getQuantity());1445714458// Take the address of the field references for "from" and "to". We14459// directly construct UnaryOperators here because semantic analysis14460// does not permit us to take the address of an xvalue.14461Expr *From = FromB.build(S, Loc);14462From = UnaryOperator::Create(14463S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),14464VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());14465Expr *To = ToB.build(S, Loc);14466To = UnaryOperator::Create(14467S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),14468VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());1446914470const Type *E = T->getBaseElementTypeUnsafe();14471bool NeedsCollectableMemCpy =14472E->isRecordType() &&14473E->castAs<RecordType>()->getDecl()->hasObjectMember();1447414475// Create a reference to the __builtin_objc_memmove_collectable function14476StringRef MemCpyName = NeedsCollectableMemCpy ?14477"__builtin_objc_memmove_collectable" :14478"__builtin_memcpy";14479LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,14480Sema::LookupOrdinaryName);14481S.LookupName(R, S.TUScope, true);1448214483FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();14484if (!MemCpy)14485// Something went horribly wrong earlier, and we will have complained14486// about it.14487return StmtError();1448814489ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,14490VK_PRValue, Loc, nullptr);14491assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");1449214493Expr *CallArgs[] = {14494To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)14495};14496ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),14497Loc, CallArgs, Loc);1449814499assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");14500return Call.getAs<Stmt>();14501}1450214503/// Builds a statement that copies/moves the given entity from \p From to14504/// \c To.14505///14506/// This routine is used to copy/move the members of a class with an14507/// implicitly-declared copy/move assignment operator. When the entities being14508/// copied are arrays, this routine builds for loops to copy them.14509///14510/// \param S The Sema object used for type-checking.14511///14512/// \param Loc The location where the implicit copy/move is being generated.14513///14514/// \param T The type of the expressions being copied/moved. Both expressions14515/// must have this type.14516///14517/// \param To The expression we are copying/moving to.14518///14519/// \param From The expression we are copying/moving from.14520///14521/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.14522/// Otherwise, it's a non-static member subobject.14523///14524/// \param Copying Whether we're copying or moving.14525///14526/// \param Depth Internal parameter recording the depth of the recursion.14527///14528/// \returns A statement or a loop that copies the expressions, or StmtResult(0)14529/// if a memcpy should be used instead.14530static StmtResult14531buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,14532const ExprBuilder &To, const ExprBuilder &From,14533bool CopyingBaseSubobject, bool Copying,14534unsigned Depth = 0) {14535// C++11 [class.copy]p28:14536// Each subobject is assigned in the manner appropriate to its type:14537//14538// - if the subobject is of class type, as if by a call to operator= with14539// the subobject as the object expression and the corresponding14540// subobject of x as a single function argument (as if by explicit14541// qualification; that is, ignoring any possible virtual overriding14542// functions in more derived classes);14543//14544// C++03 [class.copy]p13:14545// - if the subobject is of class type, the copy assignment operator for14546// the class is used (as if by explicit qualification; that is,14547// ignoring any possible virtual overriding functions in more derived14548// classes);14549if (const RecordType *RecordTy = T->getAs<RecordType>()) {14550CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());1455114552// Look for operator=.14553DeclarationName Name14554= S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);14555LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);14556S.LookupQualifiedName(OpLookup, ClassDecl, false);1455714558// Prior to C++11, filter out any result that isn't a copy/move-assignment14559// operator.14560if (!S.getLangOpts().CPlusPlus11) {14561LookupResult::Filter F = OpLookup.makeFilter();14562while (F.hasNext()) {14563NamedDecl *D = F.next();14564if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))14565if (Method->isCopyAssignmentOperator() ||14566(!Copying && Method->isMoveAssignmentOperator()))14567continue;1456814569F.erase();14570}14571F.done();14572}1457314574// Suppress the protected check (C++ [class.protected]) for each of the14575// assignment operators we found. This strange dance is required when14576// we're assigning via a base classes's copy-assignment operator. To14577// ensure that we're getting the right base class subobject (without14578// ambiguities), we need to cast "this" to that subobject type; to14579// ensure that we don't go through the virtual call mechanism, we need14580// to qualify the operator= name with the base class (see below). However,14581// this means that if the base class has a protected copy assignment14582// operator, the protected member access check will fail. So, we14583// rewrite "protected" access to "public" access in this case, since we14584// know by construction that we're calling from a derived class.14585if (CopyingBaseSubobject) {14586for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();14587L != LEnd; ++L) {14588if (L.getAccess() == AS_protected)14589L.setAccess(AS_public);14590}14591}1459214593// Create the nested-name-specifier that will be used to qualify the14594// reference to operator=; this is required to suppress the virtual14595// call mechanism.14596CXXScopeSpec SS;14597const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());14598SS.MakeTrivial(S.Context,14599NestedNameSpecifier::Create(S.Context, nullptr, false,14600CanonicalT),14601Loc);1460214603// Create the reference to operator=.14604ExprResult OpEqualRef14605= S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,14606SS, /*TemplateKWLoc=*/SourceLocation(),14607/*FirstQualifierInScope=*/nullptr,14608OpLookup,14609/*TemplateArgs=*/nullptr, /*S*/nullptr,14610/*SuppressQualifierCheck=*/true);14611if (OpEqualRef.isInvalid())14612return StmtError();1461314614// Build the call to the assignment operator.1461514616Expr *FromInst = From.build(S, Loc);14617ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,14618OpEqualRef.getAs<Expr>(),14619Loc, FromInst, Loc);14620if (Call.isInvalid())14621return StmtError();1462214623// If we built a call to a trivial 'operator=' while copying an array,14624// bail out. We'll replace the whole shebang with a memcpy.14625CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());14626if (CE && CE->getMethodDecl()->isTrivial() && Depth)14627return StmtResult((Stmt*)nullptr);1462814629// Convert to an expression-statement, and clean up any produced14630// temporaries.14631return S.ActOnExprStmt(Call);14632}1463314634// - if the subobject is of scalar type, the built-in assignment14635// operator is used.14636const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);14637if (!ArrayTy) {14638ExprResult Assignment = S.CreateBuiltinBinOp(14639Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));14640if (Assignment.isInvalid())14641return StmtError();14642return S.ActOnExprStmt(Assignment);14643}1464414645// - if the subobject is an array, each element is assigned, in the14646// manner appropriate to the element type;1464714648// Construct a loop over the array bounds, e.g.,14649//14650// for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)14651//14652// that will copy each of the array elements.14653QualType SizeType = S.Context.getSizeType();1465414655// Create the iteration variable.14656IdentifierInfo *IterationVarName = nullptr;14657{14658SmallString<8> Str;14659llvm::raw_svector_ostream OS(Str);14660OS << "__i" << Depth;14661IterationVarName = &S.Context.Idents.get(OS.str());14662}14663VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,14664IterationVarName, SizeType,14665S.Context.getTrivialTypeSourceInfo(SizeType, Loc),14666SC_None);1466714668// Initialize the iteration variable to zero.14669llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);14670IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));1467114672// Creates a reference to the iteration variable.14673RefBuilder IterationVarRef(IterationVar, SizeType);14674LvalueConvBuilder IterationVarRefRVal(IterationVarRef);1467514676// Create the DeclStmt that holds the iteration variable.14677Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);1467814679// Subscript the "from" and "to" expressions with the iteration variable.14680SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);14681MoveCastBuilder FromIndexMove(FromIndexCopy);14682const ExprBuilder *FromIndex;14683if (Copying)14684FromIndex = &FromIndexCopy;14685else14686FromIndex = &FromIndexMove;1468714688SubscriptBuilder ToIndex(To, IterationVarRefRVal);1468914690// Build the copy/move for an individual element of the array.14691StmtResult Copy =14692buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),14693ToIndex, *FromIndex, CopyingBaseSubobject,14694Copying, Depth + 1);14695// Bail out if copying fails or if we determined that we should use memcpy.14696if (Copy.isInvalid() || !Copy.get())14697return Copy;1469814699// Create the comparison against the array bound.14700llvm::APInt Upper14701= ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));14702Expr *Comparison = BinaryOperator::Create(14703S.Context, IterationVarRefRVal.build(S, Loc),14704IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,14705S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,14706S.CurFPFeatureOverrides());1470714708// Create the pre-increment of the iteration variable. We can determine14709// whether the increment will overflow based on the value of the array14710// bound.14711Expr *Increment = UnaryOperator::Create(14712S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,14713OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());1471414715// Construct the loop that copies all elements of this array.14716return S.ActOnForStmt(14717Loc, Loc, InitStmt,14718S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),14719S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());14720}1472114722static StmtResult14723buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,14724const ExprBuilder &To, const ExprBuilder &From,14725bool CopyingBaseSubobject, bool Copying) {14726// Maybe we should use a memcpy?14727if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&14728T.isTriviallyCopyableType(S.Context))14729return buildMemcpyForAssignmentOp(S, Loc, T, To, From);1473014731StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,14732CopyingBaseSubobject,14733Copying, 0));1473414735// If we ended up picking a trivial assignment operator for an array of a14736// non-trivially-copyable class type, just emit a memcpy.14737if (!Result.isInvalid() && !Result.get())14738return buildMemcpyForAssignmentOp(S, Loc, T, To, From);1473914740return Result;14741}1474214743CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {14744// Note: The following rules are largely analoguous to the copy14745// constructor rules. Note that virtual bases are not taken into account14746// for determining the argument type of the operator. Note also that14747// operators taking an object instead of a reference are allowed.14748assert(ClassDecl->needsImplicitCopyAssignment());1474914750DeclaringSpecialMember DSM(*this, ClassDecl,14751CXXSpecialMemberKind::CopyAssignment);14752if (DSM.isAlreadyBeingDeclared())14753return nullptr;1475414755QualType ArgType = Context.getTypeDeclType(ClassDecl);14756ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,14757ArgType, nullptr);14758LangAS AS = getDefaultCXXMethodAddrSpace();14759if (AS != LangAS::Default)14760ArgType = Context.getAddrSpaceQualType(ArgType, AS);14761QualType RetType = Context.getLValueReferenceType(ArgType);14762bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();14763if (Const)14764ArgType = ArgType.withConst();1476514766ArgType = Context.getLValueReferenceType(ArgType);1476714768bool Constexpr = defaultedSpecialMemberIsConstexpr(14769*this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);1477014771// An implicitly-declared copy assignment operator is an inline public14772// member of its class.14773DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);14774SourceLocation ClassLoc = ClassDecl->getLocation();14775DeclarationNameInfo NameInfo(Name, ClassLoc);14776CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(14777Context, ClassDecl, ClassLoc, NameInfo, QualType(),14778/*TInfo=*/nullptr, /*StorageClass=*/SC_None,14779getCurFPFeatures().isFPConstrained(),14780/*isInline=*/true,14781Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,14782SourceLocation());14783CopyAssignment->setAccess(AS_public);14784CopyAssignment->setDefaulted();14785CopyAssignment->setImplicit();1478614787setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);1478814789if (getLangOpts().CUDA)14790CUDA().inferTargetForImplicitSpecialMember(14791ClassDecl, CXXSpecialMemberKind::CopyAssignment, CopyAssignment,14792/* ConstRHS */ Const,14793/* Diagnose */ false);1479414795// Add the parameter to the operator.14796ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,14797ClassLoc, ClassLoc,14798/*Id=*/nullptr, ArgType,14799/*TInfo=*/nullptr, SC_None,14800nullptr);14801CopyAssignment->setParams(FromParam);1480214803CopyAssignment->setTrivial(14804ClassDecl->needsOverloadResolutionForCopyAssignment()14805? SpecialMemberIsTrivial(CopyAssignment,14806CXXSpecialMemberKind::CopyAssignment)14807: ClassDecl->hasTrivialCopyAssignment());1480814809// Note that we have added this copy-assignment operator.14810++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;1481114812Scope *S = getScopeForContext(ClassDecl);14813CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);1481414815if (ShouldDeleteSpecialMember(CopyAssignment,14816CXXSpecialMemberKind::CopyAssignment)) {14817ClassDecl->setImplicitCopyAssignmentIsDeleted();14818SetDeclDeleted(CopyAssignment, ClassLoc);14819}1482014821if (S)14822PushOnScopeChains(CopyAssignment, S, false);14823ClassDecl->addDecl(CopyAssignment);1482414825return CopyAssignment;14826}1482714828/// Diagnose an implicit copy operation for a class which is odr-used, but14829/// which is deprecated because the class has a user-declared copy constructor,14830/// copy assignment operator, or destructor.14831static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {14832assert(CopyOp->isImplicit());1483314834CXXRecordDecl *RD = CopyOp->getParent();14835CXXMethodDecl *UserDeclaredOperation = nullptr;1483614837if (RD->hasUserDeclaredDestructor()) {14838UserDeclaredOperation = RD->getDestructor();14839} else if (!isa<CXXConstructorDecl>(CopyOp) &&14840RD->hasUserDeclaredCopyConstructor()) {14841// Find any user-declared copy constructor.14842for (auto *I : RD->ctors()) {14843if (I->isCopyConstructor()) {14844UserDeclaredOperation = I;14845break;14846}14847}14848assert(UserDeclaredOperation);14849} else if (isa<CXXConstructorDecl>(CopyOp) &&14850RD->hasUserDeclaredCopyAssignment()) {14851// Find any user-declared move assignment operator.14852for (auto *I : RD->methods()) {14853if (I->isCopyAssignmentOperator()) {14854UserDeclaredOperation = I;14855break;14856}14857}14858assert(UserDeclaredOperation);14859}1486014861if (UserDeclaredOperation) {14862bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();14863bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);14864bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);14865unsigned DiagID =14866(UDOIsUserProvided && UDOIsDestructor)14867? diag::warn_deprecated_copy_with_user_provided_dtor14868: (UDOIsUserProvided && !UDOIsDestructor)14869? diag::warn_deprecated_copy_with_user_provided_copy14870: (!UDOIsUserProvided && UDOIsDestructor)14871? diag::warn_deprecated_copy_with_dtor14872: diag::warn_deprecated_copy;14873S.Diag(UserDeclaredOperation->getLocation(), DiagID)14874<< RD << IsCopyAssignment;14875}14876}1487714878void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,14879CXXMethodDecl *CopyAssignOperator) {14880assert((CopyAssignOperator->isDefaulted() &&14881CopyAssignOperator->isOverloadedOperator() &&14882CopyAssignOperator->getOverloadedOperator() == OO_Equal &&14883!CopyAssignOperator->doesThisDeclarationHaveABody() &&14884!CopyAssignOperator->isDeleted()) &&14885"DefineImplicitCopyAssignment called for wrong function");14886if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())14887return;1488814889CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();14890if (ClassDecl->isInvalidDecl()) {14891CopyAssignOperator->setInvalidDecl();14892return;14893}1489414895SynthesizedFunctionScope Scope(*this, CopyAssignOperator);1489614897// The exception specification is needed because we are defining the14898// function.14899ResolveExceptionSpec(CurrentLocation,14900CopyAssignOperator->getType()->castAs<FunctionProtoType>());1490114902// Add a context note for diagnostics produced after this point.14903Scope.addContextNote(CurrentLocation);1490414905// C++11 [class.copy]p18:14906// The [definition of an implicitly declared copy assignment operator] is14907// deprecated if the class has a user-declared copy constructor or a14908// user-declared destructor.14909if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())14910diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);1491114912// C++0x [class.copy]p30:14913// The implicitly-defined or explicitly-defaulted copy assignment operator14914// for a non-union class X performs memberwise copy assignment of its14915// subobjects. The direct base classes of X are assigned first, in the14916// order of their declaration in the base-specifier-list, and then the14917// immediate non-static data members of X are assigned, in the order in14918// which they were declared in the class definition.1491914920// The statements that form the synthesized function body.14921SmallVector<Stmt*, 8> Statements;1492214923// The parameter for the "other" object, which we are copying from.14924ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);14925Qualifiers OtherQuals = Other->getType().getQualifiers();14926QualType OtherRefType = Other->getType();14927if (OtherRefType->isLValueReferenceType()) {14928OtherRefType = OtherRefType->getPointeeType();14929OtherQuals = OtherRefType.getQualifiers();14930}1493114932// Our location for everything implicitly-generated.14933SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()14934? CopyAssignOperator->getEndLoc()14935: CopyAssignOperator->getLocation();1493614937// Builds a DeclRefExpr for the "other" object.14938RefBuilder OtherRef(Other, OtherRefType);1493914940// Builds the function object parameter.14941std::optional<ThisBuilder> This;14942std::optional<DerefBuilder> DerefThis;14943std::optional<RefBuilder> ExplicitObject;14944bool IsArrow = false;14945QualType ObjectType;14946if (CopyAssignOperator->isExplicitObjectMemberFunction()) {14947ObjectType = CopyAssignOperator->getParamDecl(0)->getType();14948if (ObjectType->isReferenceType())14949ObjectType = ObjectType->getPointeeType();14950ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);14951} else {14952ObjectType = getCurrentThisType();14953This.emplace();14954DerefThis.emplace(*This);14955IsArrow = !LangOpts.HLSL;14956}14957ExprBuilder &ObjectParameter =14958ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)14959: static_cast<ExprBuilder &>(*This);1496014961// Assign base classes.14962bool Invalid = false;14963for (auto &Base : ClassDecl->bases()) {14964// Form the assignment:14965// static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));14966QualType BaseType = Base.getType().getUnqualifiedType();14967if (!BaseType->isRecordType()) {14968Invalid = true;14969continue;14970}1497114972CXXCastPath BasePath;14973BasePath.push_back(&Base);1497414975// Construct the "from" expression, which is an implicit cast to the14976// appropriately-qualified base type.14977CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),14978VK_LValue, BasePath);1497914980// Dereference "this".14981CastBuilder To(14982ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)14983: static_cast<ExprBuilder &>(*DerefThis),14984Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),14985VK_LValue, BasePath);1498614987// Build the copy.14988StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,14989To, From,14990/*CopyingBaseSubobject=*/true,14991/*Copying=*/true);14992if (Copy.isInvalid()) {14993CopyAssignOperator->setInvalidDecl();14994return;14995}1499614997// Success! Record the copy.14998Statements.push_back(Copy.getAs<Expr>());14999}1500015001// Assign non-static members.15002for (auto *Field : ClassDecl->fields()) {15003// FIXME: We should form some kind of AST representation for the implied15004// memcpy in a union copy operation.15005if (Field->isUnnamedBitField() || Field->getParent()->isUnion())15006continue;1500715008if (Field->isInvalidDecl()) {15009Invalid = true;15010continue;15011}1501215013// Check for members of reference type; we can't copy those.15014if (Field->getType()->isReferenceType()) {15015Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15016<< Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();15017Diag(Field->getLocation(), diag::note_declared_at);15018Invalid = true;15019continue;15020}1502115022// Check for members of const-qualified, non-class type.15023QualType BaseType = Context.getBaseElementType(Field->getType());15024if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {15025Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15026<< Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();15027Diag(Field->getLocation(), diag::note_declared_at);15028Invalid = true;15029continue;15030}1503115032// Suppress assigning zero-width bitfields.15033if (Field->isZeroLengthBitField(Context))15034continue;1503515036QualType FieldType = Field->getType().getNonReferenceType();15037if (FieldType->isIncompleteArrayType()) {15038assert(ClassDecl->hasFlexibleArrayMember() &&15039"Incomplete array type is not valid");15040continue;15041}1504215043// Build references to the field in the object we're copying from and to.15044CXXScopeSpec SS; // Intentionally empty15045LookupResult MemberLookup(*this, Field->getDeclName(), Loc,15046LookupMemberName);15047MemberLookup.addDecl(Field);15048MemberLookup.resolveKind();1504915050MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);15051MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);15052// Build the copy of this field.15053StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,15054To, From,15055/*CopyingBaseSubobject=*/false,15056/*Copying=*/true);15057if (Copy.isInvalid()) {15058CopyAssignOperator->setInvalidDecl();15059return;15060}1506115062// Success! Record the copy.15063Statements.push_back(Copy.getAs<Stmt>());15064}1506515066if (!Invalid) {15067// Add a "return *this;"15068Expr *ThisExpr =15069(ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15070: LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)15071: static_cast<ExprBuilder &>(*DerefThis))15072.build(*this, Loc);15073StmtResult Return = BuildReturnStmt(Loc, ThisExpr);15074if (Return.isInvalid())15075Invalid = true;15076else15077Statements.push_back(Return.getAs<Stmt>());15078}1507915080if (Invalid) {15081CopyAssignOperator->setInvalidDecl();15082return;15083}1508415085StmtResult Body;15086{15087CompoundScopeRAII CompoundScope(*this);15088Body = ActOnCompoundStmt(Loc, Loc, Statements,15089/*isStmtExpr=*/false);15090assert(!Body.isInvalid() && "Compound statement creation cannot fail");15091}15092CopyAssignOperator->setBody(Body.getAs<Stmt>());15093CopyAssignOperator->markUsed(Context);1509415095if (ASTMutationListener *L = getASTMutationListener()) {15096L->CompletedImplicitDefinition(CopyAssignOperator);15097}15098}1509915100CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {15101assert(ClassDecl->needsImplicitMoveAssignment());1510215103DeclaringSpecialMember DSM(*this, ClassDecl,15104CXXSpecialMemberKind::MoveAssignment);15105if (DSM.isAlreadyBeingDeclared())15106return nullptr;1510715108// Note: The following rules are largely analoguous to the move15109// constructor rules.1511015111QualType ArgType = Context.getTypeDeclType(ClassDecl);15112ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,15113ArgType, nullptr);15114LangAS AS = getDefaultCXXMethodAddrSpace();15115if (AS != LangAS::Default)15116ArgType = Context.getAddrSpaceQualType(ArgType, AS);15117QualType RetType = Context.getLValueReferenceType(ArgType);15118ArgType = Context.getRValueReferenceType(ArgType);1511915120bool Constexpr = defaultedSpecialMemberIsConstexpr(15121*this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);1512215123// An implicitly-declared move assignment operator is an inline public15124// member of its class.15125DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);15126SourceLocation ClassLoc = ClassDecl->getLocation();15127DeclarationNameInfo NameInfo(Name, ClassLoc);15128CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(15129Context, ClassDecl, ClassLoc, NameInfo, QualType(),15130/*TInfo=*/nullptr, /*StorageClass=*/SC_None,15131getCurFPFeatures().isFPConstrained(),15132/*isInline=*/true,15133Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,15134SourceLocation());15135MoveAssignment->setAccess(AS_public);15136MoveAssignment->setDefaulted();15137MoveAssignment->setImplicit();1513815139setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);1514015141if (getLangOpts().CUDA)15142CUDA().inferTargetForImplicitSpecialMember(15143ClassDecl, CXXSpecialMemberKind::MoveAssignment, MoveAssignment,15144/* ConstRHS */ false,15145/* Diagnose */ false);1514615147// Add the parameter to the operator.15148ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,15149ClassLoc, ClassLoc,15150/*Id=*/nullptr, ArgType,15151/*TInfo=*/nullptr, SC_None,15152nullptr);15153MoveAssignment->setParams(FromParam);1515415155MoveAssignment->setTrivial(15156ClassDecl->needsOverloadResolutionForMoveAssignment()15157? SpecialMemberIsTrivial(MoveAssignment,15158CXXSpecialMemberKind::MoveAssignment)15159: ClassDecl->hasTrivialMoveAssignment());1516015161// Note that we have added this copy-assignment operator.15162++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;1516315164Scope *S = getScopeForContext(ClassDecl);15165CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);1516615167if (ShouldDeleteSpecialMember(MoveAssignment,15168CXXSpecialMemberKind::MoveAssignment)) {15169ClassDecl->setImplicitMoveAssignmentIsDeleted();15170SetDeclDeleted(MoveAssignment, ClassLoc);15171}1517215173if (S)15174PushOnScopeChains(MoveAssignment, S, false);15175ClassDecl->addDecl(MoveAssignment);1517615177return MoveAssignment;15178}1517915180/// Check if we're implicitly defining a move assignment operator for a class15181/// with virtual bases. Such a move assignment might move-assign the virtual15182/// base multiple times.15183static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,15184SourceLocation CurrentLocation) {15185assert(!Class->isDependentContext() && "should not define dependent move");1518615187// Only a virtual base could get implicitly move-assigned multiple times.15188// Only a non-trivial move assignment can observe this. We only want to15189// diagnose if we implicitly define an assignment operator that assigns15190// two base classes, both of which move-assign the same virtual base.15191if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||15192Class->getNumBases() < 2)15193return;1519415195llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;15196typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;15197VBaseMap VBases;1519815199for (auto &BI : Class->bases()) {15200Worklist.push_back(&BI);15201while (!Worklist.empty()) {15202CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();15203CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();1520415205// If the base has no non-trivial move assignment operators,15206// we don't care about moves from it.15207if (!Base->hasNonTrivialMoveAssignment())15208continue;1520915210// If there's nothing virtual here, skip it.15211if (!BaseSpec->isVirtual() && !Base->getNumVBases())15212continue;1521315214// If we're not actually going to call a move assignment for this base,15215// or the selected move assignment is trivial, skip it.15216Sema::SpecialMemberOverloadResult SMOR =15217S.LookupSpecialMember(Base, CXXSpecialMemberKind::MoveAssignment,15218/*ConstArg*/ false, /*VolatileArg*/ false,15219/*RValueThis*/ true, /*ConstThis*/ false,15220/*VolatileThis*/ false);15221if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||15222!SMOR.getMethod()->isMoveAssignmentOperator())15223continue;1522415225if (BaseSpec->isVirtual()) {15226// We're going to move-assign this virtual base, and its move15227// assignment operator is not trivial. If this can happen for15228// multiple distinct direct bases of Class, diagnose it. (If it15229// only happens in one base, we'll diagnose it when synthesizing15230// that base class's move assignment operator.)15231CXXBaseSpecifier *&Existing =15232VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))15233.first->second;15234if (Existing && Existing != &BI) {15235S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)15236<< Class << Base;15237S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)15238<< (Base->getCanonicalDecl() ==15239Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())15240<< Base << Existing->getType() << Existing->getSourceRange();15241S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)15242<< (Base->getCanonicalDecl() ==15243BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())15244<< Base << BI.getType() << BaseSpec->getSourceRange();1524515246// Only diagnose each vbase once.15247Existing = nullptr;15248}15249} else {15250// Only walk over bases that have defaulted move assignment operators.15251// We assume that any user-provided move assignment operator handles15252// the multiple-moves-of-vbase case itself somehow.15253if (!SMOR.getMethod()->isDefaulted())15254continue;1525515256// We're going to move the base classes of Base. Add them to the list.15257llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));15258}15259}15260}15261}1526215263void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,15264CXXMethodDecl *MoveAssignOperator) {15265assert((MoveAssignOperator->isDefaulted() &&15266MoveAssignOperator->isOverloadedOperator() &&15267MoveAssignOperator->getOverloadedOperator() == OO_Equal &&15268!MoveAssignOperator->doesThisDeclarationHaveABody() &&15269!MoveAssignOperator->isDeleted()) &&15270"DefineImplicitMoveAssignment called for wrong function");15271if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())15272return;1527315274CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();15275if (ClassDecl->isInvalidDecl()) {15276MoveAssignOperator->setInvalidDecl();15277return;15278}1527915280// C++0x [class.copy]p28:15281// The implicitly-defined or move assignment operator for a non-union class15282// X performs memberwise move assignment of its subobjects. The direct base15283// classes of X are assigned first, in the order of their declaration in the15284// base-specifier-list, and then the immediate non-static data members of X15285// are assigned, in the order in which they were declared in the class15286// definition.1528715288// Issue a warning if our implicit move assignment operator will move15289// from a virtual base more than once.15290checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);1529115292SynthesizedFunctionScope Scope(*this, MoveAssignOperator);1529315294// The exception specification is needed because we are defining the15295// function.15296ResolveExceptionSpec(CurrentLocation,15297MoveAssignOperator->getType()->castAs<FunctionProtoType>());1529815299// Add a context note for diagnostics produced after this point.15300Scope.addContextNote(CurrentLocation);1530115302// The statements that form the synthesized function body.15303SmallVector<Stmt*, 8> Statements;1530415305// The parameter for the "other" object, which we are move from.15306ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);15307QualType OtherRefType =15308Other->getType()->castAs<RValueReferenceType>()->getPointeeType();1530915310// Our location for everything implicitly-generated.15311SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()15312? MoveAssignOperator->getEndLoc()15313: MoveAssignOperator->getLocation();1531415315// Builds a reference to the "other" object.15316RefBuilder OtherRef(Other, OtherRefType);15317// Cast to rvalue.15318MoveCastBuilder MoveOther(OtherRef);1531915320// Builds the function object parameter.15321std::optional<ThisBuilder> This;15322std::optional<DerefBuilder> DerefThis;15323std::optional<RefBuilder> ExplicitObject;15324QualType ObjectType;15325if (MoveAssignOperator->isExplicitObjectMemberFunction()) {15326ObjectType = MoveAssignOperator->getParamDecl(0)->getType();15327if (ObjectType->isReferenceType())15328ObjectType = ObjectType->getPointeeType();15329ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);15330} else {15331ObjectType = getCurrentThisType();15332This.emplace();15333DerefThis.emplace(*This);15334}15335ExprBuilder &ObjectParameter =15336ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);1533715338// Assign base classes.15339bool Invalid = false;15340for (auto &Base : ClassDecl->bases()) {15341// C++11 [class.copy]p28:15342// It is unspecified whether subobjects representing virtual base classes15343// are assigned more than once by the implicitly-defined copy assignment15344// operator.15345// FIXME: Do not assign to a vbase that will be assigned by some other base15346// class. For a move-assignment, this can result in the vbase being moved15347// multiple times.1534815349// Form the assignment:15350// static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));15351QualType BaseType = Base.getType().getUnqualifiedType();15352if (!BaseType->isRecordType()) {15353Invalid = true;15354continue;15355}1535615357CXXCastPath BasePath;15358BasePath.push_back(&Base);1535915360// Construct the "from" expression, which is an implicit cast to the15361// appropriately-qualified base type.15362CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);1536315364// Implicitly cast "this" to the appropriately-qualified base type.15365// Dereference "this".15366CastBuilder To(15367ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15368: static_cast<ExprBuilder &>(*DerefThis),15369Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),15370VK_LValue, BasePath);1537115372// Build the move.15373StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,15374To, From,15375/*CopyingBaseSubobject=*/true,15376/*Copying=*/false);15377if (Move.isInvalid()) {15378MoveAssignOperator->setInvalidDecl();15379return;15380}1538115382// Success! Record the move.15383Statements.push_back(Move.getAs<Expr>());15384}1538515386// Assign non-static members.15387for (auto *Field : ClassDecl->fields()) {15388// FIXME: We should form some kind of AST representation for the implied15389// memcpy in a union copy operation.15390if (Field->isUnnamedBitField() || Field->getParent()->isUnion())15391continue;1539215393if (Field->isInvalidDecl()) {15394Invalid = true;15395continue;15396}1539715398// Check for members of reference type; we can't move those.15399if (Field->getType()->isReferenceType()) {15400Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15401<< Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();15402Diag(Field->getLocation(), diag::note_declared_at);15403Invalid = true;15404continue;15405}1540615407// Check for members of const-qualified, non-class type.15408QualType BaseType = Context.getBaseElementType(Field->getType());15409if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {15410Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15411<< Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();15412Diag(Field->getLocation(), diag::note_declared_at);15413Invalid = true;15414continue;15415}1541615417// Suppress assigning zero-width bitfields.15418if (Field->isZeroLengthBitField(Context))15419continue;1542015421QualType FieldType = Field->getType().getNonReferenceType();15422if (FieldType->isIncompleteArrayType()) {15423assert(ClassDecl->hasFlexibleArrayMember() &&15424"Incomplete array type is not valid");15425continue;15426}1542715428// Build references to the field in the object we're copying from and to.15429LookupResult MemberLookup(*this, Field->getDeclName(), Loc,15430LookupMemberName);15431MemberLookup.addDecl(Field);15432MemberLookup.resolveKind();15433MemberBuilder From(MoveOther, OtherRefType,15434/*IsArrow=*/false, MemberLookup);15435MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,15436MemberLookup);1543715438assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue15439"Member reference with rvalue base must be rvalue except for reference "15440"members, which aren't allowed for move assignment.");1544115442// Build the move of this field.15443StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,15444To, From,15445/*CopyingBaseSubobject=*/false,15446/*Copying=*/false);15447if (Move.isInvalid()) {15448MoveAssignOperator->setInvalidDecl();15449return;15450}1545115452// Success! Record the copy.15453Statements.push_back(Move.getAs<Stmt>());15454}1545515456if (!Invalid) {15457// Add a "return *this;"15458Expr *ThisExpr =15459(ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15460: static_cast<ExprBuilder &>(*DerefThis))15461.build(*this, Loc);1546215463StmtResult Return = BuildReturnStmt(Loc, ThisExpr);15464if (Return.isInvalid())15465Invalid = true;15466else15467Statements.push_back(Return.getAs<Stmt>());15468}1546915470if (Invalid) {15471MoveAssignOperator->setInvalidDecl();15472return;15473}1547415475StmtResult Body;15476{15477CompoundScopeRAII CompoundScope(*this);15478Body = ActOnCompoundStmt(Loc, Loc, Statements,15479/*isStmtExpr=*/false);15480assert(!Body.isInvalid() && "Compound statement creation cannot fail");15481}15482MoveAssignOperator->setBody(Body.getAs<Stmt>());15483MoveAssignOperator->markUsed(Context);1548415485if (ASTMutationListener *L = getASTMutationListener()) {15486L->CompletedImplicitDefinition(MoveAssignOperator);15487}15488}1548915490CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(15491CXXRecordDecl *ClassDecl) {15492// C++ [class.copy]p4:15493// If the class definition does not explicitly declare a copy15494// constructor, one is declared implicitly.15495assert(ClassDecl->needsImplicitCopyConstructor());1549615497DeclaringSpecialMember DSM(*this, ClassDecl,15498CXXSpecialMemberKind::CopyConstructor);15499if (DSM.isAlreadyBeingDeclared())15500return nullptr;1550115502QualType ClassType = Context.getTypeDeclType(ClassDecl);15503QualType ArgType = ClassType;15504ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,15505ArgType, nullptr);15506bool Const = ClassDecl->implicitCopyConstructorHasConstParam();15507if (Const)15508ArgType = ArgType.withConst();1550915510LangAS AS = getDefaultCXXMethodAddrSpace();15511if (AS != LangAS::Default)15512ArgType = Context.getAddrSpaceQualType(ArgType, AS);1551315514ArgType = Context.getLValueReferenceType(ArgType);1551515516bool Constexpr = defaultedSpecialMemberIsConstexpr(15517*this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);1551815519DeclarationName Name15520= Context.DeclarationNames.getCXXConstructorName(15521Context.getCanonicalType(ClassType));15522SourceLocation ClassLoc = ClassDecl->getLocation();15523DeclarationNameInfo NameInfo(Name, ClassLoc);1552415525// An implicitly-declared copy constructor is an inline public15526// member of its class.15527CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(15528Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,15529ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),15530/*isInline=*/true,15531/*isImplicitlyDeclared=*/true,15532Constexpr ? ConstexprSpecKind::Constexpr15533: ConstexprSpecKind::Unspecified);15534CopyConstructor->setAccess(AS_public);15535CopyConstructor->setDefaulted();1553615537setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);1553815539if (getLangOpts().CUDA)15540CUDA().inferTargetForImplicitSpecialMember(15541ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,15542/* ConstRHS */ Const,15543/* Diagnose */ false);1554415545// During template instantiation of special member functions we need a15546// reliable TypeSourceInfo for the parameter types in order to allow functions15547// to be substituted.15548TypeSourceInfo *TSI = nullptr;15549if (inTemplateInstantiation() && ClassDecl->isLambda())15550TSI = Context.getTrivialTypeSourceInfo(ArgType);1555115552// Add the parameter to the constructor.15553ParmVarDecl *FromParam =15554ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,15555/*IdentifierInfo=*/nullptr, ArgType,15556/*TInfo=*/TSI, SC_None, nullptr);15557CopyConstructor->setParams(FromParam);1555815559CopyConstructor->setTrivial(15560ClassDecl->needsOverloadResolutionForCopyConstructor()15561? SpecialMemberIsTrivial(CopyConstructor,15562CXXSpecialMemberKind::CopyConstructor)15563: ClassDecl->hasTrivialCopyConstructor());1556415565CopyConstructor->setTrivialForCall(15566ClassDecl->hasAttr<TrivialABIAttr>() ||15567(ClassDecl->needsOverloadResolutionForCopyConstructor()15568? SpecialMemberIsTrivial(CopyConstructor,15569CXXSpecialMemberKind::CopyConstructor,15570TAH_ConsiderTrivialABI)15571: ClassDecl->hasTrivialCopyConstructorForCall()));1557215573// Note that we have declared this constructor.15574++getASTContext().NumImplicitCopyConstructorsDeclared;1557515576Scope *S = getScopeForContext(ClassDecl);15577CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);1557815579if (ShouldDeleteSpecialMember(CopyConstructor,15580CXXSpecialMemberKind::CopyConstructor)) {15581ClassDecl->setImplicitCopyConstructorIsDeleted();15582SetDeclDeleted(CopyConstructor, ClassLoc);15583}1558415585if (S)15586PushOnScopeChains(CopyConstructor, S, false);15587ClassDecl->addDecl(CopyConstructor);1558815589return CopyConstructor;15590}1559115592void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,15593CXXConstructorDecl *CopyConstructor) {15594assert((CopyConstructor->isDefaulted() &&15595CopyConstructor->isCopyConstructor() &&15596!CopyConstructor->doesThisDeclarationHaveABody() &&15597!CopyConstructor->isDeleted()) &&15598"DefineImplicitCopyConstructor - call it for implicit copy ctor");15599if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())15600return;1560115602CXXRecordDecl *ClassDecl = CopyConstructor->getParent();15603assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");1560415605SynthesizedFunctionScope Scope(*this, CopyConstructor);1560615607// The exception specification is needed because we are defining the15608// function.15609ResolveExceptionSpec(CurrentLocation,15610CopyConstructor->getType()->castAs<FunctionProtoType>());15611MarkVTableUsed(CurrentLocation, ClassDecl);1561215613// Add a context note for diagnostics produced after this point.15614Scope.addContextNote(CurrentLocation);1561515616// C++11 [class.copy]p7:15617// The [definition of an implicitly declared copy constructor] is15618// deprecated if the class has a user-declared copy assignment operator15619// or a user-declared destructor.15620if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())15621diagnoseDeprecatedCopyOperation(*this, CopyConstructor);1562215623if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {15624CopyConstructor->setInvalidDecl();15625} else {15626SourceLocation Loc = CopyConstructor->getEndLoc().isValid()15627? CopyConstructor->getEndLoc()15628: CopyConstructor->getLocation();15629Sema::CompoundScopeRAII CompoundScope(*this);15630CopyConstructor->setBody(15631ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)15632.getAs<Stmt>());15633CopyConstructor->markUsed(Context);15634}1563515636if (ASTMutationListener *L = getASTMutationListener()) {15637L->CompletedImplicitDefinition(CopyConstructor);15638}15639}1564015641CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(15642CXXRecordDecl *ClassDecl) {15643assert(ClassDecl->needsImplicitMoveConstructor());1564415645DeclaringSpecialMember DSM(*this, ClassDecl,15646CXXSpecialMemberKind::MoveConstructor);15647if (DSM.isAlreadyBeingDeclared())15648return nullptr;1564915650QualType ClassType = Context.getTypeDeclType(ClassDecl);1565115652QualType ArgType = ClassType;15653ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,15654ArgType, nullptr);15655LangAS AS = getDefaultCXXMethodAddrSpace();15656if (AS != LangAS::Default)15657ArgType = Context.getAddrSpaceQualType(ClassType, AS);15658ArgType = Context.getRValueReferenceType(ArgType);1565915660bool Constexpr = defaultedSpecialMemberIsConstexpr(15661*this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);1566215663DeclarationName Name15664= Context.DeclarationNames.getCXXConstructorName(15665Context.getCanonicalType(ClassType));15666SourceLocation ClassLoc = ClassDecl->getLocation();15667DeclarationNameInfo NameInfo(Name, ClassLoc);1566815669// C++11 [class.copy]p11:15670// An implicitly-declared copy/move constructor is an inline public15671// member of its class.15672CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(15673Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,15674ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),15675/*isInline=*/true,15676/*isImplicitlyDeclared=*/true,15677Constexpr ? ConstexprSpecKind::Constexpr15678: ConstexprSpecKind::Unspecified);15679MoveConstructor->setAccess(AS_public);15680MoveConstructor->setDefaulted();1568115682setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);1568315684if (getLangOpts().CUDA)15685CUDA().inferTargetForImplicitSpecialMember(15686ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,15687/* ConstRHS */ false,15688/* Diagnose */ false);1568915690// Add the parameter to the constructor.15691ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,15692ClassLoc, ClassLoc,15693/*IdentifierInfo=*/nullptr,15694ArgType, /*TInfo=*/nullptr,15695SC_None, nullptr);15696MoveConstructor->setParams(FromParam);1569715698MoveConstructor->setTrivial(15699ClassDecl->needsOverloadResolutionForMoveConstructor()15700? SpecialMemberIsTrivial(MoveConstructor,15701CXXSpecialMemberKind::MoveConstructor)15702: ClassDecl->hasTrivialMoveConstructor());1570315704MoveConstructor->setTrivialForCall(15705ClassDecl->hasAttr<TrivialABIAttr>() ||15706(ClassDecl->needsOverloadResolutionForMoveConstructor()15707? SpecialMemberIsTrivial(MoveConstructor,15708CXXSpecialMemberKind::MoveConstructor,15709TAH_ConsiderTrivialABI)15710: ClassDecl->hasTrivialMoveConstructorForCall()));1571115712// Note that we have declared this constructor.15713++getASTContext().NumImplicitMoveConstructorsDeclared;1571415715Scope *S = getScopeForContext(ClassDecl);15716CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);1571715718if (ShouldDeleteSpecialMember(MoveConstructor,15719CXXSpecialMemberKind::MoveConstructor)) {15720ClassDecl->setImplicitMoveConstructorIsDeleted();15721SetDeclDeleted(MoveConstructor, ClassLoc);15722}1572315724if (S)15725PushOnScopeChains(MoveConstructor, S, false);15726ClassDecl->addDecl(MoveConstructor);1572715728return MoveConstructor;15729}1573015731void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,15732CXXConstructorDecl *MoveConstructor) {15733assert((MoveConstructor->isDefaulted() &&15734MoveConstructor->isMoveConstructor() &&15735!MoveConstructor->doesThisDeclarationHaveABody() &&15736!MoveConstructor->isDeleted()) &&15737"DefineImplicitMoveConstructor - call it for implicit move ctor");15738if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())15739return;1574015741CXXRecordDecl *ClassDecl = MoveConstructor->getParent();15742assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");1574315744SynthesizedFunctionScope Scope(*this, MoveConstructor);1574515746// The exception specification is needed because we are defining the15747// function.15748ResolveExceptionSpec(CurrentLocation,15749MoveConstructor->getType()->castAs<FunctionProtoType>());15750MarkVTableUsed(CurrentLocation, ClassDecl);1575115752// Add a context note for diagnostics produced after this point.15753Scope.addContextNote(CurrentLocation);1575415755if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {15756MoveConstructor->setInvalidDecl();15757} else {15758SourceLocation Loc = MoveConstructor->getEndLoc().isValid()15759? MoveConstructor->getEndLoc()15760: MoveConstructor->getLocation();15761Sema::CompoundScopeRAII CompoundScope(*this);15762MoveConstructor->setBody(15763ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)15764.getAs<Stmt>());15765MoveConstructor->markUsed(Context);15766}1576715768if (ASTMutationListener *L = getASTMutationListener()) {15769L->CompletedImplicitDefinition(MoveConstructor);15770}15771}1577215773bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {15774return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);15775}1577615777void Sema::DefineImplicitLambdaToFunctionPointerConversion(15778SourceLocation CurrentLocation,15779CXXConversionDecl *Conv) {15780SynthesizedFunctionScope Scope(*this, Conv);15781assert(!Conv->getReturnType()->isUndeducedType());1578215783QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();15784CallingConv CC =15785ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();1578615787CXXRecordDecl *Lambda = Conv->getParent();15788FunctionDecl *CallOp = Lambda->getLambdaCallOperator();15789FunctionDecl *Invoker =15790CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()15791? CallOp15792: Lambda->getLambdaStaticInvoker(CC);1579315794if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {15795CallOp = InstantiateFunctionDeclaration(15796CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);15797if (!CallOp)15798return;1579915800if (CallOp != Invoker) {15801Invoker = InstantiateFunctionDeclaration(15802Invoker->getDescribedFunctionTemplate(), TemplateArgs,15803CurrentLocation);15804if (!Invoker)15805return;15806}15807}1580815809if (CallOp->isInvalidDecl())15810return;1581115812// Mark the call operator referenced (and add to pending instantiations15813// if necessary).15814// For both the conversion and static-invoker template specializations15815// we construct their body's in this function, so no need to add them15816// to the PendingInstantiations.15817MarkFunctionReferenced(CurrentLocation, CallOp);1581815819if (Invoker != CallOp) {15820// Fill in the __invoke function with a dummy implementation. IR generation15821// will fill in the actual details. Update its type in case it contained15822// an 'auto'.15823Invoker->markUsed(Context);15824Invoker->setReferenced();15825Invoker->setType(Conv->getReturnType()->getPointeeType());15826Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));15827}1582815829// Construct the body of the conversion function { return __invoke; }.15830Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,15831Conv->getLocation());15832assert(FunctionRef && "Can't refer to __invoke function?");15833Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();15834Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),15835Conv->getLocation(), Conv->getLocation()));15836Conv->markUsed(Context);15837Conv->setReferenced();1583815839if (ASTMutationListener *L = getASTMutationListener()) {15840L->CompletedImplicitDefinition(Conv);15841if (Invoker != CallOp)15842L->CompletedImplicitDefinition(Invoker);15843}15844}1584515846void Sema::DefineImplicitLambdaToBlockPointerConversion(15847SourceLocation CurrentLocation, CXXConversionDecl *Conv) {15848assert(!Conv->getParent()->isGenericLambda());1584915850SynthesizedFunctionScope Scope(*this, Conv);1585115852// Copy-initialize the lambda object as needed to capture it.15853Expr *This = ActOnCXXThis(CurrentLocation).get();15854Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();1585515856ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,15857Conv->getLocation(),15858Conv, DerefThis);1585915860// If we're not under ARC, make sure we still get the _Block_copy/autorelease15861// behavior. Note that only the general conversion function does this15862// (since it's unusable otherwise); in the case where we inline the15863// block literal, it has block literal lifetime semantics.15864if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)15865BuildBlock = ImplicitCastExpr::Create(15866Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,15867BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());1586815869if (BuildBlock.isInvalid()) {15870Diag(CurrentLocation, diag::note_lambda_to_block_conv);15871Conv->setInvalidDecl();15872return;15873}1587415875// Create the return statement that returns the block from the conversion15876// function.15877StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());15878if (Return.isInvalid()) {15879Diag(CurrentLocation, diag::note_lambda_to_block_conv);15880Conv->setInvalidDecl();15881return;15882}1588315884// Set the body of the conversion function.15885Stmt *ReturnS = Return.get();15886Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),15887Conv->getLocation(), Conv->getLocation()));15888Conv->markUsed(Context);1588915890// We're done; notify the mutation listener, if any.15891if (ASTMutationListener *L = getASTMutationListener()) {15892L->CompletedImplicitDefinition(Conv);15893}15894}1589515896/// Determine whether the given list arguments contains exactly one15897/// "real" (non-default) argument.15898static bool hasOneRealArgument(MultiExprArg Args) {15899switch (Args.size()) {15900case 0:15901return false;1590215903default:15904if (!Args[1]->isDefaultArgument())15905return false;1590615907[[fallthrough]];15908case 1:15909return !Args[0]->isDefaultArgument();15910}1591115912return false;15913}1591415915ExprResult Sema::BuildCXXConstructExpr(15916SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,15917CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,15918bool HadMultipleCandidates, bool IsListInitialization,15919bool IsStdInitListInitialization, bool RequiresZeroInit,15920CXXConstructionKind ConstructKind, SourceRange ParenRange) {15921bool Elidable = false;1592215923// C++0x [class.copy]p34:15924// When certain criteria are met, an implementation is allowed to15925// omit the copy/move construction of a class object, even if the15926// copy/move constructor and/or destructor for the object have15927// side effects. [...]15928// - when a temporary class object that has not been bound to a15929// reference (12.2) would be copied/moved to a class object15930// with the same cv-unqualified type, the copy/move operation15931// can be omitted by constructing the temporary object15932// directly into the target of the omitted copy/move15933if (ConstructKind == CXXConstructionKind::Complete && Constructor &&15934// FIXME: Converting constructors should also be accepted.15935// But to fix this, the logic that digs down into a CXXConstructExpr15936// to find the source object needs to handle it.15937// Right now it assumes the source object is passed directly as the15938// first argument.15939Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {15940Expr *SubExpr = ExprArgs[0];15941// FIXME: Per above, this is also incorrect if we want to accept15942// converting constructors, as isTemporaryObject will15943// reject temporaries with different type from the15944// CXXRecord itself.15945Elidable = SubExpr->isTemporaryObject(15946Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));15947}1594815949return BuildCXXConstructExpr(ConstructLoc, DeclInitType,15950FoundDecl, Constructor,15951Elidable, ExprArgs, HadMultipleCandidates,15952IsListInitialization,15953IsStdInitListInitialization, RequiresZeroInit,15954ConstructKind, ParenRange);15955}1595615957ExprResult Sema::BuildCXXConstructExpr(15958SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,15959CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,15960bool HadMultipleCandidates, bool IsListInitialization,15961bool IsStdInitListInitialization, bool RequiresZeroInit,15962CXXConstructionKind ConstructKind, SourceRange ParenRange) {15963if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {15964Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);15965// The only way to get here is if we did overload resolution to find the15966// shadow decl, so we don't need to worry about re-checking the trailing15967// requires clause.15968if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))15969return ExprError();15970}1597115972return BuildCXXConstructExpr(15973ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,15974HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,15975RequiresZeroInit, ConstructKind, ParenRange);15976}1597715978/// BuildCXXConstructExpr - Creates a complete call to a constructor,15979/// including handling of its default argument expressions.15980ExprResult Sema::BuildCXXConstructExpr(15981SourceLocation ConstructLoc, QualType DeclInitType,15982CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,15983bool HadMultipleCandidates, bool IsListInitialization,15984bool IsStdInitListInitialization, bool RequiresZeroInit,15985CXXConstructionKind ConstructKind, SourceRange ParenRange) {15986assert(declaresSameEntity(15987Constructor->getParent(),15988DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&15989"given constructor for wrong type");15990MarkFunctionReferenced(ConstructLoc, Constructor);15991if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))15992return ExprError();1599315994return CheckForImmediateInvocation(15995CXXConstructExpr::Create(15996Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,15997HadMultipleCandidates, IsListInitialization,15998IsStdInitListInitialization, RequiresZeroInit,15999static_cast<CXXConstructionKind>(ConstructKind), ParenRange),16000Constructor);16001}1600216003void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {16004if (VD->isInvalidDecl()) return;16005// If initializing the variable failed, don't also diagnose problems with16006// the destructor, they're likely related.16007if (VD->getInit() && VD->getInit()->containsErrors())16008return;1600916010CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());16011if (ClassDecl->isInvalidDecl()) return;16012if (ClassDecl->hasIrrelevantDestructor()) return;16013if (ClassDecl->isDependentContext()) return;1601416015if (VD->isNoDestroy(getASTContext()))16016return;1601716018CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);16019// The result of `LookupDestructor` might be nullptr if the destructor is16020// invalid, in which case it is marked as `IneligibleOrNotSelected` and16021// will not be selected by `CXXRecordDecl::getDestructor()`.16022if (!Destructor)16023return;16024// If this is an array, we'll require the destructor during initialization, so16025// we can skip over this. We still want to emit exit-time destructor warnings16026// though.16027if (!VD->getType()->isArrayType()) {16028MarkFunctionReferenced(VD->getLocation(), Destructor);16029CheckDestructorAccess(VD->getLocation(), Destructor,16030PDiag(diag::err_access_dtor_var)16031<< VD->getDeclName() << VD->getType());16032DiagnoseUseOfDecl(Destructor, VD->getLocation());16033}1603416035if (Destructor->isTrivial()) return;1603616037// If the destructor is constexpr, check whether the variable has constant16038// destruction now.16039if (Destructor->isConstexpr()) {16040bool HasConstantInit = false;16041if (VD->getInit() && !VD->getInit()->isValueDependent())16042HasConstantInit = VD->evaluateValue();16043SmallVector<PartialDiagnosticAt, 8> Notes;16044if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&16045HasConstantInit) {16046Diag(VD->getLocation(),16047diag::err_constexpr_var_requires_const_destruction) << VD;16048for (unsigned I = 0, N = Notes.size(); I != N; ++I)16049Diag(Notes[I].first, Notes[I].second);16050}16051}1605216053if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))16054return;1605516056// Emit warning for non-trivial dtor in global scope (a real global,16057// class-static, function-static).16058if (!VD->hasAttr<AlwaysDestroyAttr>())16059Diag(VD->getLocation(), diag::warn_exit_time_destructor);1606016061// TODO: this should be re-enabled for static locals by !CXAAtExit16062if (!VD->isStaticLocal())16063Diag(VD->getLocation(), diag::warn_global_destructor);16064}1606516066bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,16067QualType DeclInitType, MultiExprArg ArgsPtr,16068SourceLocation Loc,16069SmallVectorImpl<Expr *> &ConvertedArgs,16070bool AllowExplicit,16071bool IsListInitialization) {16072// FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.16073unsigned NumArgs = ArgsPtr.size();16074Expr **Args = ArgsPtr.data();1607516076const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();16077unsigned NumParams = Proto->getNumParams();1607816079// If too few arguments are available, we'll fill in the rest with defaults.16080if (NumArgs < NumParams)16081ConvertedArgs.reserve(NumParams);16082else16083ConvertedArgs.reserve(NumArgs);1608416085VariadicCallType CallType =16086Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;16087SmallVector<Expr *, 8> AllArgs;16088bool Invalid = GatherArgumentsForCall(16089Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,16090CallType, AllowExplicit, IsListInitialization);16091ConvertedArgs.append(AllArgs.begin(), AllArgs.end());1609216093DiagnoseSentinelCalls(Constructor, Loc, AllArgs);1609416095CheckConstructorCall(Constructor, DeclInitType,16096llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,16097Loc);1609816099return Invalid;16100}1610116102static inline bool16103CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,16104const FunctionDecl *FnDecl) {16105const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();16106if (isa<NamespaceDecl>(DC)) {16107return SemaRef.Diag(FnDecl->getLocation(),16108diag::err_operator_new_delete_declared_in_namespace)16109<< FnDecl->getDeclName();16110}1611116112if (isa<TranslationUnitDecl>(DC) &&16113FnDecl->getStorageClass() == SC_Static) {16114return SemaRef.Diag(FnDecl->getLocation(),16115diag::err_operator_new_delete_declared_static)16116<< FnDecl->getDeclName();16117}1611816119return false;16120}1612116122static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,16123const PointerType *PtrTy) {16124auto &Ctx = SemaRef.Context;16125Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();16126PtrQuals.removeAddressSpace();16127return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(16128PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));16129}1613016131static inline bool16132CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,16133CanQualType ExpectedResultType,16134CanQualType ExpectedFirstParamType,16135unsigned DependentParamTypeDiag,16136unsigned InvalidParamTypeDiag) {16137QualType ResultType =16138FnDecl->getType()->castAs<FunctionType>()->getReturnType();1613916140if (SemaRef.getLangOpts().OpenCLCPlusPlus) {16141// The operator is valid on any address space for OpenCL.16142// Drop address space from actual and expected result types.16143if (const auto *PtrTy = ResultType->getAs<PointerType>())16144ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);1614516146if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())16147ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);16148}1614916150// Check that the result type is what we expect.16151if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {16152// Reject even if the type is dependent; an operator delete function is16153// required to have a non-dependent result type.16154return SemaRef.Diag(16155FnDecl->getLocation(),16156ResultType->isDependentType()16157? diag::err_operator_new_delete_dependent_result_type16158: diag::err_operator_new_delete_invalid_result_type)16159<< FnDecl->getDeclName() << ExpectedResultType;16160}1616116162// A function template must have at least 2 parameters.16163if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)16164return SemaRef.Diag(FnDecl->getLocation(),16165diag::err_operator_new_delete_template_too_few_parameters)16166<< FnDecl->getDeclName();1616716168// The function decl must have at least 1 parameter.16169if (FnDecl->getNumParams() == 0)16170return SemaRef.Diag(FnDecl->getLocation(),16171diag::err_operator_new_delete_too_few_parameters)16172<< FnDecl->getDeclName();1617316174QualType FirstParamType = FnDecl->getParamDecl(0)->getType();16175if (SemaRef.getLangOpts().OpenCLCPlusPlus) {16176// The operator is valid on any address space for OpenCL.16177// Drop address space from actual and expected first parameter types.16178if (const auto *PtrTy =16179FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())16180FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);1618116182if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())16183ExpectedFirstParamType =16184RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);16185}1618616187// Check that the first parameter type is what we expect.16188if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=16189ExpectedFirstParamType) {16190// The first parameter type is not allowed to be dependent. As a tentative16191// DR resolution, we allow a dependent parameter type if it is the right16192// type anyway, to allow destroying operator delete in class templates.16193return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()16194? DependentParamTypeDiag16195: InvalidParamTypeDiag)16196<< FnDecl->getDeclName() << ExpectedFirstParamType;16197}1619816199return false;16200}1620116202static bool16203CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {16204// C++ [basic.stc.dynamic.allocation]p1:16205// A program is ill-formed if an allocation function is declared in a16206// namespace scope other than global scope or declared static in global16207// scope.16208if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))16209return true;1621016211CanQualType SizeTy =16212SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());1621316214// C++ [basic.stc.dynamic.allocation]p1:16215// The return type shall be void*. The first parameter shall have type16216// std::size_t.16217if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,16218SizeTy,16219diag::err_operator_new_dependent_param_type,16220diag::err_operator_new_param_type))16221return true;1622216223// C++ [basic.stc.dynamic.allocation]p1:16224// The first parameter shall not have an associated default argument.16225if (FnDecl->getParamDecl(0)->hasDefaultArg())16226return SemaRef.Diag(FnDecl->getLocation(),16227diag::err_operator_new_default_arg)16228<< FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();1622916230return false;16231}1623216233static bool16234CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {16235// C++ [basic.stc.dynamic.deallocation]p1:16236// A program is ill-formed if deallocation functions are declared in a16237// namespace scope other than global scope or declared static in global16238// scope.16239if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))16240return true;1624116242auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);1624316244// C++ P0722:16245// Within a class C, the first parameter of a destroying operator delete16246// shall be of type C *. The first parameter of any other deallocation16247// function shall be of type void *.16248CanQualType ExpectedFirstParamType =16249MD && MD->isDestroyingOperatorDelete()16250? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(16251SemaRef.Context.getRecordType(MD->getParent())))16252: SemaRef.Context.VoidPtrTy;1625316254// C++ [basic.stc.dynamic.deallocation]p2:16255// Each deallocation function shall return void16256if (CheckOperatorNewDeleteTypes(16257SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,16258diag::err_operator_delete_dependent_param_type,16259diag::err_operator_delete_param_type))16260return true;1626116262// C++ P0722:16263// A destroying operator delete shall be a usual deallocation function.16264if (MD && !MD->getParent()->isDependentContext() &&16265MD->isDestroyingOperatorDelete() &&16266!SemaRef.isUsualDeallocationFunction(MD)) {16267SemaRef.Diag(MD->getLocation(),16268diag::err_destroying_operator_delete_not_usual);16269return true;16270}1627116272return false;16273}1627416275bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {16276assert(FnDecl && FnDecl->isOverloadedOperator() &&16277"Expected an overloaded operator declaration");1627816279OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();1628016281// C++ [over.oper]p5:16282// The allocation and deallocation functions, operator new,16283// operator new[], operator delete and operator delete[], are16284// described completely in 3.7.3. The attributes and restrictions16285// found in the rest of this subclause do not apply to them unless16286// explicitly stated in 3.7.3.16287if (Op == OO_Delete || Op == OO_Array_Delete)16288return CheckOperatorDeleteDeclaration(*this, FnDecl);1628916290if (Op == OO_New || Op == OO_Array_New)16291return CheckOperatorNewDeclaration(*this, FnDecl);1629216293// C++ [over.oper]p7:16294// An operator function shall either be a member function or16295// be a non-member function and have at least one parameter16296// whose type is a class, a reference to a class, an enumeration,16297// or a reference to an enumeration.16298// Note: Before C++23, a member function could not be static. The only member16299// function allowed to be static is the call operator function.16300if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {16301if (MethodDecl->isStatic()) {16302if (Op == OO_Call || Op == OO_Subscript)16303Diag(FnDecl->getLocation(),16304(LangOpts.CPlusPlus2316305? diag::warn_cxx20_compat_operator_overload_static16306: diag::ext_operator_overload_static))16307<< FnDecl;16308else16309return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)16310<< FnDecl;16311}16312} else {16313bool ClassOrEnumParam = false;16314for (auto *Param : FnDecl->parameters()) {16315QualType ParamType = Param->getType().getNonReferenceType();16316if (ParamType->isDependentType() || ParamType->isRecordType() ||16317ParamType->isEnumeralType()) {16318ClassOrEnumParam = true;16319break;16320}16321}1632216323if (!ClassOrEnumParam)16324return Diag(FnDecl->getLocation(),16325diag::err_operator_overload_needs_class_or_enum)16326<< FnDecl->getDeclName();16327}1632816329// C++ [over.oper]p8:16330// An operator function cannot have default arguments (8.3.6),16331// except where explicitly stated below.16332//16333// Only the function-call operator (C++ [over.call]p1) and the subscript16334// operator (CWG2507) allow default arguments.16335if (Op != OO_Call) {16336ParmVarDecl *FirstDefaultedParam = nullptr;16337for (auto *Param : FnDecl->parameters()) {16338if (Param->hasDefaultArg()) {16339FirstDefaultedParam = Param;16340break;16341}16342}16343if (FirstDefaultedParam) {16344if (Op == OO_Subscript) {16345Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2316346? diag::ext_subscript_overload16347: diag::error_subscript_overload)16348<< FnDecl->getDeclName() << 116349<< FirstDefaultedParam->getDefaultArgRange();16350} else {16351return Diag(FirstDefaultedParam->getLocation(),16352diag::err_operator_overload_default_arg)16353<< FnDecl->getDeclName()16354<< FirstDefaultedParam->getDefaultArgRange();16355}16356}16357}1635816359static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {16360{ false, false, false }16361#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \16362, { Unary, Binary, MemberOnly }16363#include "clang/Basic/OperatorKinds.def"16364};1636516366bool CanBeUnaryOperator = OperatorUses[Op][0];16367bool CanBeBinaryOperator = OperatorUses[Op][1];16368bool MustBeMemberOperator = OperatorUses[Op][2];1636916370// C++ [over.oper]p8:16371// [...] Operator functions cannot have more or fewer parameters16372// than the number required for the corresponding operator, as16373// described in the rest of this subclause.16374unsigned NumParams = FnDecl->getNumParams() +16375(isa<CXXMethodDecl>(FnDecl) &&16376!FnDecl->hasCXXExplicitFunctionObjectParameter()16377? 116378: 0);16379if (Op != OO_Call && Op != OO_Subscript &&16380((NumParams == 1 && !CanBeUnaryOperator) ||16381(NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||16382(NumParams > 2))) {16383// We have the wrong number of parameters.16384unsigned ErrorKind;16385if (CanBeUnaryOperator && CanBeBinaryOperator) {16386ErrorKind = 2; // 2 -> unary or binary.16387} else if (CanBeUnaryOperator) {16388ErrorKind = 0; // 0 -> unary16389} else {16390assert(CanBeBinaryOperator &&16391"All non-call overloaded operators are unary or binary!");16392ErrorKind = 1; // 1 -> binary16393}16394return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)16395<< FnDecl->getDeclName() << NumParams << ErrorKind;16396}1639716398if (Op == OO_Subscript && NumParams != 2) {16399Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2316400? diag::ext_subscript_overload16401: diag::error_subscript_overload)16402<< FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);16403}1640416405// Overloaded operators other than operator() and operator[] cannot be16406// variadic.16407if (Op != OO_Call &&16408FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {16409return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)16410<< FnDecl->getDeclName();16411}1641216413// Some operators must be member functions.16414if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {16415return Diag(FnDecl->getLocation(),16416diag::err_operator_overload_must_be_member)16417<< FnDecl->getDeclName();16418}1641916420// C++ [over.inc]p1:16421// The user-defined function called operator++ implements the16422// prefix and postfix ++ operator. If this function is a member16423// function with no parameters, or a non-member function with one16424// parameter of class or enumeration type, it defines the prefix16425// increment operator ++ for objects of that type. If the function16426// is a member function with one parameter (which shall be of type16427// int) or a non-member function with two parameters (the second16428// of which shall be of type int), it defines the postfix16429// increment operator ++ for objects of that type.16430if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {16431ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);16432QualType ParamType = LastParam->getType();1643316434if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&16435!ParamType->isDependentType())16436return Diag(LastParam->getLocation(),16437diag::err_operator_overload_post_incdec_must_be_int)16438<< LastParam->getType() << (Op == OO_MinusMinus);16439}1644016441return false;16442}1644316444static bool16445checkLiteralOperatorTemplateParameterList(Sema &SemaRef,16446FunctionTemplateDecl *TpDecl) {16447TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();1644816449// Must have one or two template parameters.16450if (TemplateParams->size() == 1) {16451NonTypeTemplateParmDecl *PmDecl =16452dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));1645316454// The template parameter must be a char parameter pack.16455if (PmDecl && PmDecl->isTemplateParameterPack() &&16456SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))16457return false;1645816459// C++20 [over.literal]p5:16460// A string literal operator template is a literal operator template16461// whose template-parameter-list comprises a single non-type16462// template-parameter of class type.16463//16464// As a DR resolution, we also allow placeholders for deduced class16465// template specializations.16466if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&16467!PmDecl->isTemplateParameterPack() &&16468(PmDecl->getType()->isRecordType() ||16469PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))16470return false;16471} else if (TemplateParams->size() == 2) {16472TemplateTypeParmDecl *PmType =16473dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));16474NonTypeTemplateParmDecl *PmArgs =16475dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));1647616477// The second template parameter must be a parameter pack with the16478// first template parameter as its type.16479if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&16480PmArgs->isTemplateParameterPack()) {16481const TemplateTypeParmType *TArgs =16482PmArgs->getType()->getAs<TemplateTypeParmType>();16483if (TArgs && TArgs->getDepth() == PmType->getDepth() &&16484TArgs->getIndex() == PmType->getIndex()) {16485if (!SemaRef.inTemplateInstantiation())16486SemaRef.Diag(TpDecl->getLocation(),16487diag::ext_string_literal_operator_template);16488return false;16489}16490}16491}1649216493SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),16494diag::err_literal_operator_template)16495<< TpDecl->getTemplateParameters()->getSourceRange();16496return true;16497}1649816499bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {16500if (isa<CXXMethodDecl>(FnDecl)) {16501Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)16502<< FnDecl->getDeclName();16503return true;16504}1650516506if (FnDecl->isExternC()) {16507Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);16508if (const LinkageSpecDecl *LSD =16509FnDecl->getDeclContext()->getExternCContext())16510Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);16511return true;16512}1651316514// This might be the definition of a literal operator template.16515FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();1651616517// This might be a specialization of a literal operator template.16518if (!TpDecl)16519TpDecl = FnDecl->getPrimaryTemplate();1652016521// template <char...> type operator "" name() and16522// template <class T, T...> type operator "" name() are the only valid16523// template signatures, and the only valid signatures with no parameters.16524//16525// C++20 also allows template <SomeClass T> type operator "" name().16526if (TpDecl) {16527if (FnDecl->param_size() != 0) {16528Diag(FnDecl->getLocation(),16529diag::err_literal_operator_template_with_params);16530return true;16531}1653216533if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))16534return true;1653516536} else if (FnDecl->param_size() == 1) {16537const ParmVarDecl *Param = FnDecl->getParamDecl(0);1653816539QualType ParamType = Param->getType().getUnqualifiedType();1654016541// Only unsigned long long int, long double, any character type, and const16542// char * are allowed as the only parameters.16543if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||16544ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||16545Context.hasSameType(ParamType, Context.CharTy) ||16546Context.hasSameType(ParamType, Context.WideCharTy) ||16547Context.hasSameType(ParamType, Context.Char8Ty) ||16548Context.hasSameType(ParamType, Context.Char16Ty) ||16549Context.hasSameType(ParamType, Context.Char32Ty)) {16550} else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {16551QualType InnerType = Ptr->getPointeeType();1655216553// Pointer parameter must be a const char *.16554if (!(Context.hasSameType(InnerType.getUnqualifiedType(),16555Context.CharTy) &&16556InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {16557Diag(Param->getSourceRange().getBegin(),16558diag::err_literal_operator_param)16559<< ParamType << "'const char *'" << Param->getSourceRange();16560return true;16561}1656216563} else if (ParamType->isRealFloatingType()) {16564Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)16565<< ParamType << Context.LongDoubleTy << Param->getSourceRange();16566return true;1656716568} else if (ParamType->isIntegerType()) {16569Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)16570<< ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();16571return true;1657216573} else {16574Diag(Param->getSourceRange().getBegin(),16575diag::err_literal_operator_invalid_param)16576<< ParamType << Param->getSourceRange();16577return true;16578}1657916580} else if (FnDecl->param_size() == 2) {16581FunctionDecl::param_iterator Param = FnDecl->param_begin();1658216583// First, verify that the first parameter is correct.1658416585QualType FirstParamType = (*Param)->getType().getUnqualifiedType();1658616587// Two parameter function must have a pointer to const as a16588// first parameter; let's strip those qualifiers.16589const PointerType *PT = FirstParamType->getAs<PointerType>();1659016591if (!PT) {16592Diag((*Param)->getSourceRange().getBegin(),16593diag::err_literal_operator_param)16594<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();16595return true;16596}1659716598QualType PointeeType = PT->getPointeeType();16599// First parameter must be const16600if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {16601Diag((*Param)->getSourceRange().getBegin(),16602diag::err_literal_operator_param)16603<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();16604return true;16605}1660616607QualType InnerType = PointeeType.getUnqualifiedType();16608// Only const char *, const wchar_t*, const char8_t*, const char16_t*, and16609// const char32_t* are allowed as the first parameter to a two-parameter16610// function16611if (!(Context.hasSameType(InnerType, Context.CharTy) ||16612Context.hasSameType(InnerType, Context.WideCharTy) ||16613Context.hasSameType(InnerType, Context.Char8Ty) ||16614Context.hasSameType(InnerType, Context.Char16Ty) ||16615Context.hasSameType(InnerType, Context.Char32Ty))) {16616Diag((*Param)->getSourceRange().getBegin(),16617diag::err_literal_operator_param)16618<< FirstParamType << "'const char *'" << (*Param)->getSourceRange();16619return true;16620}1662116622// Move on to the second and final parameter.16623++Param;1662416625// The second parameter must be a std::size_t.16626QualType SecondParamType = (*Param)->getType().getUnqualifiedType();16627if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {16628Diag((*Param)->getSourceRange().getBegin(),16629diag::err_literal_operator_param)16630<< SecondParamType << Context.getSizeType()16631<< (*Param)->getSourceRange();16632return true;16633}16634} else {16635Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);16636return true;16637}1663816639// Parameters are good.1664016641// A parameter-declaration-clause containing a default argument is not16642// equivalent to any of the permitted forms.16643for (auto *Param : FnDecl->parameters()) {16644if (Param->hasDefaultArg()) {16645Diag(Param->getDefaultArgRange().getBegin(),16646diag::err_literal_operator_default_argument)16647<< Param->getDefaultArgRange();16648break;16649}16650}1665116652const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();16653ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();16654if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&16655!getSourceManager().isInSystemHeader(FnDecl->getLocation())) {16656// C++23 [usrlit.suffix]p1:16657// Literal suffix identifiers that do not start with an underscore are16658// reserved for future standardization. Literal suffix identifiers that16659// contain a double underscore __ are reserved for use by C++16660// implementations.16661Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)16662<< static_cast<int>(Status)16663<< StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());16664}1666516666return false;16667}1666816669Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,16670Expr *LangStr,16671SourceLocation LBraceLoc) {16672StringLiteral *Lit = cast<StringLiteral>(LangStr);16673assert(Lit->isUnevaluated() && "Unexpected string literal kind");1667416675StringRef Lang = Lit->getString();16676LinkageSpecLanguageIDs Language;16677if (Lang == "C")16678Language = LinkageSpecLanguageIDs::C;16679else if (Lang == "C++")16680Language = LinkageSpecLanguageIDs::CXX;16681else {16682Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)16683<< LangStr->getSourceRange();16684return nullptr;16685}1668616687// FIXME: Add all the various semantics of linkage specifications1668816689LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,16690LangStr->getExprLoc(), Language,16691LBraceLoc.isValid());1669216693/// C++ [module.unit]p7.2.316694/// - Otherwise, if the declaration16695/// - ...16696/// - ...16697/// - appears within a linkage-specification,16698/// it is attached to the global module.16699///16700/// If the declaration is already in global module fragment, we don't16701/// need to attach it again.16702if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {16703Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);16704D->setLocalOwningModule(GlobalModule);16705}1670616707CurContext->addDecl(D);16708PushDeclContext(S, D);16709return D;16710}1671116712Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,16713Decl *LinkageSpec,16714SourceLocation RBraceLoc) {16715if (RBraceLoc.isValid()) {16716LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);16717LSDecl->setRBraceLoc(RBraceLoc);16718}1671916720// If the current module doesn't has Parent, it implies that the16721// LinkageSpec isn't in the module created by itself. So we don't16722// need to pop it.16723if (getLangOpts().CPlusPlusModules && getCurrentModule() &&16724getCurrentModule()->isImplicitGlobalModule() &&16725getCurrentModule()->Parent)16726PopImplicitGlobalModuleFragment();1672716728PopDeclContext();16729return LinkageSpec;16730}1673116732Decl *Sema::ActOnEmptyDeclaration(Scope *S,16733const ParsedAttributesView &AttrList,16734SourceLocation SemiLoc) {16735Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);16736// Attribute declarations appertain to empty declaration so we handle16737// them here.16738ProcessDeclAttributeList(S, ED, AttrList);1673916740CurContext->addDecl(ED);16741return ED;16742}1674316744VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,16745SourceLocation StartLoc,16746SourceLocation Loc,16747const IdentifierInfo *Name) {16748bool Invalid = false;16749QualType ExDeclType = TInfo->getType();1675016751// Arrays and functions decay.16752if (ExDeclType->isArrayType())16753ExDeclType = Context.getArrayDecayedType(ExDeclType);16754else if (ExDeclType->isFunctionType())16755ExDeclType = Context.getPointerType(ExDeclType);1675616757// C++ 15.3p1: The exception-declaration shall not denote an incomplete type.16758// The exception-declaration shall not denote a pointer or reference to an16759// incomplete type, other than [cv] void*.16760// N2844 forbids rvalue references.16761if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {16762Diag(Loc, diag::err_catch_rvalue_ref);16763Invalid = true;16764}1676516766if (ExDeclType->isVariablyModifiedType()) {16767Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;16768Invalid = true;16769}1677016771QualType BaseType = ExDeclType;16772int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference16773unsigned DK = diag::err_catch_incomplete;16774if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {16775BaseType = Ptr->getPointeeType();16776Mode = 1;16777DK = diag::err_catch_incomplete_ptr;16778} else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {16779// For the purpose of error recovery, we treat rvalue refs like lvalue refs.16780BaseType = Ref->getPointeeType();16781Mode = 2;16782DK = diag::err_catch_incomplete_ref;16783}16784if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&16785!BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))16786Invalid = true;1678716788if (!Invalid && BaseType.isWebAssemblyReferenceType()) {16789Diag(Loc, diag::err_wasm_reftype_tc) << 1;16790Invalid = true;16791}1679216793if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {16794Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;16795Invalid = true;16796}1679716798if (!Invalid && !ExDeclType->isDependentType() &&16799RequireNonAbstractType(Loc, ExDeclType,16800diag::err_abstract_type_in_decl,16801AbstractVariableType))16802Invalid = true;1680316804// Only the non-fragile NeXT runtime currently supports C++ catches16805// of ObjC types, and no runtime supports catching ObjC types by value.16806if (!Invalid && getLangOpts().ObjC) {16807QualType T = ExDeclType;16808if (const ReferenceType *RT = T->getAs<ReferenceType>())16809T = RT->getPointeeType();1681016811if (T->isObjCObjectType()) {16812Diag(Loc, diag::err_objc_object_catch);16813Invalid = true;16814} else if (T->isObjCObjectPointerType()) {16815// FIXME: should this be a test for macosx-fragile specifically?16816if (getLangOpts().ObjCRuntime.isFragile())16817Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);16818}16819}1682016821VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,16822ExDeclType, TInfo, SC_None);16823ExDecl->setExceptionVariable(true);1682416825// In ARC, infer 'retaining' for variables of retainable type.16826if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))16827Invalid = true;1682816829if (!Invalid && !ExDeclType->isDependentType()) {16830if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {16831// Insulate this from anything else we might currently be parsing.16832EnterExpressionEvaluationContext scope(16833*this, ExpressionEvaluationContext::PotentiallyEvaluated);1683416835// C++ [except.handle]p16:16836// The object declared in an exception-declaration or, if the16837// exception-declaration does not specify a name, a temporary (12.2) is16838// copy-initialized (8.5) from the exception object. [...]16839// The object is destroyed when the handler exits, after the destruction16840// of any automatic objects initialized within the handler.16841//16842// We just pretend to initialize the object with itself, then make sure16843// it can be destroyed later.16844QualType initType = Context.getExceptionObjectType(ExDeclType);1684516846InitializedEntity entity =16847InitializedEntity::InitializeVariable(ExDecl);16848InitializationKind initKind =16849InitializationKind::CreateCopy(Loc, SourceLocation());1685016851Expr *opaqueValue =16852new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);16853InitializationSequence sequence(*this, entity, initKind, opaqueValue);16854ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);16855if (result.isInvalid())16856Invalid = true;16857else {16858// If the constructor used was non-trivial, set this as the16859// "initializer".16860CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();16861if (!construct->getConstructor()->isTrivial()) {16862Expr *init = MaybeCreateExprWithCleanups(construct);16863ExDecl->setInit(init);16864}1686516866// And make sure it's destructable.16867FinalizeVarWithDestructor(ExDecl, recordType);16868}16869}16870}1687116872if (Invalid)16873ExDecl->setInvalidDecl();1687416875return ExDecl;16876}1687716878Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {16879TypeSourceInfo *TInfo = GetTypeForDeclarator(D);16880bool Invalid = D.isInvalidType();1688116882// Check for unexpanded parameter packs.16883if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,16884UPPC_ExceptionType)) {16885TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,16886D.getIdentifierLoc());16887Invalid = true;16888}1688916890const IdentifierInfo *II = D.getIdentifier();16891if (NamedDecl *PrevDecl =16892LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,16893RedeclarationKind::ForVisibleRedeclaration)) {16894// The scope should be freshly made just for us. There is just no way16895// it contains any previous declaration, except for function parameters in16896// a function-try-block's catch statement.16897assert(!S->isDeclScope(PrevDecl));16898if (isDeclInScope(PrevDecl, CurContext, S)) {16899Diag(D.getIdentifierLoc(), diag::err_redefinition)16900<< D.getIdentifier();16901Diag(PrevDecl->getLocation(), diag::note_previous_definition);16902Invalid = true;16903} else if (PrevDecl->isTemplateParameter())16904// Maybe we will complain about the shadowed template parameter.16905DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);16906}1690716908if (D.getCXXScopeSpec().isSet() && !Invalid) {16909Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)16910<< D.getCXXScopeSpec().getRange();16911Invalid = true;16912}1691316914VarDecl *ExDecl = BuildExceptionDeclaration(16915S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());16916if (Invalid)16917ExDecl->setInvalidDecl();1691816919// Add the exception declaration into this scope.16920if (II)16921PushOnScopeChains(ExDecl, S);16922else16923CurContext->addDecl(ExDecl);1692416925ProcessDeclAttributes(S, ExDecl, D);16926return ExDecl;16927}1692816929Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,16930Expr *AssertExpr,16931Expr *AssertMessageExpr,16932SourceLocation RParenLoc) {16933if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))16934return nullptr;1693516936return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,16937AssertMessageExpr, RParenLoc, false);16938}1693916940static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {16941switch (BTK) {16942case BuiltinType::Char_S:16943case BuiltinType::Char_U:16944break;16945case BuiltinType::Char8:16946OS << "u8";16947break;16948case BuiltinType::Char16:16949OS << 'u';16950break;16951case BuiltinType::Char32:16952OS << 'U';16953break;16954case BuiltinType::WChar_S:16955case BuiltinType::WChar_U:16956OS << 'L';16957break;16958default:16959llvm_unreachable("Non-character type");16960}16961}1696216963/// Convert character's value, interpreted as a code unit, to a string.16964/// The value needs to be zero-extended to 32-bits.16965/// FIXME: This assumes Unicode literal encodings16966static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,16967unsigned TyWidth,16968SmallVectorImpl<char> &Str) {16969char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];16970char *Ptr = Arr;16971BuiltinType::Kind K = BTy->getKind();16972llvm::raw_svector_ostream OS(Str);1697316974// This should catch Char_S, Char_U, Char8, and use of escaped characters in16975// other types.16976if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||16977K == BuiltinType::Char8 || Value <= 0x7F) {16978StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);16979if (!Escaped.empty())16980EscapeStringForDiagnostic(Escaped, Str);16981else16982OS << static_cast<char>(Value);16983return;16984}1698516986switch (K) {16987case BuiltinType::Char16:16988case BuiltinType::Char32:16989case BuiltinType::WChar_S:16990case BuiltinType::WChar_U: {16991if (llvm::ConvertCodePointToUTF8(Value, Ptr))16992EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);16993else16994OS << "\\x"16995<< llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);16996break;16997}16998default:16999llvm_unreachable("Non-character type is passed");17000}17001}1700217003/// Convert \V to a string we can present to the user in a diagnostic17004/// \T is the type of the expression that has been evaluated into \V17005static bool ConvertAPValueToString(const APValue &V, QualType T,17006SmallVectorImpl<char> &Str,17007ASTContext &Context) {17008if (!V.hasValue())17009return false;1701017011switch (V.getKind()) {17012case APValue::ValueKind::Int:17013if (T->isBooleanType()) {17014// Bools are reduced to ints during evaluation, but for17015// diagnostic purposes we want to print them as17016// true or false.17017int64_t BoolValue = V.getInt().getExtValue();17018assert((BoolValue == 0 || BoolValue == 1) &&17019"Bool type, but value is not 0 or 1");17020llvm::raw_svector_ostream OS(Str);17021OS << (BoolValue ? "true" : "false");17022} else {17023llvm::raw_svector_ostream OS(Str);17024// Same is true for chars.17025// We want to print the character representation for textual types17026const auto *BTy = T->getAs<BuiltinType>();17027if (BTy) {17028switch (BTy->getKind()) {17029case BuiltinType::Char_S:17030case BuiltinType::Char_U:17031case BuiltinType::Char8:17032case BuiltinType::Char16:17033case BuiltinType::Char32:17034case BuiltinType::WChar_S:17035case BuiltinType::WChar_U: {17036unsigned TyWidth = Context.getIntWidth(T);17037assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");17038uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());17039WriteCharTypePrefix(BTy->getKind(), OS);17040OS << '\'';17041WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);17042OS << "' (0x"17043<< llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,17044/*Upper=*/true)17045<< ", " << V.getInt() << ')';17046return true;17047}17048default:17049break;17050}17051}17052V.getInt().toString(Str);17053}1705417055break;1705617057case APValue::ValueKind::Float:17058V.getFloat().toString(Str);17059break;1706017061case APValue::ValueKind::LValue:17062if (V.isNullPointer()) {17063llvm::raw_svector_ostream OS(Str);17064OS << "nullptr";17065} else17066return false;17067break;1706817069case APValue::ValueKind::ComplexFloat: {17070llvm::raw_svector_ostream OS(Str);17071OS << '(';17072V.getComplexFloatReal().toString(Str);17073OS << " + ";17074V.getComplexFloatImag().toString(Str);17075OS << "i)";17076} break;1707717078case APValue::ValueKind::ComplexInt: {17079llvm::raw_svector_ostream OS(Str);17080OS << '(';17081V.getComplexIntReal().toString(Str);17082OS << " + ";17083V.getComplexIntImag().toString(Str);17084OS << "i)";17085} break;1708617087default:17088return false;17089}1709017091return true;17092}1709317094/// Some Expression types are not useful to print notes about,17095/// e.g. literals and values that have already been expanded17096/// before such as int-valued template parameters.17097static bool UsefulToPrintExpr(const Expr *E) {17098E = E->IgnoreParenImpCasts();17099// Literals are pretty easy for humans to understand.17100if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,17101CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))17102return false;1710317104// These have been substituted from template parameters17105// and appear as literals in the static assert error.17106if (isa<SubstNonTypeTemplateParmExpr>(E))17107return false;1710817109// -5 is also simple to understand.17110if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))17111return UsefulToPrintExpr(UnaryOp->getSubExpr());1711217113// Only print nested arithmetic operators.17114if (const auto *BO = dyn_cast<BinaryOperator>(E))17115return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||17116BO->isBitwiseOp());1711717118return true;17119}1712017121void Sema::DiagnoseStaticAssertDetails(const Expr *E) {17122if (const auto *Op = dyn_cast<BinaryOperator>(E);17123Op && Op->getOpcode() != BO_LOr) {17124const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();17125const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();1712617127// Ignore comparisons of boolean expressions with a boolean literal.17128if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||17129(isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))17130return;1713117132// Don't print obvious expressions.17133if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))17134return;1713517136struct {17137const clang::Expr *Cond;17138Expr::EvalResult Result;17139SmallString<12> ValueString;17140bool Print;17141} DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},17142{RHS, Expr::EvalResult(), {}, false}};17143for (unsigned I = 0; I < 2; I++) {17144const Expr *Side = DiagSide[I].Cond;1714517146Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);1714717148DiagSide[I].Print =17149ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),17150DiagSide[I].ValueString, Context);17151}17152if (DiagSide[0].Print && DiagSide[1].Print) {17153Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)17154<< DiagSide[0].ValueString << Op->getOpcodeStr()17155<< DiagSide[1].ValueString << Op->getSourceRange();17156}17157}17158}1715917160bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,17161std::string &Result,17162ASTContext &Ctx,17163bool ErrorOnInvalidMessage) {17164assert(Message);17165assert(!Message->isTypeDependent() && !Message->isValueDependent() &&17166"can't evaluate a dependant static assert message");1716717168if (const auto *SL = dyn_cast<StringLiteral>(Message)) {17169assert(SL->isUnevaluated() && "expected an unevaluated string");17170Result.assign(SL->getString().begin(), SL->getString().end());17171return true;17172}1717317174SourceLocation Loc = Message->getBeginLoc();17175QualType T = Message->getType().getNonReferenceType();17176auto *RD = T->getAsCXXRecordDecl();17177if (!RD) {17178Diag(Loc, diag::err_static_assert_invalid_message);17179return false;17180}1718117182auto FindMember = [&](StringRef Member, bool &Empty,17183bool Diag = false) -> std::optional<LookupResult> {17184DeclarationName DN = PP.getIdentifierInfo(Member);17185LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);17186LookupQualifiedName(MemberLookup, RD);17187Empty = MemberLookup.empty();17188OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),17189OverloadCandidateSet::CSK_Normal);17190if (MemberLookup.empty())17191return std::nullopt;17192return std::move(MemberLookup);17193};1719417195bool SizeNotFound, DataNotFound;17196std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);17197std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);17198if (SizeNotFound || DataNotFound) {17199Diag(Loc, diag::err_static_assert_missing_member_function)17200<< ((SizeNotFound && DataNotFound) ? 217201: SizeNotFound ? 017202: 1);17203return false;17204}1720517206if (!SizeMember || !DataMember) {17207if (!SizeMember)17208FindMember("size", SizeNotFound, /*Diag=*/true);17209if (!DataMember)17210FindMember("data", DataNotFound, /*Diag=*/true);17211return false;17212}1721317214auto BuildExpr = [&](LookupResult &LR) {17215ExprResult Res = BuildMemberReferenceExpr(17216Message, Message->getType(), Message->getBeginLoc(), false,17217CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);17218if (Res.isInvalid())17219return ExprError();17220Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,17221false, true);17222if (Res.isInvalid())17223return ExprError();17224if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())17225return ExprError();17226return TemporaryMaterializationConversion(Res.get());17227};1722817229ExprResult SizeE = BuildExpr(*SizeMember);17230ExprResult DataE = BuildExpr(*DataMember);1723117232QualType SizeT = Context.getSizeType();17233QualType ConstCharPtr =17234Context.getPointerType(Context.getConstType(Context.CharTy));1723517236ExprResult EvaluatedSize =17237SizeE.isInvalid() ? ExprError()17238: BuildConvertedConstantExpression(17239SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);17240if (EvaluatedSize.isInvalid()) {17241Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;17242return false;17243}1724417245ExprResult EvaluatedData =17246DataE.isInvalid()17247? ExprError()17248: BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,17249CCEK_StaticAssertMessageData);17250if (EvaluatedData.isInvalid()) {17251Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;17252return false;17253}1725417255if (!ErrorOnInvalidMessage &&17256Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))17257return true;1725817259Expr::EvalResult Status;17260SmallVector<PartialDiagnosticAt, 8> Notes;17261Status.Diag = &Notes;17262if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),17263EvaluatedData.get(), Ctx, Status) ||17264!Notes.empty()) {17265Diag(Message->getBeginLoc(),17266ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr17267: diag::warn_static_assert_message_constexpr);17268for (const auto &Note : Notes)17269Diag(Note.first, Note.second);17270return !ErrorOnInvalidMessage;17271}17272return true;17273}1727417275Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,17276Expr *AssertExpr, Expr *AssertMessage,17277SourceLocation RParenLoc,17278bool Failed) {17279assert(AssertExpr != nullptr && "Expected non-null condition");17280if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&17281(!AssertMessage || (!AssertMessage->isTypeDependent() &&17282!AssertMessage->isValueDependent())) &&17283!Failed) {17284// In a static_assert-declaration, the constant-expression shall be a17285// constant expression that can be contextually converted to bool.17286ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);17287if (Converted.isInvalid())17288Failed = true;1728917290ExprResult FullAssertExpr =17291ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,17292/*DiscardedValue*/ false,17293/*IsConstexpr*/ true);17294if (FullAssertExpr.isInvalid())17295Failed = true;17296else17297AssertExpr = FullAssertExpr.get();1729817299llvm::APSInt Cond;17300Expr *BaseExpr = AssertExpr;17301AllowFoldKind FoldKind = NoFold;1730217303if (!getLangOpts().CPlusPlus) {17304// In C mode, allow folding as an extension for better compatibility with17305// C++ in terms of expressions like static_assert("test") or17306// static_assert(nullptr).17307FoldKind = AllowFold;17308}1730917310if (!Failed && VerifyIntegerConstantExpression(17311BaseExpr, &Cond,17312diag::err_static_assert_expression_is_not_constant,17313FoldKind).isInvalid())17314Failed = true;1731517316// If the static_assert passes, only verify that17317// the message is grammatically valid without evaluating it.17318if (!Failed && AssertMessage && Cond.getBoolValue()) {17319std::string Str;17320EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,17321/*ErrorOnInvalidMessage=*/false);17322}1732317324// CWG251817325// [dcl.pre]/p10 If [...] the expression is evaluated in the context of a17326// template definition, the declaration has no effect.17327bool InTemplateDefinition =17328getLangOpts().CPlusPlus && CurContext->isDependentContext();1732917330if (!Failed && !Cond && !InTemplateDefinition) {17331SmallString<256> MsgBuffer;17332llvm::raw_svector_ostream Msg(MsgBuffer);17333bool HasMessage = AssertMessage;17334if (AssertMessage) {17335std::string Str;17336HasMessage =17337EvaluateStaticAssertMessageAsString(17338AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||17339!Str.empty();17340Msg << Str;17341}17342Expr *InnerCond = nullptr;17343std::string InnerCondDescription;17344std::tie(InnerCond, InnerCondDescription) =17345findFailedBooleanCondition(Converted.get());17346if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {17347// Drill down into concept specialization expressions to see why they17348// weren't satisfied.17349Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)17350<< !HasMessage << Msg.str() << AssertExpr->getSourceRange();17351ConstraintSatisfaction Satisfaction;17352if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))17353DiagnoseUnsatisfiedConstraint(Satisfaction);17354} else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)17355&& !isa<IntegerLiteral>(InnerCond)) {17356Diag(InnerCond->getBeginLoc(),17357diag::err_static_assert_requirement_failed)17358<< InnerCondDescription << !HasMessage << Msg.str()17359<< InnerCond->getSourceRange();17360DiagnoseStaticAssertDetails(InnerCond);17361} else {17362Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)17363<< !HasMessage << Msg.str() << AssertExpr->getSourceRange();17364PrintContextStack();17365}17366Failed = true;17367}17368} else {17369ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,17370/*DiscardedValue*/false,17371/*IsConstexpr*/true);17372if (FullAssertExpr.isInvalid())17373Failed = true;17374else17375AssertExpr = FullAssertExpr.get();17376}1737717378Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,17379AssertExpr, AssertMessage, RParenLoc,17380Failed);1738117382CurContext->addDecl(Decl);17383return Decl;17384}1738517386DeclResult Sema::ActOnTemplatedFriendTag(17387Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,17388CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,17389const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {17390TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);1739117392bool IsMemberSpecialization = false;17393bool Invalid = false;1739417395if (TemplateParameterList *TemplateParams =17396MatchTemplateParametersToScopeSpecifier(17397TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,17398IsMemberSpecialization, Invalid)) {17399if (TemplateParams->size() > 0) {17400// This is a declaration of a class template.17401if (Invalid)17402return true;1740317404return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,17405Name, NameLoc, Attr, TemplateParams, AS_public,17406/*ModulePrivateLoc=*/SourceLocation(),17407FriendLoc, TempParamLists.size() - 1,17408TempParamLists.data())17409.get();17410} else {17411// The "template<>" header is extraneous.17412Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)17413<< TypeWithKeyword::getTagTypeKindName(Kind) << Name;17414IsMemberSpecialization = true;17415}17416}1741717418if (Invalid) return true;1741917420bool isAllExplicitSpecializations = true;17421for (unsigned I = TempParamLists.size(); I-- > 0; ) {17422if (TempParamLists[I]->size()) {17423isAllExplicitSpecializations = false;17424break;17425}17426}1742717428// FIXME: don't ignore attributes.1742917430// If it's explicit specializations all the way down, just forget17431// about the template header and build an appropriate non-templated17432// friend. TODO: for source fidelity, remember the headers.17433if (isAllExplicitSpecializations) {17434if (SS.isEmpty()) {17435bool Owned = false;17436bool IsDependent = false;17437return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,17438Attr, AS_public,17439/*ModulePrivateLoc=*/SourceLocation(),17440MultiTemplateParamsArg(), Owned, IsDependent,17441/*ScopedEnumKWLoc=*/SourceLocation(),17442/*ScopedEnumUsesClassTag=*/false,17443/*UnderlyingType=*/TypeResult(),17444/*IsTypeSpecifier=*/false,17445/*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);17446}1744717448NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);17449ElaboratedTypeKeyword Keyword17450= TypeWithKeyword::getKeywordForTagTypeKind(Kind);17451QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,17452*Name, NameLoc);17453if (T.isNull())17454return true;1745517456TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);17457if (isa<DependentNameType>(T)) {17458DependentNameTypeLoc TL =17459TSI->getTypeLoc().castAs<DependentNameTypeLoc>();17460TL.setElaboratedKeywordLoc(TagLoc);17461TL.setQualifierLoc(QualifierLoc);17462TL.setNameLoc(NameLoc);17463} else {17464ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();17465TL.setElaboratedKeywordLoc(TagLoc);17466TL.setQualifierLoc(QualifierLoc);17467TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);17468}1746917470FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,17471TSI, FriendLoc, TempParamLists);17472Friend->setAccess(AS_public);17473CurContext->addDecl(Friend);17474return Friend;17475}1747617477assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");17478174791748017481// Handle the case of a templated-scope friend class. e.g.17482// template <class T> class A<T>::B;17483// FIXME: we don't support these right now.17484Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)17485<< SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);17486ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);17487QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);17488TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);17489DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();17490TL.setElaboratedKeywordLoc(TagLoc);17491TL.setQualifierLoc(SS.getWithLocInContext(Context));17492TL.setNameLoc(NameLoc);1749317494FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,17495TSI, FriendLoc, TempParamLists);17496Friend->setAccess(AS_public);17497Friend->setUnsupportedFriend(true);17498CurContext->addDecl(Friend);17499return Friend;17500}1750117502Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,17503MultiTemplateParamsArg TempParams) {17504SourceLocation Loc = DS.getBeginLoc();17505SourceLocation FriendLoc = DS.getFriendSpecLoc();1750617507assert(DS.isFriendSpecified());17508assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);1750917510// C++ [class.friend]p3:17511// A friend declaration that does not declare a function shall have one of17512// the following forms:17513// friend elaborated-type-specifier ;17514// friend simple-type-specifier ;17515// friend typename-specifier ;17516//17517// If the friend keyword isn't first, or if the declarations has any type17518// qualifiers, then the declaration doesn't have that form.17519if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())17520Diag(FriendLoc, diag::err_friend_not_first_in_declaration);17521if (DS.getTypeQualifiers()) {17522if (DS.getTypeQualifiers() & DeclSpec::TQ_const)17523Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";17524if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)17525Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";17526if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)17527Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";17528if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)17529Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";17530if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)17531Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";17532}1753317534// Try to convert the decl specifier to a type. This works for17535// friend templates because ActOnTag never produces a ClassTemplateDecl17536// for a TagUseKind::Friend.17537Declarator TheDeclarator(DS, ParsedAttributesView::none(),17538DeclaratorContext::Member);17539TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);17540QualType T = TSI->getType();17541if (TheDeclarator.isInvalidType())17542return nullptr;1754317544if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))17545return nullptr;1754617547if (!T->isElaboratedTypeSpecifier()) {17548if (TempParams.size()) {17549// C++23 [dcl.pre]p5:17550// In a simple-declaration, the optional init-declarator-list can be17551// omitted only when declaring a class or enumeration, that is, when17552// the decl-specifier-seq contains either a class-specifier, an17553// elaborated-type-specifier with a class-key, or an enum-specifier.17554//17555// The declaration of a template-declaration or explicit-specialization17556// is never a member-declaration, so this must be a simple-declaration17557// with no init-declarator-list. Therefore, this is ill-formed.17558Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();17559return nullptr;17560} else if (const RecordDecl *RD = T->getAsRecordDecl()) {17561SmallString<16> InsertionText(" ");17562InsertionText += RD->getKindName();1756317564Diag(Loc, getLangOpts().CPlusPlus1117565? diag::warn_cxx98_compat_unelaborated_friend_type17566: diag::ext_unelaborated_friend_type)17567<< (unsigned)RD->getTagKind() << T17568<< FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),17569InsertionText);17570} else {17571Diag(FriendLoc, getLangOpts().CPlusPlus1117572? diag::warn_cxx98_compat_nonclass_type_friend17573: diag::ext_nonclass_type_friend)17574<< T << DS.getSourceRange();17575}17576}1757717578// C++98 [class.friend]p1: A friend of a class is a function17579// or class that is not a member of the class . . .17580// This is fixed in DR77, which just barely didn't make the C++0317581// deadline. It's also a very silly restriction that seriously17582// affects inner classes and which nobody else seems to implement;17583// thus we never diagnose it, not even in -pedantic.17584//17585// But note that we could warn about it: it's always useless to17586// friend one of your own members (it's not, however, worthless to17587// friend a member of an arbitrary specialization of your template).1758817589Decl *D;17590if (!TempParams.empty())17591D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,17592FriendLoc);17593else17594D = FriendDecl::Create(Context, CurContext, TSI->getTypeLoc().getBeginLoc(),17595TSI, FriendLoc);1759617597if (!D)17598return nullptr;1759917600D->setAccess(AS_public);17601CurContext->addDecl(D);1760217603return D;17604}1760517606NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,17607MultiTemplateParamsArg TemplateParams) {17608const DeclSpec &DS = D.getDeclSpec();1760917610assert(DS.isFriendSpecified());17611assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);1761217613SourceLocation Loc = D.getIdentifierLoc();17614TypeSourceInfo *TInfo = GetTypeForDeclarator(D);1761517616// C++ [class.friend]p117617// A friend of a class is a function or class....17618// Note that this sees through typedefs, which is intended.17619// It *doesn't* see through dependent types, which is correct17620// according to [temp.arg.type]p3:17621// If a declaration acquires a function type through a17622// type dependent on a template-parameter and this causes17623// a declaration that does not use the syntactic form of a17624// function declarator to have a function type, the program17625// is ill-formed.17626if (!TInfo->getType()->isFunctionType()) {17627Diag(Loc, diag::err_unexpected_friend);1762817629// It might be worthwhile to try to recover by creating an17630// appropriate declaration.17631return nullptr;17632}1763317634// C++ [namespace.memdef]p317635// - If a friend declaration in a non-local class first declares a17636// class or function, the friend class or function is a member17637// of the innermost enclosing namespace.17638// - The name of the friend is not found by simple name lookup17639// until a matching declaration is provided in that namespace17640// scope (either before or after the class declaration granting17641// friendship).17642// - If a friend function is called, its name may be found by the17643// name lookup that considers functions from namespaces and17644// classes associated with the types of the function arguments.17645// - When looking for a prior declaration of a class or a function17646// declared as a friend, scopes outside the innermost enclosing17647// namespace scope are not considered.1764817649CXXScopeSpec &SS = D.getCXXScopeSpec();17650DeclarationNameInfo NameInfo = GetNameForDeclarator(D);17651assert(NameInfo.getName());1765217653// Check for unexpanded parameter packs.17654if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||17655DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||17656DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))17657return nullptr;1765817659// The context we found the declaration in, or in which we should17660// create the declaration.17661DeclContext *DC;17662Scope *DCScope = S;17663LookupResult Previous(*this, NameInfo, LookupOrdinaryName,17664RedeclarationKind::ForExternalRedeclaration);1766517666bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;1766717668// There are five cases here.17669// - There's no scope specifier and we're in a local class. Only look17670// for functions declared in the immediately-enclosing block scope.17671// We recover from invalid scope qualifiers as if they just weren't there.17672FunctionDecl *FunctionContainingLocalClass = nullptr;17673if ((SS.isInvalid() || !SS.isSet()) &&17674(FunctionContainingLocalClass =17675cast<CXXRecordDecl>(CurContext)->isLocalClass())) {17676// C++11 [class.friend]p11:17677// If a friend declaration appears in a local class and the name17678// specified is an unqualified name, a prior declaration is17679// looked up without considering scopes that are outside the17680// innermost enclosing non-class scope. For a friend function17681// declaration, if there is no prior declaration, the program is17682// ill-formed.1768317684// Find the innermost enclosing non-class scope. This is the block17685// scope containing the local class definition (or for a nested class,17686// the outer local class).17687DCScope = S->getFnParent();1768817689// Look up the function name in the scope.17690Previous.clear(LookupLocalFriendName);17691LookupName(Previous, S, /*AllowBuiltinCreation*/false);1769217693if (!Previous.empty()) {17694// All possible previous declarations must have the same context:17695// either they were declared at block scope or they are members of17696// one of the enclosing local classes.17697DC = Previous.getRepresentativeDecl()->getDeclContext();17698} else {17699// This is ill-formed, but provide the context that we would have17700// declared the function in, if we were permitted to, for error recovery.17701DC = FunctionContainingLocalClass;17702}17703adjustContextForLocalExternDecl(DC);1770417705// - There's no scope specifier, in which case we just go to the17706// appropriate scope and look for a function or function template17707// there as appropriate.17708} else if (SS.isInvalid() || !SS.isSet()) {17709// C++11 [namespace.memdef]p3:17710// If the name in a friend declaration is neither qualified nor17711// a template-id and the declaration is a function or an17712// elaborated-type-specifier, the lookup to determine whether17713// the entity has been previously declared shall not consider17714// any scopes outside the innermost enclosing namespace.1771517716// Find the appropriate context according to the above.17717DC = CurContext;1771817719// Skip class contexts. If someone can cite chapter and verse17720// for this behavior, that would be nice --- it's what GCC and17721// EDG do, and it seems like a reasonable intent, but the spec17722// really only says that checks for unqualified existing17723// declarations should stop at the nearest enclosing namespace,17724// not that they should only consider the nearest enclosing17725// namespace.17726while (DC->isRecord())17727DC = DC->getParent();1772817729DeclContext *LookupDC = DC->getNonTransparentContext();17730while (true) {17731LookupQualifiedName(Previous, LookupDC);1773217733if (!Previous.empty()) {17734DC = LookupDC;17735break;17736}1773717738if (isTemplateId) {17739if (isa<TranslationUnitDecl>(LookupDC)) break;17740} else {17741if (LookupDC->isFileContext()) break;17742}17743LookupDC = LookupDC->getParent();17744}1774517746DCScope = getScopeForDeclContext(S, DC);1774717748// - There's a non-dependent scope specifier, in which case we17749// compute it and do a previous lookup there for a function17750// or function template.17751} else if (!SS.getScopeRep()->isDependent()) {17752DC = computeDeclContext(SS);17753if (!DC) return nullptr;1775417755if (RequireCompleteDeclContext(SS, DC)) return nullptr;1775617757LookupQualifiedName(Previous, DC);1775817759// C++ [class.friend]p1: A friend of a class is a function or17760// class that is not a member of the class . . .17761if (DC->Equals(CurContext))17762Diag(DS.getFriendSpecLoc(),17763getLangOpts().CPlusPlus11 ?17764diag::warn_cxx98_compat_friend_is_member :17765diag::err_friend_is_member);1776617767// - There's a scope specifier that does not match any template17768// parameter lists, in which case we use some arbitrary context,17769// create a method or method template, and wait for instantiation.17770// - There's a scope specifier that does match some template17771// parameter lists, which we don't handle right now.17772} else {17773DC = CurContext;17774assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");17775}1777617777if (!DC->isRecord()) {17778int DiagArg = -1;17779switch (D.getName().getKind()) {17780case UnqualifiedIdKind::IK_ConstructorTemplateId:17781case UnqualifiedIdKind::IK_ConstructorName:17782DiagArg = 0;17783break;17784case UnqualifiedIdKind::IK_DestructorName:17785DiagArg = 1;17786break;17787case UnqualifiedIdKind::IK_ConversionFunctionId:17788DiagArg = 2;17789break;17790case UnqualifiedIdKind::IK_DeductionGuideName:17791DiagArg = 3;17792break;17793case UnqualifiedIdKind::IK_Identifier:17794case UnqualifiedIdKind::IK_ImplicitSelfParam:17795case UnqualifiedIdKind::IK_LiteralOperatorId:17796case UnqualifiedIdKind::IK_OperatorFunctionId:17797case UnqualifiedIdKind::IK_TemplateId:17798break;17799}17800// This implies that it has to be an operator or function.17801if (DiagArg >= 0) {17802Diag(Loc, diag::err_introducing_special_friend) << DiagArg;17803return nullptr;17804}17805}1780617807// FIXME: This is an egregious hack to cope with cases where the scope stack17808// does not contain the declaration context, i.e., in an out-of-line17809// definition of a class.17810Scope FakeDCScope(S, Scope::DeclScope, Diags);17811if (!DCScope) {17812FakeDCScope.setEntity(DC);17813DCScope = &FakeDCScope;17814}1781517816bool AddToScope = true;17817NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,17818TemplateParams, AddToScope);17819if (!ND) return nullptr;1782017821assert(ND->getLexicalDeclContext() == CurContext);1782217823// If we performed typo correction, we might have added a scope specifier17824// and changed the decl context.17825DC = ND->getDeclContext();1782617827// Add the function declaration to the appropriate lookup tables,17828// adjusting the redeclarations list as necessary. We don't17829// want to do this yet if the friending class is dependent.17830//17831// Also update the scope-based lookup if the target context's17832// lookup context is in lexical scope.17833if (!CurContext->isDependentContext()) {17834DC = DC->getRedeclContext();17835DC->makeDeclVisibleInContext(ND);17836if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))17837PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);17838}1783917840FriendDecl *FrD = FriendDecl::Create(Context, CurContext,17841D.getIdentifierLoc(), ND,17842DS.getFriendSpecLoc());17843FrD->setAccess(AS_public);17844CurContext->addDecl(FrD);1784517846if (ND->isInvalidDecl()) {17847FrD->setInvalidDecl();17848} else {17849if (DC->isRecord()) CheckFriendAccess(ND);1785017851FunctionDecl *FD;17852if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))17853FD = FTD->getTemplatedDecl();17854else17855FD = cast<FunctionDecl>(ND);1785617857// C++ [class.friend]p6:17858// A function may be defined in a friend declaration of a class if and17859// only if the class is a non-local class, and the function name is17860// unqualified.17861if (D.isFunctionDefinition()) {17862// Qualified friend function definition.17863if (SS.isNotEmpty()) {17864// FIXME: We should only do this if the scope specifier names the17865// innermost enclosing namespace; otherwise the fixit changes the17866// meaning of the code.17867SemaDiagnosticBuilder DB =17868Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);1786917870DB << SS.getScopeRep();17871if (DC->isFileContext())17872DB << FixItHint::CreateRemoval(SS.getRange());1787317874// Friend function defined in a local class.17875} else if (FunctionContainingLocalClass) {17876Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);1787717878// Per [basic.pre]p4, a template-id is not a name. Therefore, if we have17879// a template-id, the function name is not unqualified because these is17880// no name. While the wording requires some reading in-between the17881// lines, GCC, MSVC, and EDG all consider a friend function17882// specialization definitions // to be de facto explicit specialization17883// and diagnose them as such.17884} else if (isTemplateId) {17885Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);17886}17887}1788817889// C++11 [dcl.fct.default]p4: If a friend declaration specifies a17890// default argument expression, that declaration shall be a definition17891// and shall be the only declaration of the function or function17892// template in the translation unit.17893if (functionDeclHasDefaultArgument(FD)) {17894// We can't look at FD->getPreviousDecl() because it may not have been set17895// if we're in a dependent context. If the function is known to be a17896// redeclaration, we will have narrowed Previous down to the right decl.17897if (D.isRedeclaration()) {17898Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);17899Diag(Previous.getRepresentativeDecl()->getLocation(),17900diag::note_previous_declaration);17901} else if (!D.isFunctionDefinition())17902Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);17903}1790417905// Mark templated-scope function declarations as unsupported.17906if (FD->getNumTemplateParameterLists() && SS.isValid()) {17907Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)17908<< SS.getScopeRep() << SS.getRange()17909<< cast<CXXRecordDecl>(CurContext);17910FrD->setUnsupportedFriend(true);17911}17912}1791317914warnOnReservedIdentifier(ND);1791517916return ND;17917}1791817919void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,17920StringLiteral *Message) {17921AdjustDeclIfTemplate(Dcl);1792217923FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);17924if (!Fn) {17925Diag(DelLoc, diag::err_deleted_non_function);17926return;17927}1792817929// Deleted function does not have a body.17930Fn->setWillHaveBody(false);1793117932if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {17933// Don't consider the implicit declaration we generate for explicit17934// specializations. FIXME: Do not generate these implicit declarations.17935if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||17936Prev->getPreviousDecl()) &&17937!Prev->isDefined()) {17938Diag(DelLoc, diag::err_deleted_decl_not_first);17939Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),17940Prev->isImplicit() ? diag::note_previous_implicit_declaration17941: diag::note_previous_declaration);17942// We can't recover from this; the declaration might have already17943// been used.17944Fn->setInvalidDecl();17945return;17946}1794717948// To maintain the invariant that functions are only deleted on their first17949// declaration, mark the implicitly-instantiated declaration of the17950// explicitly-specialized function as deleted instead of marking the17951// instantiated redeclaration.17952Fn = Fn->getCanonicalDecl();17953}1795417955// dllimport/dllexport cannot be deleted.17956if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {17957Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;17958Fn->setInvalidDecl();17959}1796017961// C++11 [basic.start.main]p3:17962// A program that defines main as deleted [...] is ill-formed.17963if (Fn->isMain())17964Diag(DelLoc, diag::err_deleted_main);1796517966// C++11 [dcl.fct.def.delete]p4:17967// A deleted function is implicitly inline.17968Fn->setImplicitlyInline();17969Fn->setDeletedAsWritten(true, Message);17970}1797117972void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {17973if (!Dcl || Dcl->isInvalidDecl())17974return;1797517976auto *FD = dyn_cast<FunctionDecl>(Dcl);17977if (!FD) {17978if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {17979if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {17980Diag(DefaultLoc, diag::err_defaulted_comparison_template);17981return;17982}17983}1798417985Diag(DefaultLoc, diag::err_default_special_members)17986<< getLangOpts().CPlusPlus20;17987return;17988}1798917990// Reject if this can't possibly be a defaultable function.17991DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);17992if (!DefKind &&17993// A dependent function that doesn't locally look defaultable can17994// still instantiate to a defaultable function if it's a constructor17995// or assignment operator.17996(!FD->isDependentContext() ||17997(!isa<CXXConstructorDecl>(FD) &&17998FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {17999Diag(DefaultLoc, diag::err_default_special_members)18000<< getLangOpts().CPlusPlus20;18001return;18002}1800318004// Issue compatibility warning. We already warned if the operator is18005// 'operator<=>' when parsing the '<=>' token.18006if (DefKind.isComparison() &&18007DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {18008Diag(DefaultLoc, getLangOpts().CPlusPlus2018009? diag::warn_cxx17_compat_defaulted_comparison18010: diag::ext_defaulted_comparison);18011}1801218013FD->setDefaulted();18014FD->setExplicitlyDefaulted();18015FD->setDefaultLoc(DefaultLoc);1801618017// Defer checking functions that are defaulted in a dependent context.18018if (FD->isDependentContext())18019return;1802018021// Unset that we will have a body for this function. We might not,18022// if it turns out to be trivial, and we don't need this marking now18023// that we've marked it as defaulted.18024FD->setWillHaveBody(false);1802518026if (DefKind.isComparison()) {18027// If this comparison's defaulting occurs within the definition of its18028// lexical class context, we have to do the checking when complete.18029if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))18030if (!RD->isCompleteDefinition())18031return;18032}1803318034// If this member fn was defaulted on its first declaration, we will have18035// already performed the checking in CheckCompletedCXXClass. Such a18036// declaration doesn't trigger an implicit definition.18037if (isa<CXXMethodDecl>(FD)) {18038const FunctionDecl *Primary = FD;18039if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())18040// Ask the template instantiation pattern that actually had the18041// '= default' on it.18042Primary = Pattern;18043if (Primary->getCanonicalDecl()->isDefaulted())18044return;18045}1804618047if (DefKind.isComparison()) {18048if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))18049FD->setInvalidDecl();18050else18051DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());18052} else {18053auto *MD = cast<CXXMethodDecl>(FD);1805418055if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),18056DefaultLoc))18057MD->setInvalidDecl();18058else18059DefineDefaultedFunction(*this, MD, DefaultLoc);18060}18061}1806218063static void SearchForReturnInStmt(Sema &Self, Stmt *S) {18064for (Stmt *SubStmt : S->children()) {18065if (!SubStmt)18066continue;18067if (isa<ReturnStmt>(SubStmt))18068Self.Diag(SubStmt->getBeginLoc(),18069diag::err_return_in_constructor_handler);18070if (!isa<Expr>(SubStmt))18071SearchForReturnInStmt(Self, SubStmt);18072}18073}1807418075void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {18076for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {18077CXXCatchStmt *Handler = TryBlock->getHandler(I);18078SearchForReturnInStmt(*this, Handler);18079}18080}1808118082void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,18083StringLiteral *DeletedMessage) {18084switch (BodyKind) {18085case FnBodyKind::Delete:18086SetDeclDeleted(D, Loc, DeletedMessage);18087break;18088case FnBodyKind::Default:18089SetDeclDefaulted(D, Loc);18090break;18091case FnBodyKind::Other:18092llvm_unreachable(18093"Parsed function body should be '= delete;' or '= default;'");18094}18095}1809618097bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,18098const CXXMethodDecl *Old) {18099const auto *NewFT = New->getType()->castAs<FunctionProtoType>();18100const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();1810118102if (OldFT->hasExtParameterInfos()) {18103for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)18104// A parameter of the overriding method should be annotated with noescape18105// if the corresponding parameter of the overridden method is annotated.18106if (OldFT->getExtParameterInfo(I).isNoEscape() &&18107!NewFT->getExtParameterInfo(I).isNoEscape()) {18108Diag(New->getParamDecl(I)->getLocation(),18109diag::warn_overriding_method_missing_noescape);18110Diag(Old->getParamDecl(I)->getLocation(),18111diag::note_overridden_marked_noescape);18112}18113}1811418115// SME attributes must match when overriding a function declaration.18116if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {18117Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)18118<< New << New->getType() << Old->getType();18119Diag(Old->getLocation(), diag::note_overridden_virtual_function);18120return true;18121}1812218123// Virtual overrides must have the same code_seg.18124const auto *OldCSA = Old->getAttr<CodeSegAttr>();18125const auto *NewCSA = New->getAttr<CodeSegAttr>();18126if ((NewCSA || OldCSA) &&18127(!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {18128Diag(New->getLocation(), diag::err_mismatched_code_seg_override);18129Diag(Old->getLocation(), diag::note_previous_declaration);18130return true;18131}1813218133// Virtual overrides: check for matching effects.18134if (Context.hasAnyFunctionEffects()) {18135const auto OldFX = Old->getFunctionEffects();18136const auto NewFXOrig = New->getFunctionEffects();1813718138if (OldFX != NewFXOrig) {18139FunctionEffectSet NewFX(NewFXOrig);18140const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);18141FunctionEffectSet::Conflicts Errs;18142for (const auto &Diff : Diffs) {18143switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {18144case FunctionEffectDiff::OverrideResult::NoAction:18145break;18146case FunctionEffectDiff::OverrideResult::Warn:18147Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)18148<< Diff.effectName();18149Diag(Old->getLocation(), diag::note_overridden_virtual_function)18150<< Old->getReturnTypeSourceRange();18151break;18152case FunctionEffectDiff::OverrideResult::Merge: {18153NewFX.insert(Diff.Old, Errs);18154const auto *NewFT = New->getType()->castAs<FunctionProtoType>();18155FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();18156EPI.FunctionEffects = FunctionEffectsRef(NewFX);18157QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),18158NewFT->getParamTypes(), EPI);18159New->setType(ModQT);18160break;18161}18162}18163}18164if (!Errs.empty())18165diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),18166Old->getLocation());18167}18168}1816918170CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();1817118172// If the calling conventions match, everything is fine18173if (NewCC == OldCC)18174return false;1817518176// If the calling conventions mismatch because the new function is static,18177// suppress the calling convention mismatch error; the error about static18178// function override (err_static_overrides_virtual from18179// Sema::CheckFunctionDeclaration) is more clear.18180if (New->getStorageClass() == SC_Static)18181return false;1818218183Diag(New->getLocation(),18184diag::err_conflicting_overriding_cc_attributes)18185<< New->getDeclName() << New->getType() << Old->getType();18186Diag(Old->getLocation(), diag::note_overridden_virtual_function);18187return true;18188}1818918190bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,18191const CXXMethodDecl *Old) {18192// CWG255318193// A virtual function shall not be an explicit object member function.18194if (!New->isExplicitObjectMemberFunction())18195return true;18196Diag(New->getParamDecl(0)->getBeginLoc(),18197diag::err_explicit_object_parameter_nonmember)18198<< New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;18199Diag(Old->getLocation(), diag::note_overridden_virtual_function);18200New->setInvalidDecl();18201return false;18202}1820318204bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,18205const CXXMethodDecl *Old) {18206QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();18207QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();1820818209if (Context.hasSameType(NewTy, OldTy) ||18210NewTy->isDependentType() || OldTy->isDependentType())18211return false;1821218213// Check if the return types are covariant18214QualType NewClassTy, OldClassTy;1821518216/// Both types must be pointers or references to classes.18217if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {18218if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {18219NewClassTy = NewPT->getPointeeType();18220OldClassTy = OldPT->getPointeeType();18221}18222} else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {18223if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {18224if (NewRT->getTypeClass() == OldRT->getTypeClass()) {18225NewClassTy = NewRT->getPointeeType();18226OldClassTy = OldRT->getPointeeType();18227}18228}18229}1823018231// The return types aren't either both pointers or references to a class type.18232if (NewClassTy.isNull()) {18233Diag(New->getLocation(),18234diag::err_different_return_type_for_overriding_virtual_function)18235<< New->getDeclName() << NewTy << OldTy18236<< New->getReturnTypeSourceRange();18237Diag(Old->getLocation(), diag::note_overridden_virtual_function)18238<< Old->getReturnTypeSourceRange();1823918240return true;18241}1824218243if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {18244// C++14 [class.virtual]p8:18245// If the class type in the covariant return type of D::f differs from18246// that of B::f, the class type in the return type of D::f shall be18247// complete at the point of declaration of D::f or shall be the class18248// type D.18249if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {18250if (!RT->isBeingDefined() &&18251RequireCompleteType(New->getLocation(), NewClassTy,18252diag::err_covariant_return_incomplete,18253New->getDeclName()))18254return true;18255}1825618257// Check if the new class derives from the old class.18258if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {18259Diag(New->getLocation(), diag::err_covariant_return_not_derived)18260<< New->getDeclName() << NewTy << OldTy18261<< New->getReturnTypeSourceRange();18262Diag(Old->getLocation(), diag::note_overridden_virtual_function)18263<< Old->getReturnTypeSourceRange();18264return true;18265}1826618267// Check if we the conversion from derived to base is valid.18268if (CheckDerivedToBaseConversion(18269NewClassTy, OldClassTy,18270diag::err_covariant_return_inaccessible_base,18271diag::err_covariant_return_ambiguous_derived_to_base_conv,18272New->getLocation(), New->getReturnTypeSourceRange(),18273New->getDeclName(), nullptr)) {18274// FIXME: this note won't trigger for delayed access control18275// diagnostics, and it's impossible to get an undelayed error18276// here from access control during the original parse because18277// the ParsingDeclSpec/ParsingDeclarator are still in scope.18278Diag(Old->getLocation(), diag::note_overridden_virtual_function)18279<< Old->getReturnTypeSourceRange();18280return true;18281}18282}1828318284// The qualifiers of the return types must be the same.18285if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {18286Diag(New->getLocation(),18287diag::err_covariant_return_type_different_qualifications)18288<< New->getDeclName() << NewTy << OldTy18289<< New->getReturnTypeSourceRange();18290Diag(Old->getLocation(), diag::note_overridden_virtual_function)18291<< Old->getReturnTypeSourceRange();18292return true;18293}182941829518296// The new class type must have the same or less qualifiers as the old type.18297if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {18298Diag(New->getLocation(),18299diag::err_covariant_return_type_class_type_more_qualified)18300<< New->getDeclName() << NewTy << OldTy18301<< New->getReturnTypeSourceRange();18302Diag(Old->getLocation(), diag::note_overridden_virtual_function)18303<< Old->getReturnTypeSourceRange();18304return true;18305}1830618307return false;18308}1830918310bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {18311SourceLocation EndLoc = InitRange.getEnd();18312if (EndLoc.isValid())18313Method->setRangeEnd(EndLoc);1831418315if (Method->isVirtual() || Method->getParent()->isDependentContext()) {18316Method->setIsPureVirtual();18317return false;18318}1831918320if (!Method->isInvalidDecl())18321Diag(Method->getLocation(), diag::err_non_virtual_pure)18322<< Method->getDeclName() << InitRange;18323return true;18324}1832518326void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {18327if (D->getFriendObjectKind())18328Diag(D->getLocation(), diag::err_pure_friend);18329else if (auto *M = dyn_cast<CXXMethodDecl>(D))18330CheckPureMethod(M, ZeroLoc);18331else18332Diag(D->getLocation(), diag::err_illegal_initializer);18333}1833418335/// Invoked when we are about to parse an initializer for the declaration18336/// 'Dcl'.18337///18338/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a18339/// static data member of class X, names should be looked up in the scope of18340/// class X. If the declaration had a scope specifier, a scope will have18341/// been created and passed in for this purpose. Otherwise, S will be null.18342void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {18343assert(D && !D->isInvalidDecl());1834418345// We will always have a nested name specifier here, but this declaration18346// might not be out of line if the specifier names the current namespace:18347// extern int n;18348// int ::n = 0;18349if (S && D->isOutOfLine())18350EnterDeclaratorContext(S, D->getDeclContext());1835118352PushExpressionEvaluationContext(18353ExpressionEvaluationContext::PotentiallyEvaluated, D);18354}1835518356void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {18357assert(D);1835818359if (S && D->isOutOfLine())18360ExitDeclaratorContext(S);1836118362if (getLangOpts().CPlusPlus23) {18363// An expression or conversion is 'manifestly constant-evaluated' if it is:18364// [...]18365// - the initializer of a variable that is usable in constant expressions or18366// has constant initialization.18367if (auto *VD = dyn_cast<VarDecl>(D);18368VD && (VD->isUsableInConstantExpressions(Context) ||18369VD->hasConstantInitialization())) {18370// An expression or conversion is in an 'immediate function context' if it18371// is potentially evaluated and either:18372// [...]18373// - it is a subexpression of a manifestly constant-evaluated expression18374// or conversion.18375ExprEvalContexts.back().InImmediateFunctionContext = true;18376}18377}1837818379// Unless the initializer is in an immediate function context (as determined18380// above), this will evaluate all contained immediate function calls as18381// constant expressions. If the initializer IS an immediate function context,18382// the initializer has been determined to be a constant expression, and all18383// such evaluations will be elided (i.e., as if we "knew the whole time" that18384// it was a constant expression).18385PopExpressionEvaluationContext();18386}1838718388DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {18389// C++ 6.4p2:18390// The declarator shall not specify a function or an array.18391// The type-specifier-seq shall not contain typedef and shall not declare a18392// new class or enumeration.18393assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&18394"Parser allowed 'typedef' as storage class of condition decl.");1839518396Decl *Dcl = ActOnDeclarator(S, D);18397if (!Dcl)18398return true;1839918400if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.18401Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)18402<< D.getSourceRange();18403return true;18404}1840518406if (auto *VD = dyn_cast<VarDecl>(Dcl))18407VD->setCXXCondDecl();1840818409return Dcl;18410}1841118412void Sema::LoadExternalVTableUses() {18413if (!ExternalSource)18414return;1841518416SmallVector<ExternalVTableUse, 4> VTables;18417ExternalSource->ReadUsedVTables(VTables);18418SmallVector<VTableUse, 4> NewUses;18419for (unsigned I = 0, N = VTables.size(); I != N; ++I) {18420llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos18421= VTablesUsed.find(VTables[I].Record);18422// Even if a definition wasn't required before, it may be required now.18423if (Pos != VTablesUsed.end()) {18424if (!Pos->second && VTables[I].DefinitionRequired)18425Pos->second = true;18426continue;18427}1842818429VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;18430NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));18431}1843218433VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());18434}1843518436void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,18437bool DefinitionRequired) {18438// Ignore any vtable uses in unevaluated operands or for classes that do18439// not have a vtable.18440if (!Class->isDynamicClass() || Class->isDependentContext() ||18441CurContext->isDependentContext() || isUnevaluatedContext())18442return;18443// Do not mark as used if compiling for the device outside of the target18444// region.18445if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&18446!OpenMP().isInOpenMPDeclareTargetContext() &&18447!OpenMP().isInOpenMPTargetExecutionDirective()) {18448if (!DefinitionRequired)18449MarkVirtualMembersReferenced(Loc, Class);18450return;18451}1845218453// Try to insert this class into the map.18454LoadExternalVTableUses();18455Class = Class->getCanonicalDecl();18456std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>18457Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));18458if (!Pos.second) {18459// If we already had an entry, check to see if we are promoting this vtable18460// to require a definition. If so, we need to reappend to the VTableUses18461// list, since we may have already processed the first entry.18462if (DefinitionRequired && !Pos.first->second) {18463Pos.first->second = true;18464} else {18465// Otherwise, we can early exit.18466return;18467}18468} else {18469// The Microsoft ABI requires that we perform the destructor body18470// checks (i.e. operator delete() lookup) when the vtable is marked used, as18471// the deleting destructor is emitted with the vtable, not with the18472// destructor definition as in the Itanium ABI.18473if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {18474CXXDestructorDecl *DD = Class->getDestructor();18475if (DD && DD->isVirtual() && !DD->isDeleted()) {18476if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {18477// If this is an out-of-line declaration, marking it referenced will18478// not do anything. Manually call CheckDestructor to look up operator18479// delete().18480ContextRAII SavedContext(*this, DD);18481CheckDestructor(DD);18482} else {18483MarkFunctionReferenced(Loc, Class->getDestructor());18484}18485}18486}18487}1848818489// Local classes need to have their virtual members marked18490// immediately. For all other classes, we mark their virtual members18491// at the end of the translation unit.18492if (Class->isLocalClass())18493MarkVirtualMembersReferenced(Loc, Class->getDefinition());18494else18495VTableUses.push_back(std::make_pair(Class, Loc));18496}1849718498bool Sema::DefineUsedVTables() {18499LoadExternalVTableUses();18500if (VTableUses.empty())18501return false;1850218503// Note: The VTableUses vector could grow as a result of marking18504// the members of a class as "used", so we check the size each18505// time through the loop and prefer indices (which are stable) to18506// iterators (which are not).18507bool DefinedAnything = false;18508for (unsigned I = 0; I != VTableUses.size(); ++I) {18509CXXRecordDecl *Class = VTableUses[I].first->getDefinition();18510if (!Class)18511continue;18512TemplateSpecializationKind ClassTSK =18513Class->getTemplateSpecializationKind();1851418515SourceLocation Loc = VTableUses[I].second;1851618517bool DefineVTable = true;1851818519const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);18520// V-tables for non-template classes with an owning module are always18521// uniquely emitted in that module.18522if (Class->isInCurrentModuleUnit()) {18523DefineVTable = true;18524} else if (KeyFunction && !KeyFunction->hasBody()) {18525// If this class has a key function, but that key function is18526// defined in another translation unit, we don't need to emit the18527// vtable even though we're using it.18528// The key function is in another translation unit.18529DefineVTable = false;18530TemplateSpecializationKind TSK =18531KeyFunction->getTemplateSpecializationKind();18532assert(TSK != TSK_ExplicitInstantiationDefinition &&18533TSK != TSK_ImplicitInstantiation &&18534"Instantiations don't have key functions");18535(void)TSK;18536} else if (!KeyFunction) {18537// If we have a class with no key function that is the subject18538// of an explicit instantiation declaration, suppress the18539// vtable; it will live with the explicit instantiation18540// definition.18541bool IsExplicitInstantiationDeclaration =18542ClassTSK == TSK_ExplicitInstantiationDeclaration;18543for (auto *R : Class->redecls()) {18544TemplateSpecializationKind TSK18545= cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();18546if (TSK == TSK_ExplicitInstantiationDeclaration)18547IsExplicitInstantiationDeclaration = true;18548else if (TSK == TSK_ExplicitInstantiationDefinition) {18549IsExplicitInstantiationDeclaration = false;18550break;18551}18552}1855318554if (IsExplicitInstantiationDeclaration)18555DefineVTable = false;18556}1855718558// The exception specifications for all virtual members may be needed even18559// if we are not providing an authoritative form of the vtable in this TU.18560// We may choose to emit it available_externally anyway.18561if (!DefineVTable) {18562MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);18563continue;18564}1856518566// Mark all of the virtual members of this class as referenced, so18567// that we can build a vtable. Then, tell the AST consumer that a18568// vtable for this class is required.18569DefinedAnything = true;18570MarkVirtualMembersReferenced(Loc, Class);18571CXXRecordDecl *Canonical = Class->getCanonicalDecl();18572if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())18573Consumer.HandleVTable(Class);1857418575// Warn if we're emitting a weak vtable. The vtable will be weak if there is18576// no key function or the key function is inlined. Don't warn in C++ ABIs18577// that lack key functions, since the user won't be able to make one.18578if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&18579Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&18580ClassTSK != TSK_ExplicitInstantiationDefinition) {18581const FunctionDecl *KeyFunctionDef = nullptr;18582if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&18583KeyFunctionDef->isInlined()))18584Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;18585}18586}18587VTableUses.clear();1858818589return DefinedAnything;18590}1859118592void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,18593const CXXRecordDecl *RD) {18594for (const auto *I : RD->methods())18595if (I->isVirtual() && !I->isPureVirtual())18596ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());18597}1859818599void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,18600const CXXRecordDecl *RD,18601bool ConstexprOnly) {18602// Mark all functions which will appear in RD's vtable as used.18603CXXFinalOverriderMap FinalOverriders;18604RD->getFinalOverriders(FinalOverriders);18605for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),18606E = FinalOverriders.end();18607I != E; ++I) {18608for (OverridingMethods::const_iterator OI = I->second.begin(),18609OE = I->second.end();18610OI != OE; ++OI) {18611assert(OI->second.size() > 0 && "no final overrider");18612CXXMethodDecl *Overrider = OI->second.front().Method;1861318614// C++ [basic.def.odr]p2:18615// [...] A virtual member function is used if it is not pure. [...]18616if (!Overrider->isPureVirtual() &&18617(!ConstexprOnly || Overrider->isConstexpr()))18618MarkFunctionReferenced(Loc, Overrider);18619}18620}1862118622// Only classes that have virtual bases need a VTT.18623if (RD->getNumVBases() == 0)18624return;1862518626for (const auto &I : RD->bases()) {18627const auto *Base =18628cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());18629if (Base->getNumVBases() == 0)18630continue;18631MarkVirtualMembersReferenced(Loc, Base);18632}18633}1863418635static18636void DelegatingCycleHelper(CXXConstructorDecl* Ctor,18637llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,18638llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,18639llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,18640Sema &S) {18641if (Ctor->isInvalidDecl())18642return;1864318644CXXConstructorDecl *Target = Ctor->getTargetConstructor();1864518646// Target may not be determinable yet, for instance if this is a dependent18647// call in an uninstantiated template.18648if (Target) {18649const FunctionDecl *FNTarget = nullptr;18650(void)Target->hasBody(FNTarget);18651Target = const_cast<CXXConstructorDecl*>(18652cast_or_null<CXXConstructorDecl>(FNTarget));18653}1865418655CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),18656// Avoid dereferencing a null pointer here.18657*TCanonical = Target? Target->getCanonicalDecl() : nullptr;1865818659if (!Current.insert(Canonical).second)18660return;1866118662// We know that beyond here, we aren't chaining into a cycle.18663if (!Target || !Target->isDelegatingConstructor() ||18664Target->isInvalidDecl() || Valid.count(TCanonical)) {18665Valid.insert(Current.begin(), Current.end());18666Current.clear();18667// We've hit a cycle.18668} else if (TCanonical == Canonical || Invalid.count(TCanonical) ||18669Current.count(TCanonical)) {18670// If we haven't diagnosed this cycle yet, do so now.18671if (!Invalid.count(TCanonical)) {18672S.Diag((*Ctor->init_begin())->getSourceLocation(),18673diag::warn_delegating_ctor_cycle)18674<< Ctor;1867518676// Don't add a note for a function delegating directly to itself.18677if (TCanonical != Canonical)18678S.Diag(Target->getLocation(), diag::note_it_delegates_to);1867918680CXXConstructorDecl *C = Target;18681while (C->getCanonicalDecl() != Canonical) {18682const FunctionDecl *FNTarget = nullptr;18683(void)C->getTargetConstructor()->hasBody(FNTarget);18684assert(FNTarget && "Ctor cycle through bodiless function");1868518686C = const_cast<CXXConstructorDecl*>(18687cast<CXXConstructorDecl>(FNTarget));18688S.Diag(C->getLocation(), diag::note_which_delegates_to);18689}18690}1869118692Invalid.insert(Current.begin(), Current.end());18693Current.clear();18694} else {18695DelegatingCycleHelper(Target, Valid, Invalid, Current, S);18696}18697}186981869918700void Sema::CheckDelegatingCtorCycles() {18701llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;1870218703for (DelegatingCtorDeclsType::iterator18704I = DelegatingCtorDecls.begin(ExternalSource.get()),18705E = DelegatingCtorDecls.end();18706I != E; ++I)18707DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);1870818709for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)18710(*CI)->setInvalidDecl();18711}1871218713namespace {18714/// AST visitor that finds references to the 'this' expression.18715class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {18716Sema &S;1871718718public:18719explicit FindCXXThisExpr(Sema &S) : S(S) { }1872018721bool VisitCXXThisExpr(CXXThisExpr *E) {18722S.Diag(E->getLocation(), diag::err_this_static_member_func)18723<< E->isImplicit();18724return false;18725}18726};18727}1872818729bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {18730TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();18731if (!TSInfo)18732return false;1873318734TypeLoc TL = TSInfo->getTypeLoc();18735FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();18736if (!ProtoTL)18737return false;1873818739// C++11 [expr.prim.general]p3:18740// [The expression this] shall not appear before the optional18741// cv-qualifier-seq and it shall not appear within the declaration of a18742// static member function (although its type and value category are defined18743// within a static member function as they are within a non-static member18744// function). [ Note: this is because declaration matching does not occur18745// until the complete declarator is known. - end note ]18746const FunctionProtoType *Proto = ProtoTL.getTypePtr();18747FindCXXThisExpr Finder(*this);1874818749// If the return type came after the cv-qualifier-seq, check it now.18750if (Proto->hasTrailingReturn() &&18751!Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))18752return true;1875318754// Check the exception specification.18755if (checkThisInStaticMemberFunctionExceptionSpec(Method))18756return true;1875718758// Check the trailing requires clause18759if (Expr *E = Method->getTrailingRequiresClause())18760if (!Finder.TraverseStmt(E))18761return true;1876218763return checkThisInStaticMemberFunctionAttributes(Method);18764}1876518766bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {18767TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();18768if (!TSInfo)18769return false;1877018771TypeLoc TL = TSInfo->getTypeLoc();18772FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();18773if (!ProtoTL)18774return false;1877518776const FunctionProtoType *Proto = ProtoTL.getTypePtr();18777FindCXXThisExpr Finder(*this);1877818779switch (Proto->getExceptionSpecType()) {18780case EST_Unparsed:18781case EST_Uninstantiated:18782case EST_Unevaluated:18783case EST_BasicNoexcept:18784case EST_NoThrow:18785case EST_DynamicNone:18786case EST_MSAny:18787case EST_None:18788break;1878918790case EST_DependentNoexcept:18791case EST_NoexceptFalse:18792case EST_NoexceptTrue:18793if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))18794return true;18795[[fallthrough]];1879618797case EST_Dynamic:18798for (const auto &E : Proto->exceptions()) {18799if (!Finder.TraverseType(E))18800return true;18801}18802break;18803}1880418805return false;18806}1880718808bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {18809FindCXXThisExpr Finder(*this);1881018811// Check attributes.18812for (const auto *A : Method->attrs()) {18813// FIXME: This should be emitted by tblgen.18814Expr *Arg = nullptr;18815ArrayRef<Expr *> Args;18816if (const auto *G = dyn_cast<GuardedByAttr>(A))18817Arg = G->getArg();18818else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))18819Arg = G->getArg();18820else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))18821Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());18822else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))18823Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());18824else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {18825Arg = ETLF->getSuccessValue();18826Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());18827} else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {18828Arg = STLF->getSuccessValue();18829Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());18830} else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))18831Arg = LR->getArg();18832else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))18833Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());18834else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))18835Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());18836else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))18837Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());18838else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))18839Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());18840else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))18841Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());1884218843if (Arg && !Finder.TraverseStmt(Arg))18844return true;1884518846for (unsigned I = 0, N = Args.size(); I != N; ++I) {18847if (!Finder.TraverseStmt(Args[I]))18848return true;18849}18850}1885118852return false;18853}1885418855void Sema::checkExceptionSpecification(18856bool IsTopLevel, ExceptionSpecificationType EST,18857ArrayRef<ParsedType> DynamicExceptions,18858ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,18859SmallVectorImpl<QualType> &Exceptions,18860FunctionProtoType::ExceptionSpecInfo &ESI) {18861Exceptions.clear();18862ESI.Type = EST;18863if (EST == EST_Dynamic) {18864Exceptions.reserve(DynamicExceptions.size());18865for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {18866// FIXME: Preserve type source info.18867QualType ET = GetTypeFromParser(DynamicExceptions[ei]);1886818869if (IsTopLevel) {18870SmallVector<UnexpandedParameterPack, 2> Unexpanded;18871collectUnexpandedParameterPacks(ET, Unexpanded);18872if (!Unexpanded.empty()) {18873DiagnoseUnexpandedParameterPacks(18874DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,18875Unexpanded);18876continue;18877}18878}1887918880// Check that the type is valid for an exception spec, and18881// drop it if not.18882if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))18883Exceptions.push_back(ET);18884}18885ESI.Exceptions = Exceptions;18886return;18887}1888818889if (isComputedNoexcept(EST)) {18890assert((NoexceptExpr->isTypeDependent() ||18891NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==18892Context.BoolTy) &&18893"Parser should have made sure that the expression is boolean");18894if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {18895ESI.Type = EST_BasicNoexcept;18896return;18897}1889818899ESI.NoexceptExpr = NoexceptExpr;18900return;18901}18902}1890318904void Sema::actOnDelayedExceptionSpecification(18905Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,18906ArrayRef<ParsedType> DynamicExceptions,18907ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {18908if (!D)18909return;1891018911// Dig out the function we're referring to.18912if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))18913D = FTD->getTemplatedDecl();1891418915FunctionDecl *FD = dyn_cast<FunctionDecl>(D);18916if (!FD)18917return;1891818919// Check the exception specification.18920llvm::SmallVector<QualType, 4> Exceptions;18921FunctionProtoType::ExceptionSpecInfo ESI;18922checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,18923DynamicExceptionRanges, NoexceptExpr, Exceptions,18924ESI);1892518926// Update the exception specification on the function type.18927Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);1892818929if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {18930if (MD->isStatic())18931checkThisInStaticMemberFunctionExceptionSpec(MD);1893218933if (MD->isVirtual()) {18934// Check overrides, which we previously had to delay.18935for (const CXXMethodDecl *O : MD->overridden_methods())18936CheckOverridingFunctionExceptionSpec(MD, O);18937}18938}18939}1894018941/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.18942///18943MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,18944SourceLocation DeclStart, Declarator &D,18945Expr *BitWidth,18946InClassInitStyle InitStyle,18947AccessSpecifier AS,18948const ParsedAttr &MSPropertyAttr) {18949const IdentifierInfo *II = D.getIdentifier();18950if (!II) {18951Diag(DeclStart, diag::err_anonymous_property);18952return nullptr;18953}18954SourceLocation Loc = D.getIdentifierLoc();1895518956TypeSourceInfo *TInfo = GetTypeForDeclarator(D);18957QualType T = TInfo->getType();18958if (getLangOpts().CPlusPlus) {18959CheckExtraCXXDefaultArguments(D);1896018961if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,18962UPPC_DataMemberType)) {18963D.setInvalidType();18964T = Context.IntTy;18965TInfo = Context.getTrivialTypeSourceInfo(T, Loc);18966}18967}1896818969DiagnoseFunctionSpecifiers(D.getDeclSpec());1897018971if (D.getDeclSpec().isInlineSpecified())18972Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)18973<< getLangOpts().CPlusPlus17;18974if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())18975Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),18976diag::err_invalid_thread)18977<< DeclSpec::getSpecifierName(TSCS);1897818979// Check to see if this name was declared as a member previously18980NamedDecl *PrevDecl = nullptr;18981LookupResult Previous(*this, II, Loc, LookupMemberName,18982RedeclarationKind::ForVisibleRedeclaration);18983LookupName(Previous, S);18984switch (Previous.getResultKind()) {18985case LookupResult::Found:18986case LookupResult::FoundUnresolvedValue:18987PrevDecl = Previous.getAsSingle<NamedDecl>();18988break;1898918990case LookupResult::FoundOverloaded:18991PrevDecl = Previous.getRepresentativeDecl();18992break;1899318994case LookupResult::NotFound:18995case LookupResult::NotFoundInCurrentInstantiation:18996case LookupResult::Ambiguous:18997break;18998}1899919000if (PrevDecl && PrevDecl->isTemplateParameter()) {19001// Maybe we will complain about the shadowed template parameter.19002DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);19003// Just pretend that we didn't see the previous declaration.19004PrevDecl = nullptr;19005}1900619007if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))19008PrevDecl = nullptr;1900919010SourceLocation TSSL = D.getBeginLoc();19011MSPropertyDecl *NewPD =19012MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,19013MSPropertyAttr.getPropertyDataGetter(),19014MSPropertyAttr.getPropertyDataSetter());19015ProcessDeclAttributes(TUScope, NewPD, D);19016NewPD->setAccess(AS);1901719018if (NewPD->isInvalidDecl())19019Record->setInvalidDecl();1902019021if (D.getDeclSpec().isModulePrivateSpecified())19022NewPD->setModulePrivate();1902319024if (NewPD->isInvalidDecl() && PrevDecl) {19025// Don't introduce NewFD into scope; there's already something19026// with the same name in the same scope.19027} else if (II) {19028PushOnScopeChains(NewPD, S);19029} else19030Record->addDecl(NewPD);1903119032return NewPD;19033}1903419035void Sema::ActOnStartFunctionDeclarationDeclarator(19036Declarator &Declarator, unsigned TemplateParameterDepth) {19037auto &Info = InventedParameterInfos.emplace_back();19038TemplateParameterList *ExplicitParams = nullptr;19039ArrayRef<TemplateParameterList *> ExplicitLists =19040Declarator.getTemplateParameterLists();19041if (!ExplicitLists.empty()) {19042bool IsMemberSpecialization, IsInvalid;19043ExplicitParams = MatchTemplateParametersToScopeSpecifier(19044Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),19045Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,19046ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,19047/*SuppressDiagnostic=*/true);19048}19049// C++23 [dcl.fct]p23:19050// An abbreviated function template can have a template-head. The invented19051// template-parameters are appended to the template-parameter-list after19052// the explicitly declared template-parameters.19053//19054// A template-head must have one or more template-parameters (read:19055// 'template<>' is *not* a template-head). Only append the invented19056// template parameters if we matched the nested-name-specifier to a non-empty19057// TemplateParameterList.19058if (ExplicitParams && !ExplicitParams->empty()) {19059Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();19060llvm::append_range(Info.TemplateParams, *ExplicitParams);19061Info.NumExplicitTemplateParams = ExplicitParams->size();19062} else {19063Info.AutoTemplateParameterDepth = TemplateParameterDepth;19064Info.NumExplicitTemplateParams = 0;19065}19066}1906719068void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {19069auto &FSI = InventedParameterInfos.back();19070if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {19071if (FSI.NumExplicitTemplateParams != 0) {19072TemplateParameterList *ExplicitParams =19073Declarator.getTemplateParameterLists().back();19074Declarator.setInventedTemplateParameterList(19075TemplateParameterList::Create(19076Context, ExplicitParams->getTemplateLoc(),19077ExplicitParams->getLAngleLoc(), FSI.TemplateParams,19078ExplicitParams->getRAngleLoc(),19079ExplicitParams->getRequiresClause()));19080} else {19081Declarator.setInventedTemplateParameterList(19082TemplateParameterList::Create(19083Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,19084SourceLocation(), /*RequiresClause=*/nullptr));19085}19086}19087InventedParameterInfos.pop_back();19088}190891909019091