Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaLambda.cpp
35233 views
//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//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++ lambda expressions.9//10//===----------------------------------------------------------------------===//11#include "clang/Sema/SemaLambda.h"12#include "TypeLocBuilder.h"13#include "clang/AST/ASTLambda.h"14#include "clang/AST/CXXInheritance.h"15#include "clang/AST/ExprCXX.h"16#include "clang/Basic/TargetInfo.h"17#include "clang/Sema/DeclSpec.h"18#include "clang/Sema/Initialization.h"19#include "clang/Sema/Lookup.h"20#include "clang/Sema/Scope.h"21#include "clang/Sema/ScopeInfo.h"22#include "clang/Sema/SemaCUDA.h"23#include "clang/Sema/SemaInternal.h"24#include "clang/Sema/SemaOpenMP.h"25#include "clang/Sema/Template.h"26#include "llvm/ADT/STLExtras.h"27#include <optional>28using namespace clang;29using namespace sema;3031/// Examines the FunctionScopeInfo stack to determine the nearest32/// enclosing lambda (to the current lambda) that is 'capture-ready' for33/// the variable referenced in the current lambda (i.e. \p VarToCapture).34/// If successful, returns the index into Sema's FunctionScopeInfo stack35/// of the capture-ready lambda's LambdaScopeInfo.36///37/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current38/// lambda - is on top) to determine the index of the nearest enclosing/outer39/// lambda that is ready to capture the \p VarToCapture being referenced in40/// the current lambda.41/// As we climb down the stack, we want the index of the first such lambda -42/// that is the lambda with the highest index that is 'capture-ready'.43///44/// A lambda 'L' is capture-ready for 'V' (var or this) if:45/// - its enclosing context is non-dependent46/// - and if the chain of lambdas between L and the lambda in which47/// V is potentially used (i.e. the lambda at the top of the scope info48/// stack), can all capture or have already captured V.49/// If \p VarToCapture is 'null' then we are trying to capture 'this'.50///51/// Note that a lambda that is deemed 'capture-ready' still needs to be checked52/// for whether it is 'capture-capable' (see53/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly54/// capture.55///56/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a57/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda58/// is at the top of the stack and has the highest index.59/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.60///61/// \returns An std::optional<unsigned> Index that if evaluates to 'true'62/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost63/// lambda which is capture-ready. If the return value evaluates to 'false'64/// then no lambda is capture-ready for \p VarToCapture.6566static inline std::optional<unsigned>67getStackIndexOfNearestEnclosingCaptureReadyLambda(68ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,69ValueDecl *VarToCapture) {70// Label failure to capture.71const std::optional<unsigned> NoLambdaIsCaptureReady;7273// Ignore all inner captured regions.74unsigned CurScopeIndex = FunctionScopes.size() - 1;75while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(76FunctionScopes[CurScopeIndex]))77--CurScopeIndex;78assert(79isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&80"The function on the top of sema's function-info stack must be a lambda");8182// If VarToCapture is null, we are attempting to capture 'this'.83const bool IsCapturingThis = !VarToCapture;84const bool IsCapturingVariable = !IsCapturingThis;8586// Start with the current lambda at the top of the stack (highest index).87DeclContext *EnclosingDC =88cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;8990do {91const clang::sema::LambdaScopeInfo *LSI =92cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);93// IF we have climbed down to an intervening enclosing lambda that contains94// the variable declaration - it obviously can/must not capture the95// variable.96// Since its enclosing DC is dependent, all the lambdas between it and the97// innermost nested lambda are dependent (otherwise we wouldn't have98// arrived here) - so we don't yet have a lambda that can capture the99// variable.100if (IsCapturingVariable &&101VarToCapture->getDeclContext()->Equals(EnclosingDC))102return NoLambdaIsCaptureReady;103104// For an enclosing lambda to be capture ready for an entity, all105// intervening lambda's have to be able to capture that entity. If even106// one of the intervening lambda's is not capable of capturing the entity107// then no enclosing lambda can ever capture that entity.108// For e.g.109// const int x = 10;110// [=](auto a) { #1111// [](auto b) { #2 <-- an intervening lambda that can never capture 'x'112// [=](auto c) { #3113// f(x, c); <-- can not lead to x's speculative capture by #1 or #2114// }; }; };115// If they do not have a default implicit capture, check to see116// if the entity has already been explicitly captured.117// If even a single dependent enclosing lambda lacks the capability118// to ever capture this variable, there is no further enclosing119// non-dependent lambda that can capture this variable.120if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {121if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))122return NoLambdaIsCaptureReady;123if (IsCapturingThis && !LSI->isCXXThisCaptured())124return NoLambdaIsCaptureReady;125}126EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);127128assert(CurScopeIndex);129--CurScopeIndex;130} while (!EnclosingDC->isTranslationUnit() &&131EnclosingDC->isDependentContext() &&132isLambdaCallOperator(EnclosingDC));133134assert(CurScopeIndex < (FunctionScopes.size() - 1));135// If the enclosingDC is not dependent, then the immediately nested lambda136// (one index above) is capture-ready.137if (!EnclosingDC->isDependentContext())138return CurScopeIndex + 1;139return NoLambdaIsCaptureReady;140}141142/// Examines the FunctionScopeInfo stack to determine the nearest143/// enclosing lambda (to the current lambda) that is 'capture-capable' for144/// the variable referenced in the current lambda (i.e. \p VarToCapture).145/// If successful, returns the index into Sema's FunctionScopeInfo stack146/// of the capture-capable lambda's LambdaScopeInfo.147///148/// Given the current stack of lambdas being processed by Sema and149/// the variable of interest, to identify the nearest enclosing lambda (to the150/// current lambda at the top of the stack) that can truly capture151/// a variable, it has to have the following two properties:152/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':153/// - climb down the stack (i.e. starting from the innermost and examining154/// each outer lambda step by step) checking if each enclosing155/// lambda can either implicitly or explicitly capture the variable.156/// Record the first such lambda that is enclosed in a non-dependent157/// context. If no such lambda currently exists return failure.158/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly159/// capture the variable by checking all its enclosing lambdas:160/// - check if all outer lambdas enclosing the 'capture-ready' lambda161/// identified above in 'a' can also capture the variable (this is done162/// via tryCaptureVariable for variables and CheckCXXThisCapture for163/// 'this' by passing in the index of the Lambda identified in step 'a')164///165/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a166/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda167/// is at the top of the stack.168///169/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.170///171///172/// \returns An std::optional<unsigned> Index that if evaluates to 'true'173/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost174/// lambda which is capture-capable. If the return value evaluates to 'false'175/// then no lambda is capture-capable for \p VarToCapture.176177std::optional<unsigned>178clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(179ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,180ValueDecl *VarToCapture, Sema &S) {181182const std::optional<unsigned> NoLambdaIsCaptureCapable;183184const std::optional<unsigned> OptionalStackIndex =185getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,186VarToCapture);187if (!OptionalStackIndex)188return NoLambdaIsCaptureCapable;189190const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;191assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||192S.getCurGenericLambda()) &&193"The capture ready lambda for a potential capture can only be the "194"current lambda if it is a generic lambda");195196const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =197cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);198199// If VarToCapture is null, we are attempting to capture 'this'200const bool IsCapturingThis = !VarToCapture;201const bool IsCapturingVariable = !IsCapturingThis;202203if (IsCapturingVariable) {204// Check if the capture-ready lambda can truly capture the variable, by205// checking whether all enclosing lambdas of the capture-ready lambda allow206// the capture - i.e. make sure it is capture-capable.207QualType CaptureType, DeclRefType;208const bool CanCaptureVariable =209!S.tryCaptureVariable(VarToCapture,210/*ExprVarIsUsedInLoc*/ SourceLocation(),211clang::Sema::TryCapture_Implicit,212/*EllipsisLoc*/ SourceLocation(),213/*BuildAndDiagnose*/ false, CaptureType,214DeclRefType, &IndexOfCaptureReadyLambda);215if (!CanCaptureVariable)216return NoLambdaIsCaptureCapable;217} else {218// Check if the capture-ready lambda can truly capture 'this' by checking219// whether all enclosing lambdas of the capture-ready lambda can capture220// 'this'.221const bool CanCaptureThis =222!S.CheckCXXThisCapture(223CaptureReadyLambdaLSI->PotentialThisCaptureLocation,224/*Explicit*/ false, /*BuildAndDiagnose*/ false,225&IndexOfCaptureReadyLambda);226if (!CanCaptureThis)227return NoLambdaIsCaptureCapable;228}229return IndexOfCaptureReadyLambda;230}231232static inline TemplateParameterList *233getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {234if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {235LSI->GLTemplateParameterList = TemplateParameterList::Create(236SemaRef.Context,237/*Template kw loc*/ SourceLocation(),238/*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),239LSI->TemplateParams,240/*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),241LSI->RequiresClause.get());242}243return LSI->GLTemplateParameterList;244}245246CXXRecordDecl *247Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,248unsigned LambdaDependencyKind,249LambdaCaptureDefault CaptureDefault) {250DeclContext *DC = CurContext;251while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))252DC = DC->getParent();253254bool IsGenericLambda =255Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this);256// Start constructing the lambda class.257CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(258Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,259IsGenericLambda, CaptureDefault);260DC->addDecl(Class);261262return Class;263}264265/// Determine whether the given context is or is enclosed in an inline266/// function.267static bool isInInlineFunction(const DeclContext *DC) {268while (!DC->isFileContext()) {269if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))270if (FD->isInlined())271return true;272273DC = DC->getLexicalParent();274}275276return false;277}278279std::tuple<MangleNumberingContext *, Decl *>280Sema::getCurrentMangleNumberContext(const DeclContext *DC) {281// Compute the context for allocating mangling numbers in the current282// expression, if the ABI requires them.283Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;284285enum ContextKind {286Normal,287DefaultArgument,288DataMember,289InlineVariable,290TemplatedVariable,291Concept292} Kind = Normal;293294bool IsInNonspecializedTemplate =295inTemplateInstantiation() || CurContext->isDependentContext();296297// Default arguments of member function parameters that appear in a class298// definition, as well as the initializers of data members, receive special299// treatment. Identify them.300if (ManglingContextDecl) {301if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {302if (const DeclContext *LexicalDC303= Param->getDeclContext()->getLexicalParent())304if (LexicalDC->isRecord())305Kind = DefaultArgument;306} else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {307if (Var->getMostRecentDecl()->isInline())308Kind = InlineVariable;309else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)310Kind = TemplatedVariable;311else if (Var->getDescribedVarTemplate())312Kind = TemplatedVariable;313else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {314if (!VTS->isExplicitSpecialization())315Kind = TemplatedVariable;316}317} else if (isa<FieldDecl>(ManglingContextDecl)) {318Kind = DataMember;319} else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {320Kind = Concept;321}322}323324// Itanium ABI [5.1.7]:325// In the following contexts [...] the one-definition rule requires closure326// types in different translation units to "correspond":327switch (Kind) {328case Normal: {329// -- the bodies of inline or templated functions330if ((IsInNonspecializedTemplate &&331!(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||332isInInlineFunction(CurContext)) {333while (auto *CD = dyn_cast<CapturedDecl>(DC))334DC = CD->getParent();335return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);336}337338return std::make_tuple(nullptr, nullptr);339}340341case Concept:342// Concept definitions aren't code generated and thus aren't mangled,343// however the ManglingContextDecl is important for the purposes of344// re-forming the template argument list of the lambda for constraint345// evaluation.346case DataMember:347// -- default member initializers348case DefaultArgument:349// -- default arguments appearing in class definitions350case InlineVariable:351case TemplatedVariable:352// -- the initializers of inline or templated variables353return std::make_tuple(354&Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,355ManglingContextDecl),356ManglingContextDecl);357}358359llvm_unreachable("unexpected context");360}361362static QualType363buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class,364TemplateParameterList *TemplateParams,365TypeSourceInfo *MethodTypeInfo) {366assert(MethodTypeInfo && "expected a non null type");367368QualType MethodType = MethodTypeInfo->getType();369// If a lambda appears in a dependent context or is a generic lambda (has370// template parameters) and has an 'auto' return type, deduce it to a371// dependent type.372if (Class->isDependentContext() || TemplateParams) {373const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();374QualType Result = FPT->getReturnType();375if (Result->isUndeducedType()) {376Result = S.SubstAutoTypeDependent(Result);377MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),378FPT->getExtProtoInfo());379}380}381return MethodType;382}383384// [C++2b] [expr.prim.lambda.closure] p4385// Given a lambda with a lambda-capture, the type of the explicit object386// parameter, if any, of the lambda's function call operator (possibly387// instantiated from a function call operator template) shall be either:388// - the closure type,389// - class type publicly and unambiguously derived from the closure type, or390// - a reference to a possibly cv-qualified such type.391bool Sema::DiagnoseInvalidExplicitObjectParameterInLambda(392CXXMethodDecl *Method, SourceLocation CallLoc) {393if (!isLambdaCallWithExplicitObjectParameter(Method))394return false;395CXXRecordDecl *RD = Method->getParent();396if (Method->getType()->isDependentType())397return false;398if (RD->isCapturelessLambda())399return false;400401ParmVarDecl *Param = Method->getParamDecl(0);402QualType ExplicitObjectParameterType = Param->getType()403.getNonReferenceType()404.getUnqualifiedType()405.getDesugaredType(getASTContext());406QualType LambdaType = getASTContext().getRecordType(RD);407if (LambdaType == ExplicitObjectParameterType)408return false;409410// Don't check the same instantiation twice.411//412// If this call operator is ill-formed, there is no point in issuing413// a diagnostic every time it is called because the problem is in the414// definition of the derived type, not at the call site.415//416// FIXME: Move this check to where we instantiate the method? This should417// be possible, but the naive approach of just marking the method as invalid418// leads to us emitting more diagnostics than we should have to for this case419// (1 error here *and* 1 error about there being no matching overload at the420// call site). It might be possible to avoid that by also checking if there421// is an empty cast path for the method stored in the context (signalling that422// we've already diagnosed it) and then just not building the call, but that423// doesn't really seem any simpler than diagnosing it at the call site...424if (auto It = Context.LambdaCastPaths.find(Method);425It != Context.LambdaCastPaths.end())426return It->second.empty();427428CXXCastPath &Path = Context.LambdaCastPaths[Method];429CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,430/*DetectVirtual=*/false);431if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,432Paths)) {433Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)434<< ExplicitObjectParameterType;435return true;436}437438if (Paths.isAmbiguous(LambdaType->getCanonicalTypeUnqualified())) {439std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);440Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)441<< LambdaType << PathsDisplay;442return true;443}444445if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,446Paths.front(),447diag::err_explicit_object_lambda_inaccessible_base))448return true;449450BuildBasePathArray(Paths, Path);451return false;452}453454void Sema::handleLambdaNumbering(455CXXRecordDecl *Class, CXXMethodDecl *Method,456std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {457if (NumberingOverride) {458Class->setLambdaNumbering(*NumberingOverride);459return;460}461462ContextRAII ManglingContext(*this, Class->getDeclContext());463464auto getMangleNumberingContext =465[this](CXXRecordDecl *Class,466Decl *ManglingContextDecl) -> MangleNumberingContext * {467// Get mangle numbering context if there's any extra decl context.468if (ManglingContextDecl)469return &Context.getManglingNumberContext(470ASTContext::NeedExtraManglingDecl, ManglingContextDecl);471// Otherwise, from that lambda's decl context.472auto DC = Class->getDeclContext();473while (auto *CD = dyn_cast<CapturedDecl>(DC))474DC = CD->getParent();475return &Context.getManglingNumberContext(DC);476};477478CXXRecordDecl::LambdaNumbering Numbering;479MangleNumberingContext *MCtx;480std::tie(MCtx, Numbering.ContextDecl) =481getCurrentMangleNumberContext(Class->getDeclContext());482if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||483getLangOpts().SYCLIsHost)) {484// Force lambda numbering in CUDA/HIP as we need to name lambdas following485// ODR. Both device- and host-compilation need to have a consistent naming486// on kernel functions. As lambdas are potential part of these `__global__`487// function names, they needs numbering following ODR.488// Also force for SYCL, since we need this for the489// __builtin_sycl_unique_stable_name implementation, which depends on lambda490// mangling.491MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);492assert(MCtx && "Retrieving mangle numbering context failed!");493Numbering.HasKnownInternalLinkage = true;494}495if (MCtx) {496Numbering.IndexInContext = MCtx->getNextLambdaIndex();497Numbering.ManglingNumber = MCtx->getManglingNumber(Method);498Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);499Class->setLambdaNumbering(Numbering);500501if (auto *Source =502dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))503Source->AssignedLambdaNumbering(Class);504}505}506507static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI,508CXXMethodDecl *CallOperator,509bool ExplicitResultType) {510if (ExplicitResultType) {511LSI->HasImplicitReturnType = false;512LSI->ReturnType = CallOperator->getReturnType();513if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())514S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,515diag::err_lambda_incomplete_result);516} else {517LSI->HasImplicitReturnType = true;518}519}520521void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,522SourceRange IntroducerRange,523LambdaCaptureDefault CaptureDefault,524SourceLocation CaptureDefaultLoc,525bool ExplicitParams, bool Mutable) {526LSI->CallOperator = CallOperator;527CXXRecordDecl *LambdaClass = CallOperator->getParent();528LSI->Lambda = LambdaClass;529if (CaptureDefault == LCD_ByCopy)530LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;531else if (CaptureDefault == LCD_ByRef)532LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;533LSI->CaptureDefaultLoc = CaptureDefaultLoc;534LSI->IntroducerRange = IntroducerRange;535LSI->ExplicitParams = ExplicitParams;536LSI->Mutable = Mutable;537}538539void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {540LSI->finishedExplicitCaptures();541}542543void Sema::ActOnLambdaExplicitTemplateParameterList(544LambdaIntroducer &Intro, SourceLocation LAngleLoc,545ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,546ExprResult RequiresClause) {547LambdaScopeInfo *LSI = getCurLambda();548assert(LSI && "Expected a lambda scope");549assert(LSI->NumExplicitTemplateParams == 0 &&550"Already acted on explicit template parameters");551assert(LSI->TemplateParams.empty() &&552"Explicit template parameters should come "553"before invented (auto) ones");554assert(!TParams.empty() &&555"No template parameters to act on");556LSI->TemplateParams.append(TParams.begin(), TParams.end());557LSI->NumExplicitTemplateParams = TParams.size();558LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};559LSI->RequiresClause = RequiresClause;560}561562/// If this expression is an enumerator-like expression of some type563/// T, return the type T; otherwise, return null.564///565/// Pointer comparisons on the result here should always work because566/// it's derived from either the parent of an EnumConstantDecl567/// (i.e. the definition) or the declaration returned by568/// EnumType::getDecl() (i.e. the definition).569static EnumDecl *findEnumForBlockReturn(Expr *E) {570// An expression is an enumerator-like expression of type T if,571// ignoring parens and parens-like expressions:572E = E->IgnoreParens();573574// - it is an enumerator whose enum type is T or575if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {576if (EnumConstantDecl *D577= dyn_cast<EnumConstantDecl>(DRE->getDecl())) {578return cast<EnumDecl>(D->getDeclContext());579}580return nullptr;581}582583// - it is a comma expression whose RHS is an enumerator-like584// expression of type T or585if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {586if (BO->getOpcode() == BO_Comma)587return findEnumForBlockReturn(BO->getRHS());588return nullptr;589}590591// - it is a statement-expression whose value expression is an592// enumerator-like expression of type T or593if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {594if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))595return findEnumForBlockReturn(last);596return nullptr;597}598599// - it is a ternary conditional operator (not the GNU ?:600// extension) whose second and third operands are601// enumerator-like expressions of type T or602if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {603if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))604if (ED == findEnumForBlockReturn(CO->getFalseExpr()))605return ED;606return nullptr;607}608609// (implicitly:)610// - it is an implicit integral conversion applied to an611// enumerator-like expression of type T or612if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {613// We can sometimes see integral conversions in valid614// enumerator-like expressions.615if (ICE->getCastKind() == CK_IntegralCast)616return findEnumForBlockReturn(ICE->getSubExpr());617618// Otherwise, just rely on the type.619}620621// - it is an expression of that formal enum type.622if (const EnumType *ET = E->getType()->getAs<EnumType>()) {623return ET->getDecl();624}625626// Otherwise, nope.627return nullptr;628}629630/// Attempt to find a type T for which the returned expression of the631/// given statement is an enumerator-like expression of that type.632static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {633if (Expr *retValue = ret->getRetValue())634return findEnumForBlockReturn(retValue);635return nullptr;636}637638/// Attempt to find a common type T for which all of the returned639/// expressions in a block are enumerator-like expressions of that640/// type.641static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {642ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();643644// Try to find one for the first return.645EnumDecl *ED = findEnumForBlockReturn(*i);646if (!ED) return nullptr;647648// Check that the rest of the returns have the same enum.649for (++i; i != e; ++i) {650if (findEnumForBlockReturn(*i) != ED)651return nullptr;652}653654// Never infer an anonymous enum type.655if (!ED->hasNameForLinkage()) return nullptr;656657return ED;658}659660/// Adjust the given return statements so that they formally return661/// the given type. It should require, at most, an IntegralCast.662static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,663QualType returnType) {664for (ArrayRef<ReturnStmt*>::iterator665i = returns.begin(), e = returns.end(); i != e; ++i) {666ReturnStmt *ret = *i;667Expr *retValue = ret->getRetValue();668if (S.Context.hasSameType(retValue->getType(), returnType))669continue;670671// Right now we only support integral fixup casts.672assert(returnType->isIntegralOrUnscopedEnumerationType());673assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());674675ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);676677Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);678E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,679/*base path*/ nullptr, VK_PRValue,680FPOptionsOverride());681if (cleanups) {682cleanups->setSubExpr(E);683} else {684ret->setRetValue(E);685}686}687}688689void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {690assert(CSI.HasImplicitReturnType);691// If it was ever a placeholder, it had to been deduced to DependentTy.692assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());693assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&694"lambda expressions use auto deduction in C++14 onwards");695696// C++ core issue 975:697// If a lambda-expression does not include a trailing-return-type,698// it is as if the trailing-return-type denotes the following type:699// - if there are no return statements in the compound-statement,700// or all return statements return either an expression of type701// void or no expression or braced-init-list, the type void;702// - otherwise, if all return statements return an expression703// and the types of the returned expressions after704// lvalue-to-rvalue conversion (4.1 [conv.lval]),705// array-to-pointer conversion (4.2 [conv.array]), and706// function-to-pointer conversion (4.3 [conv.func]) are the707// same, that common type;708// - otherwise, the program is ill-formed.709//710// C++ core issue 1048 additionally removes top-level cv-qualifiers711// from the types of returned expressions to match the C++14 auto712// deduction rules.713//714// In addition, in blocks in non-C++ modes, if all of the return715// statements are enumerator-like expressions of some type T, where716// T has a name for linkage, then we infer the return type of the717// block to be that type.718719// First case: no return statements, implicit void return type.720ASTContext &Ctx = getASTContext();721if (CSI.Returns.empty()) {722// It's possible there were simply no /valid/ return statements.723// In this case, the first one we found may have at least given us a type.724if (CSI.ReturnType.isNull())725CSI.ReturnType = Ctx.VoidTy;726return;727}728729// Second case: at least one return statement has dependent type.730// Delay type checking until instantiation.731assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");732if (CSI.ReturnType->isDependentType())733return;734735// Try to apply the enum-fuzz rule.736if (!getLangOpts().CPlusPlus) {737assert(isa<BlockScopeInfo>(CSI));738const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);739if (ED) {740CSI.ReturnType = Context.getTypeDeclType(ED);741adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);742return;743}744}745746// Third case: only one return statement. Don't bother doing extra work!747if (CSI.Returns.size() == 1)748return;749750// General case: many return statements.751// Check that they all have compatible return types.752753// We require the return types to strictly match here.754// Note that we've already done the required promotions as part of755// processing the return statement.756for (const ReturnStmt *RS : CSI.Returns) {757const Expr *RetE = RS->getRetValue();758759QualType ReturnType =760(RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();761if (Context.getCanonicalFunctionResultType(ReturnType) ==762Context.getCanonicalFunctionResultType(CSI.ReturnType)) {763// Use the return type with the strictest possible nullability annotation.764auto RetTyNullability = ReturnType->getNullability();765auto BlockNullability = CSI.ReturnType->getNullability();766if (BlockNullability &&767(!RetTyNullability ||768hasWeakerNullability(*RetTyNullability, *BlockNullability)))769CSI.ReturnType = ReturnType;770continue;771}772773// FIXME: This is a poor diagnostic for ReturnStmts without expressions.774// TODO: It's possible that the *first* return is the divergent one.775Diag(RS->getBeginLoc(),776diag::err_typecheck_missing_return_type_incompatible)777<< ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);778// Continue iterating so that we keep emitting diagnostics.779}780}781782QualType Sema::buildLambdaInitCaptureInitialization(783SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,784std::optional<unsigned> NumExpansions, IdentifierInfo *Id,785bool IsDirectInit, Expr *&Init) {786// Create an 'auto' or 'auto&' TypeSourceInfo that we can use to787// deduce against.788QualType DeductType = Context.getAutoDeductType();789TypeLocBuilder TLB;790AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);791TL.setNameLoc(Loc);792if (ByRef) {793DeductType = BuildReferenceType(DeductType, true, Loc, Id);794assert(!DeductType.isNull() && "can't build reference to auto");795TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);796}797if (EllipsisLoc.isValid()) {798if (Init->containsUnexpandedParameterPack()) {799Diag(EllipsisLoc, getLangOpts().CPlusPlus20800? diag::warn_cxx17_compat_init_capture_pack801: diag::ext_init_capture_pack);802DeductType = Context.getPackExpansionType(DeductType, NumExpansions,803/*ExpectPackInType=*/false);804TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);805} else {806// Just ignore the ellipsis for now and form a non-pack variable. We'll807// diagnose this later when we try to capture it.808}809}810TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);811812// Deduce the type of the init capture.813QualType DeducedType = deduceVarTypeFromInitializer(814/*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,815SourceRange(Loc, Loc), IsDirectInit, Init);816if (DeducedType.isNull())817return QualType();818819// Are we a non-list direct initialization?820ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);821822// Perform initialization analysis and ensure any implicit conversions823// (such as lvalue-to-rvalue) are enforced.824InitializedEntity Entity =825InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);826InitializationKind Kind =827IsDirectInit828? (CXXDirectInit ? InitializationKind::CreateDirect(829Loc, Init->getBeginLoc(), Init->getEndLoc())830: InitializationKind::CreateDirectList(Loc))831: InitializationKind::CreateCopy(Loc, Init->getBeginLoc());832833MultiExprArg Args = Init;834if (CXXDirectInit)835Args =836MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());837QualType DclT;838InitializationSequence InitSeq(*this, Entity, Kind, Args);839ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);840841if (Result.isInvalid())842return QualType();843844Init = Result.getAs<Expr>();845return DeducedType;846}847848VarDecl *Sema::createLambdaInitCaptureVarDecl(849SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,850IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {851// FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization852// rather than reconstructing it here.853TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);854if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())855PETL.setEllipsisLoc(EllipsisLoc);856857// Create a dummy variable representing the init-capture. This is not actually858// used as a variable, and only exists as a way to name and refer to the859// init-capture.860// FIXME: Pass in separate source locations for '&' and identifier.861VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,862InitCaptureType, TSI, SC_Auto);863NewVD->setInitCapture(true);864NewVD->setReferenced(true);865// FIXME: Pass in a VarDecl::InitializationStyle.866NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));867NewVD->markUsed(Context);868NewVD->setInit(Init);869if (NewVD->isParameterPack())870getCurLambda()->LocalPacks.push_back(NewVD);871return NewVD;872}873874void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {875assert(Var->isInitCapture() && "init capture flag should be set");876LSI->addCapture(Var, /*isBlock=*/false, ByRef,877/*isNested=*/false, Var->getLocation(), SourceLocation(),878Var->getType(), /*Invalid=*/false);879}880881// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't882// check that the current lambda is in a consistent or fully constructed state.883static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) {884assert(!S.FunctionScopes.empty());885return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);886}887888static TypeSourceInfo *889getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) {890// C++11 [expr.prim.lambda]p4:891// If a lambda-expression does not include a lambda-declarator, it is as892// if the lambda-declarator were ().893FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention(894/*IsVariadic=*/false, /*IsCXXMethod=*/true));895EPI.HasTrailingReturn = true;896EPI.TypeQuals.addConst();897LangAS AS = S.getDefaultCXXMethodAddrSpace();898if (AS != LangAS::Default)899EPI.TypeQuals.addAddressSpace(AS);900901// C++1y [expr.prim.lambda]:902// The lambda return type is 'auto', which is replaced by the903// trailing-return type if provided and/or deduced from 'return'904// statements905// We don't do this before C++1y, because we don't support deduced return906// types there.907QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14908? S.Context.getAutoDeductType()909: S.Context.DependentTy;910QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,911std::nullopt, EPI);912return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);913}914915static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro,916Declarator &ParamInfo, Scope *CurScope,917SourceLocation Loc,918bool &ExplicitResultType) {919920ExplicitResultType = false;921922assert(923(ParamInfo.getDeclSpec().getStorageClassSpec() ==924DeclSpec::SCS_unspecified ||925ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&926"Unexpected storage specifier");927bool IsLambdaStatic =928ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;929930TypeSourceInfo *MethodTyInfo;931932if (ParamInfo.getNumTypeObjects() == 0) {933MethodTyInfo = getDummyLambdaType(S, Loc);934} else {935// Check explicit parameters936S.CheckExplicitObjectLambda(ParamInfo);937938DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();939940bool HasExplicitObjectParameter =941ParamInfo.isExplicitObjectMemberFunction();942943ExplicitResultType = FTI.hasTrailingReturnType();944if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&945!HasExplicitObjectParameter)946FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc);947948if (ExplicitResultType && S.getLangOpts().HLSL) {949QualType RetTy = FTI.getTrailingReturnType().get();950if (!RetTy.isNull()) {951// HLSL does not support specifying an address space on a lambda return952// type.953LangAS AddressSpace = RetTy.getAddressSpace();954if (AddressSpace != LangAS::Default)955S.Diag(FTI.getTrailingReturnTypeLoc(),956diag::err_return_value_with_address_space);957}958}959960MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);961assert(MethodTyInfo && "no type from lambda-declarator");962963// Check for unexpanded parameter packs in the method type.964if (MethodTyInfo->getType()->containsUnexpandedParameterPack())965S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,966S.UPPC_DeclarationType);967}968return MethodTyInfo;969}970971CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange,972CXXRecordDecl *Class) {973974// C++20 [expr.prim.lambda.closure]p3:975// The closure type for a lambda-expression has a public inline function976// call operator (for a non-generic lambda) or function call operator977// template (for a generic lambda) whose parameters and return type are978// described by the lambda-expression's parameter-declaration-clause979// and trailing-return-type respectively.980DeclarationName MethodName =981Context.DeclarationNames.getCXXOperatorName(OO_Call);982DeclarationNameLoc MethodNameLoc =983DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin());984CXXMethodDecl *Method = CXXMethodDecl::Create(985Context, Class, SourceLocation(),986DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),987MethodNameLoc),988QualType(), /*Tinfo=*/nullptr, SC_None,989getCurFPFeatures().isFPConstrained(),990/*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),991/*TrailingRequiresClause=*/nullptr);992Method->setAccess(AS_public);993return Method;994}995996void Sema::AddTemplateParametersToLambdaCallOperator(997CXXMethodDecl *CallOperator, CXXRecordDecl *Class,998TemplateParameterList *TemplateParams) {999assert(TemplateParams && "no template parameters");1000FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create(1001Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),1002TemplateParams, CallOperator);1003TemplateMethod->setAccess(AS_public);1004CallOperator->setDescribedFunctionTemplate(TemplateMethod);1005}10061007void Sema::CompleteLambdaCallOperator(1008CXXMethodDecl *Method, SourceLocation LambdaLoc,1009SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,1010TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,1011StorageClass SC, ArrayRef<ParmVarDecl *> Params,1012bool HasExplicitResultType) {10131014LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);10151016if (TrailingRequiresClause)1017Method->setTrailingRequiresClause(TrailingRequiresClause);10181019TemplateParameterList *TemplateParams =1020getGenericLambdaTemplateParameterList(LSI, *this);10211022DeclContext *DC = Method->getLexicalDeclContext();1023Method->setLexicalDeclContext(LSI->Lambda);1024if (TemplateParams) {1025FunctionTemplateDecl *TemplateMethod =1026Method->getDescribedFunctionTemplate();1027assert(TemplateMethod &&1028"AddTemplateParametersToLambdaCallOperator should have been called");10291030LSI->Lambda->addDecl(TemplateMethod);1031TemplateMethod->setLexicalDeclContext(DC);1032} else {1033LSI->Lambda->addDecl(Method);1034}1035LSI->Lambda->setLambdaIsGeneric(TemplateParams);1036LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);10371038Method->setLexicalDeclContext(DC);1039Method->setLocation(LambdaLoc);1040Method->setInnerLocStart(CallOperatorLoc);1041Method->setTypeSourceInfo(MethodTyInfo);1042Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,1043TemplateParams, MethodTyInfo));1044Method->setConstexprKind(ConstexprKind);1045Method->setStorageClass(SC);1046if (!Params.empty()) {1047CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);1048Method->setParams(Params);1049for (auto P : Method->parameters()) {1050assert(P && "null in a parameter list");1051P->setOwningFunction(Method);1052}1053}10541055buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);1056}10571058void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,1059Scope *CurrentScope) {10601061LambdaScopeInfo *LSI = getCurLambda();1062assert(LSI && "LambdaScopeInfo should be on stack!");10631064if (Intro.Default == LCD_ByCopy)1065LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;1066else if (Intro.Default == LCD_ByRef)1067LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;1068LSI->CaptureDefaultLoc = Intro.DefaultLoc;1069LSI->IntroducerRange = Intro.Range;1070LSI->AfterParameterList = false;10711072assert(LSI->NumExplicitTemplateParams == 0);10731074// Determine if we're within a context where we know that the lambda will1075// be dependent, because there are template parameters in scope.1076CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =1077CXXRecordDecl::LDK_Unknown;1078if (CurScope->getTemplateParamParent() != nullptr) {1079LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;1080} else if (Scope *P = CurScope->getParent()) {1081// Given a lambda defined inside a requires expression,1082//1083// struct S {1084// S(auto var) requires requires { [&] -> decltype(var) { }; }1085// {}1086// };1087//1088// The parameter var is not injected into the function Decl at the point of1089// parsing lambda. In such scenarios, perceiving it as dependent could1090// result in the constraint being evaluated, which matches what GCC does.1091while (P->getEntity() && P->getEntity()->isRequiresExprBody())1092P = P->getParent();1093if (P->isFunctionDeclarationScope() &&1094llvm::any_of(P->decls(), [](Decl *D) {1095return isa<ParmVarDecl>(D) &&1096cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();1097}))1098LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;1099}11001101CXXRecordDecl *Class = createLambdaClosureType(1102Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);1103LSI->Lambda = Class;11041105CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class);1106LSI->CallOperator = Method;1107Method->setLexicalDeclContext(CurContext);11081109PushDeclContext(CurScope, Method);11101111bool ContainsUnexpandedParameterPack = false;11121113// Distinct capture names, for diagnostics.1114llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;11151116// Handle explicit captures.1117SourceLocation PrevCaptureLoc =1118Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;1119for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;1120PrevCaptureLoc = C->Loc, ++C) {1121if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {1122if (C->Kind == LCK_StarThis)1123Diag(C->Loc, !getLangOpts().CPlusPlus171124? diag::ext_star_this_lambda_capture_cxx171125: diag::warn_cxx14_compat_star_this_lambda_capture);11261127// C++11 [expr.prim.lambda]p8:1128// An identifier or this shall not appear more than once in a1129// lambda-capture.1130if (LSI->isCXXThisCaptured()) {1131Diag(C->Loc, diag::err_capture_more_than_once)1132<< "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())1133<< FixItHint::CreateRemoval(1134SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));1135continue;1136}11371138// C++20 [expr.prim.lambda]p8:1139// If a lambda-capture includes a capture-default that is =,1140// each simple-capture of that lambda-capture shall be of the form1141// "&identifier", "this", or "* this". [ Note: The form [&,this] is1142// redundant but accepted for compatibility with ISO C++14. --end note ]1143if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)1144Diag(C->Loc, !getLangOpts().CPlusPlus201145? diag::ext_equals_this_lambda_capture_cxx201146: diag::warn_cxx17_compat_equals_this_lambda_capture);11471148// C++11 [expr.prim.lambda]p12:1149// If this is captured by a local lambda expression, its nearest1150// enclosing function shall be a non-static member function.1151QualType ThisCaptureType = getCurrentThisType();1152if (ThisCaptureType.isNull()) {1153Diag(C->Loc, diag::err_this_capture) << true;1154continue;1155}11561157CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,1158/*FunctionScopeIndexToStopAtPtr*/ nullptr,1159C->Kind == LCK_StarThis);1160if (!LSI->Captures.empty())1161LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;1162continue;1163}11641165assert(C->Id && "missing identifier for capture");11661167if (C->Init.isInvalid())1168continue;11691170ValueDecl *Var = nullptr;1171if (C->Init.isUsable()) {1172Diag(C->Loc, getLangOpts().CPlusPlus141173? diag::warn_cxx11_compat_init_capture1174: diag::ext_init_capture);11751176// If the initializer expression is usable, but the InitCaptureType1177// is not, then an error has occurred - so ignore the capture for now.1178// for e.g., [n{0}] { }; <-- if no <initializer_list> is included.1179// FIXME: we should create the init capture variable and mark it invalid1180// in this case.1181if (C->InitCaptureType.get().isNull())1182continue;11831184if (C->Init.get()->containsUnexpandedParameterPack() &&1185!C->InitCaptureType.get()->getAs<PackExpansionType>())1186DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);11871188unsigned InitStyle;1189switch (C->InitKind) {1190case LambdaCaptureInitKind::NoInit:1191llvm_unreachable("not an init-capture?");1192case LambdaCaptureInitKind::CopyInit:1193InitStyle = VarDecl::CInit;1194break;1195case LambdaCaptureInitKind::DirectInit:1196InitStyle = VarDecl::CallInit;1197break;1198case LambdaCaptureInitKind::ListInit:1199InitStyle = VarDecl::ListInit;1200break;1201}1202Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),1203C->EllipsisLoc, C->Id, InitStyle,1204C->Init.get(), Method);1205assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");1206if (auto *V = dyn_cast<VarDecl>(Var))1207CheckShadow(CurrentScope, V);1208PushOnScopeChains(Var, CurrentScope, false);1209} else {1210assert(C->InitKind == LambdaCaptureInitKind::NoInit &&1211"init capture has valid but null init?");12121213// C++11 [expr.prim.lambda]p8:1214// If a lambda-capture includes a capture-default that is &, the1215// identifiers in the lambda-capture shall not be preceded by &.1216// If a lambda-capture includes a capture-default that is =, [...]1217// each identifier it contains shall be preceded by &.1218if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {1219Diag(C->Loc, diag::err_reference_capture_with_reference_default)1220<< FixItHint::CreateRemoval(1221SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));1222continue;1223} else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {1224Diag(C->Loc, diag::err_copy_capture_with_copy_default)1225<< FixItHint::CreateRemoval(1226SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));1227continue;1228}12291230// C++11 [expr.prim.lambda]p10:1231// The identifiers in a capture-list are looked up using the usual1232// rules for unqualified name lookup (3.4.1)1233DeclarationNameInfo Name(C->Id, C->Loc);1234LookupResult R(*this, Name, LookupOrdinaryName);1235LookupName(R, CurScope);1236if (R.isAmbiguous())1237continue;1238if (R.empty()) {1239// FIXME: Disable corrections that would add qualification?1240CXXScopeSpec ScopeSpec;1241DeclFilterCCC<VarDecl> Validator{};1242if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))1243continue;1244}12451246if (auto *BD = R.getAsSingle<BindingDecl>())1247Var = BD;1248else if (R.getAsSingle<FieldDecl>()) {1249Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)1250<< C->Id;1251continue;1252} else1253Var = R.getAsSingle<VarDecl>();1254if (Var && DiagnoseUseOfDecl(Var, C->Loc))1255continue;1256}12571258// C++11 [expr.prim.lambda]p10:1259// [...] each such lookup shall find a variable with automatic storage1260// duration declared in the reaching scope of the local lambda expression.1261// Note that the 'reaching scope' check happens in tryCaptureVariable().1262if (!Var) {1263Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;1264continue;1265}12661267// C++11 [expr.prim.lambda]p8:1268// An identifier or this shall not appear more than once in a1269// lambda-capture.1270if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});1271!Inserted) {1272if (C->InitKind == LambdaCaptureInitKind::NoInit &&1273!Var->isInitCapture()) {1274Diag(C->Loc, diag::err_capture_more_than_once)1275<< C->Id << It->second->getBeginLoc()1276<< FixItHint::CreateRemoval(1277SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));1278Var->setInvalidDecl();1279} else if (Var && Var->isPlaceholderVar(getLangOpts())) {1280DiagPlaceholderVariableDefinition(C->Loc);1281} else {1282// Previous capture captured something different (one or both was1283// an init-capture): no fixit.1284Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;1285continue;1286}1287}12881289// Ignore invalid decls; they'll just confuse the code later.1290if (Var->isInvalidDecl())1291continue;12921293VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();12941295if (!Underlying->hasLocalStorage()) {1296Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;1297Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;1298continue;1299}13001301// C++11 [expr.prim.lambda]p23:1302// A capture followed by an ellipsis is a pack expansion (14.5.3).1303SourceLocation EllipsisLoc;1304if (C->EllipsisLoc.isValid()) {1305if (Var->isParameterPack()) {1306EllipsisLoc = C->EllipsisLoc;1307} else {1308Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)1309<< (C->Init.isUsable() ? C->Init.get()->getSourceRange()1310: SourceRange(C->Loc));13111312// Just ignore the ellipsis.1313}1314} else if (Var->isParameterPack()) {1315ContainsUnexpandedParameterPack = true;1316}13171318if (C->Init.isUsable()) {1319addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);1320} else {1321TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef1322: TryCapture_ExplicitByVal;1323tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);1324}1325if (!LSI->Captures.empty())1326LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;1327}1328finishLambdaExplicitCaptures(LSI);1329LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;1330PopDeclContext();1331}13321333void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,1334SourceLocation MutableLoc) {13351336LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);1337LSI->Mutable = MutableLoc.isValid();1338ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);13391340// C++11 [expr.prim.lambda]p9:1341// A lambda-expression whose smallest enclosing scope is a block scope is a1342// local lambda expression; any other lambda expression shall not have a1343// capture-default or simple-capture in its lambda-introducer.1344//1345// For simple-captures, this is covered by the check below that any named1346// entity is a variable that can be captured.1347//1348// For DR1632, we also allow a capture-default in any context where we can1349// odr-use 'this' (in particular, in a default initializer for a non-static1350// data member).1351if (Intro.Default != LCD_None &&1352!LSI->Lambda->getParent()->isFunctionOrMethod() &&1353(getCurrentThisType().isNull() ||1354CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,1355/*BuildAndDiagnose=*/false)))1356Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);1357}13581359void Sema::ActOnLambdaClosureParameters(1360Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {1361LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);1362PushDeclContext(LambdaScope, LSI->CallOperator);13631364for (const DeclaratorChunk::ParamInfo &P : Params) {1365auto *Param = cast<ParmVarDecl>(P.Param);1366Param->setOwningFunction(LSI->CallOperator);1367if (Param->getIdentifier())1368PushOnScopeChains(Param, LambdaScope, false);1369}13701371// After the parameter list, we may parse a noexcept/requires/trailing return1372// type which need to know whether the call operator constiture a dependent1373// context, so we need to setup the FunctionTemplateDecl of generic lambdas1374// now.1375TemplateParameterList *TemplateParams =1376getGenericLambdaTemplateParameterList(LSI, *this);1377if (TemplateParams) {1378AddTemplateParametersToLambdaCallOperator(LSI->CallOperator, LSI->Lambda,1379TemplateParams);1380LSI->Lambda->setLambdaIsGeneric(true);1381LSI->ContainsUnexpandedParameterPack |=1382TemplateParams->containsUnexpandedParameterPack();1383}1384LSI->AfterParameterList = true;1385}13861387void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,1388Declarator &ParamInfo,1389const DeclSpec &DS) {13901391LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this);1392LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier());13931394SmallVector<ParmVarDecl *, 8> Params;1395bool ExplicitResultType;13961397SourceLocation TypeLoc, CallOperatorLoc;1398if (ParamInfo.getNumTypeObjects() == 0) {1399CallOperatorLoc = TypeLoc = Intro.Range.getEnd();1400} else {1401unsigned Index;1402ParamInfo.isFunctionDeclarator(Index);1403const auto &Object = ParamInfo.getTypeObject(Index);1404TypeLoc =1405Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();1406CallOperatorLoc = ParamInfo.getSourceRange().getEnd();1407}14081409CXXRecordDecl *Class = LSI->Lambda;1410CXXMethodDecl *Method = LSI->CallOperator;14111412TypeSourceInfo *MethodTyInfo = getLambdaType(1413*this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);14141415LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;14161417if (ParamInfo.isFunctionDeclarator() != 0 &&1418!FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())) {1419const auto &FTI = ParamInfo.getFunctionTypeInfo();1420Params.reserve(Params.size());1421for (unsigned I = 0; I < FTI.NumParams; ++I) {1422auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);1423Param->setScopeInfo(0, Params.size());1424Params.push_back(Param);1425}1426}14271428bool IsLambdaStatic =1429ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;14301431CompleteLambdaCallOperator(1432Method, Intro.Range.getBegin(), CallOperatorLoc,1433ParamInfo.getTrailingRequiresClause(), MethodTyInfo,1434ParamInfo.getDeclSpec().getConstexprSpecifier(),1435IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);14361437CheckCXXDefaultArguments(Method);14381439// This represents the function body for the lambda function, check if we1440// have to apply optnone due to a pragma.1441AddRangeBasedOptnone(Method);14421443// code_seg attribute on lambda apply to the method.1444if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(1445Method, /*IsDefinition=*/true))1446Method->addAttr(A);14471448// Attributes on the lambda apply to the method.1449ProcessDeclAttributes(CurScope, Method, ParamInfo);14501451// CUDA lambdas get implicit host and device attributes.1452if (getLangOpts().CUDA)1453CUDA().SetLambdaAttrs(Method);14541455// OpenMP lambdas might get assumumption attributes.1456if (LangOpts.OpenMP)1457OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);14581459handleLambdaNumbering(Class, Method);14601461for (auto &&C : LSI->Captures) {1462if (!C.isVariableCapture())1463continue;1464ValueDecl *Var = C.getVariable();1465if (Var && Var->isInitCapture()) {1466PushOnScopeChains(Var, CurScope, false);1467}1468}14691470auto CheckRedefinition = [&](ParmVarDecl *Param) {1471for (const auto &Capture : Intro.Captures) {1472if (Capture.Id == Param->getIdentifier()) {1473Diag(Param->getLocation(), diag::err_parameter_shadow_capture);1474Diag(Capture.Loc, diag::note_var_explicitly_captured_here)1475<< Capture.Id << true;1476return false;1477}1478}1479return true;1480};14811482for (ParmVarDecl *P : Params) {1483if (!P->getIdentifier())1484continue;1485if (CheckRedefinition(P))1486CheckShadow(CurScope, P);1487PushOnScopeChains(P, CurScope);1488}14891490// C++23 [expr.prim.lambda.capture]p5:1491// If an identifier in a capture appears as the declarator-id of a parameter1492// of the lambda-declarator's parameter-declaration-clause or as the name of a1493// template parameter of the lambda-expression's template-parameter-list, the1494// program is ill-formed.1495TemplateParameterList *TemplateParams =1496getGenericLambdaTemplateParameterList(LSI, *this);1497if (TemplateParams) {1498for (const auto *TP : TemplateParams->asArray()) {1499if (!TP->getIdentifier())1500continue;1501for (const auto &Capture : Intro.Captures) {1502if (Capture.Id == TP->getIdentifier()) {1503Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;1504NoteTemplateParameterLocation(*TP);1505}1506}1507}1508}15091510// C++20: dcl.decl.general p4:1511// The optional requires-clause ([temp.pre]) in an init-declarator or1512// member-declarator shall be present only if the declarator declares a1513// templated function ([dcl.fct]).1514if (Expr *TRC = Method->getTrailingRequiresClause()) {1515// [temp.pre]/8:1516// An entity is templated if it is1517// - a template,1518// - an entity defined ([basic.def]) or created ([class.temporary]) in a1519// templated entity,1520// - a member of a templated entity,1521// - an enumerator for an enumeration that is a templated entity, or1522// - the closure type of a lambda-expression ([expr.prim.lambda.closure])1523// appearing in the declaration of a templated entity. [Note 6: A local1524// class, a local or block variable, or a friend function defined in a1525// templated entity is a templated entity. — end note]1526//1527// A templated function is a function template or a function that is1528// templated. A templated class is a class template or a class that is1529// templated. A templated variable is a variable template or a variable1530// that is templated.15311532// Note: we only have to check if this is defined in a template entity, OR1533// if we are a template, since the rest don't apply. The requires clause1534// applies to the call operator, which we already know is a member function,1535// AND defined.1536if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {1537Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);1538}1539}15401541// Enter a new evaluation context to insulate the lambda from any1542// cleanups from the enclosing full-expression.1543PushExpressionEvaluationContext(1544LSI->CallOperator->isConsteval()1545? ExpressionEvaluationContext::ImmediateFunctionContext1546: ExpressionEvaluationContext::PotentiallyEvaluated);1547ExprEvalContexts.back().InImmediateFunctionContext =1548LSI->CallOperator->isConsteval();1549ExprEvalContexts.back().InImmediateEscalatingFunctionContext =1550getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();1551}15521553void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,1554bool IsInstantiation) {1555LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());15561557// Leave the expression-evaluation context.1558DiscardCleanupsInEvaluationContext();1559PopExpressionEvaluationContext();15601561// Leave the context of the lambda.1562if (!IsInstantiation)1563PopDeclContext();15641565// Finalize the lambda.1566CXXRecordDecl *Class = LSI->Lambda;1567Class->setInvalidDecl();1568SmallVector<Decl*, 4> Fields(Class->fields());1569ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),1570SourceLocation(), ParsedAttributesView());1571CheckCompletedCXXClass(nullptr, Class);15721573PopFunctionScopeInfo();1574}15751576template <typename Func>1577static void repeatForLambdaConversionFunctionCallingConvs(1578Sema &S, const FunctionProtoType &CallOpProto, Func F) {1579CallingConv DefaultFree = S.Context.getDefaultCallingConvention(1580CallOpProto.isVariadic(), /*IsCXXMethod=*/false);1581CallingConv DefaultMember = S.Context.getDefaultCallingConvention(1582CallOpProto.isVariadic(), /*IsCXXMethod=*/true);1583CallingConv CallOpCC = CallOpProto.getCallConv();15841585/// Implement emitting a version of the operator for many of the calling1586/// conventions for MSVC, as described here:1587/// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.1588/// Experimentally, we determined that cdecl, stdcall, fastcall, and1589/// vectorcall are generated by MSVC when it is supported by the target.1590/// Additionally, we are ensuring that the default-free/default-member and1591/// call-operator calling convention are generated as well.1592/// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the1593/// 'member default', despite MSVC not doing so. We do this in order to ensure1594/// that someone who intentionally places 'thiscall' on the lambda call1595/// operator will still get that overload, since we don't have the a way of1596/// detecting the attribute by the time we get here.1597if (S.getLangOpts().MSVCCompat) {1598CallingConv Convs[] = {1599CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,1600DefaultFree, DefaultMember, CallOpCC};1601llvm::sort(Convs);1602llvm::iterator_range<CallingConv *> Range(1603std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));1604const TargetInfo &TI = S.getASTContext().getTargetInfo();16051606for (CallingConv C : Range) {1607if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)1608F(C);1609}1610return;1611}16121613if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {1614F(DefaultFree);1615F(DefaultMember);1616} else {1617F(CallOpCC);1618}1619}16201621// Returns the 'standard' calling convention to be used for the lambda1622// conversion function, that is, the 'free' function calling convention unless1623// it is overridden by a non-default calling convention attribute.1624static CallingConv1625getLambdaConversionFunctionCallConv(Sema &S,1626const FunctionProtoType *CallOpProto) {1627CallingConv DefaultFree = S.Context.getDefaultCallingConvention(1628CallOpProto->isVariadic(), /*IsCXXMethod=*/false);1629CallingConv DefaultMember = S.Context.getDefaultCallingConvention(1630CallOpProto->isVariadic(), /*IsCXXMethod=*/true);1631CallingConv CallOpCC = CallOpProto->getCallConv();16321633// If the call-operator hasn't been changed, return both the 'free' and1634// 'member' function calling convention.1635if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)1636return DefaultFree;1637return CallOpCC;1638}16391640QualType Sema::getLambdaConversionFunctionResultType(1641const FunctionProtoType *CallOpProto, CallingConv CC) {1642const FunctionProtoType::ExtProtoInfo CallOpExtInfo =1643CallOpProto->getExtProtoInfo();1644FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;1645InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);1646InvokerExtInfo.TypeQuals = Qualifiers();1647assert(InvokerExtInfo.RefQualifier == RQ_None &&1648"Lambda's call operator should not have a reference qualifier");1649return Context.getFunctionType(CallOpProto->getReturnType(),1650CallOpProto->getParamTypes(), InvokerExtInfo);1651}16521653/// Add a lambda's conversion to function pointer, as described in1654/// C++11 [expr.prim.lambda]p6.1655static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,1656CXXRecordDecl *Class,1657CXXMethodDecl *CallOperator,1658QualType InvokerFunctionTy) {1659// This conversion is explicitly disabled if the lambda's function has1660// pass_object_size attributes on any of its parameters.1661auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {1662return P->hasAttr<PassObjectSizeAttr>();1663};1664if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))1665return;16661667// Add the conversion to function pointer.1668QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);16691670// Create the type of the conversion function.1671FunctionProtoType::ExtProtoInfo ConvExtInfo(1672S.Context.getDefaultCallingConvention(1673/*IsVariadic=*/false, /*IsCXXMethod=*/true));1674// The conversion function is always const and noexcept.1675ConvExtInfo.TypeQuals = Qualifiers();1676ConvExtInfo.TypeQuals.addConst();1677ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;1678QualType ConvTy =1679S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);16801681SourceLocation Loc = IntroducerRange.getBegin();1682DeclarationName ConversionName1683= S.Context.DeclarationNames.getCXXConversionFunctionName(1684S.Context.getCanonicalType(PtrToFunctionTy));1685// Construct a TypeSourceInfo for the conversion function, and wire1686// all the parameters appropriately for the FunctionProtoTypeLoc1687// so that everything works during transformation/instantiation of1688// generic lambdas.1689// The main reason for wiring up the parameters of the conversion1690// function with that of the call operator is so that constructs1691// like the following work:1692// auto L = [](auto b) { <-- 11693// return [](auto a) -> decltype(a) { <-- 21694// return a;1695// };1696// };1697// int (*fp)(int) = L(5);1698// Because the trailing return type can contain DeclRefExprs that refer1699// to the original call operator's variables, we hijack the call1700// operators ParmVarDecls below.1701TypeSourceInfo *ConvNamePtrToFunctionTSI =1702S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);1703DeclarationNameLoc ConvNameLoc =1704DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);17051706// The conversion function is a conversion to a pointer-to-function.1707TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);1708FunctionProtoTypeLoc ConvTL =1709ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();1710// Get the result of the conversion function which is a pointer-to-function.1711PointerTypeLoc PtrToFunctionTL =1712ConvTL.getReturnLoc().getAs<PointerTypeLoc>();1713// Do the same for the TypeSourceInfo that is used to name the conversion1714// operator.1715PointerTypeLoc ConvNamePtrToFunctionTL =1716ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();17171718// Get the underlying function types that the conversion function will1719// be converting to (should match the type of the call operator).1720FunctionProtoTypeLoc CallOpConvTL =1721PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();1722FunctionProtoTypeLoc CallOpConvNameTL =1723ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();17241725// Wire up the FunctionProtoTypeLocs with the call operator's parameters.1726// These parameter's are essentially used to transform the name and1727// the type of the conversion operator. By using the same parameters1728// as the call operator's we don't have to fix any back references that1729// the trailing return type of the call operator's uses (such as1730// decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)1731// - we can simply use the return type of the call operator, and1732// everything should work.1733SmallVector<ParmVarDecl *, 4> InvokerParams;1734for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {1735ParmVarDecl *From = CallOperator->getParamDecl(I);17361737InvokerParams.push_back(ParmVarDecl::Create(1738S.Context,1739// Temporarily add to the TU. This is set to the invoker below.1740S.Context.getTranslationUnitDecl(), From->getBeginLoc(),1741From->getLocation(), From->getIdentifier(), From->getType(),1742From->getTypeSourceInfo(), From->getStorageClass(),1743/*DefArg=*/nullptr));1744CallOpConvTL.setParam(I, From);1745CallOpConvNameTL.setParam(I, From);1746}17471748CXXConversionDecl *Conversion = CXXConversionDecl::Create(1749S.Context, Class, Loc,1750DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,1751S.getCurFPFeatures().isFPConstrained(),1752/*isInline=*/true, ExplicitSpecifier(),1753S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr1754: ConstexprSpecKind::Unspecified,1755CallOperator->getBody()->getEndLoc());1756Conversion->setAccess(AS_public);1757Conversion->setImplicit(true);17581759// A non-generic lambda may still be a templated entity. We need to preserve1760// constraints when converting the lambda to a function pointer. See GH63181.1761if (Expr *Requires = CallOperator->getTrailingRequiresClause())1762Conversion->setTrailingRequiresClause(Requires);17631764if (Class->isGenericLambda()) {1765// Create a template version of the conversion operator, using the template1766// parameter list of the function call operator.1767FunctionTemplateDecl *TemplateCallOperator =1768CallOperator->getDescribedFunctionTemplate();1769FunctionTemplateDecl *ConversionTemplate =1770FunctionTemplateDecl::Create(S.Context, Class,1771Loc, ConversionName,1772TemplateCallOperator->getTemplateParameters(),1773Conversion);1774ConversionTemplate->setAccess(AS_public);1775ConversionTemplate->setImplicit(true);1776Conversion->setDescribedFunctionTemplate(ConversionTemplate);1777Class->addDecl(ConversionTemplate);1778} else1779Class->addDecl(Conversion);17801781// If the lambda is not static, we need to add a static member1782// function that will be the result of the conversion with a1783// certain unique ID.1784// When it is static we just return the static call operator instead.1785if (CallOperator->isImplicitObjectMemberFunction()) {1786DeclarationName InvokerName =1787&S.Context.Idents.get(getLambdaStaticInvokerName());1788// FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()1789// we should get a prebuilt TrivialTypeSourceInfo from Context1790// using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc1791// then rewire the parameters accordingly, by hoisting up the InvokeParams1792// loop below and then use its Params to set Invoke->setParams(...) below.1793// This would avoid the 'const' qualifier of the calloperator from1794// contaminating the type of the invoker, which is currently adjusted1795// in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the1796// trailing return type of the invoker would require a visitor to rebuild1797// the trailing return type and adjusting all back DeclRefExpr's to refer1798// to the new static invoker parameters - not the call operator's.1799CXXMethodDecl *Invoke = CXXMethodDecl::Create(1800S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),1801InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,1802S.getCurFPFeatures().isFPConstrained(),1803/*isInline=*/true, CallOperator->getConstexprKind(),1804CallOperator->getBody()->getEndLoc());1805for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)1806InvokerParams[I]->setOwningFunction(Invoke);1807Invoke->setParams(InvokerParams);1808Invoke->setAccess(AS_private);1809Invoke->setImplicit(true);1810if (Class->isGenericLambda()) {1811FunctionTemplateDecl *TemplateCallOperator =1812CallOperator->getDescribedFunctionTemplate();1813FunctionTemplateDecl *StaticInvokerTemplate =1814FunctionTemplateDecl::Create(1815S.Context, Class, Loc, InvokerName,1816TemplateCallOperator->getTemplateParameters(), Invoke);1817StaticInvokerTemplate->setAccess(AS_private);1818StaticInvokerTemplate->setImplicit(true);1819Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);1820Class->addDecl(StaticInvokerTemplate);1821} else1822Class->addDecl(Invoke);1823}1824}18251826/// Add a lambda's conversion to function pointers, as described in1827/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a1828/// single pointer conversion. In the event that the default calling convention1829/// for free and member functions is different, it will emit both conventions.1830static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,1831CXXRecordDecl *Class,1832CXXMethodDecl *CallOperator) {1833const FunctionProtoType *CallOpProto =1834CallOperator->getType()->castAs<FunctionProtoType>();18351836repeatForLambdaConversionFunctionCallingConvs(1837S, *CallOpProto, [&](CallingConv CC) {1838QualType InvokerFunctionTy =1839S.getLambdaConversionFunctionResultType(CallOpProto, CC);1840addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,1841InvokerFunctionTy);1842});1843}18441845/// Add a lambda's conversion to block pointer.1846static void addBlockPointerConversion(Sema &S,1847SourceRange IntroducerRange,1848CXXRecordDecl *Class,1849CXXMethodDecl *CallOperator) {1850const FunctionProtoType *CallOpProto =1851CallOperator->getType()->castAs<FunctionProtoType>();1852QualType FunctionTy = S.getLambdaConversionFunctionResultType(1853CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));1854QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);18551856FunctionProtoType::ExtProtoInfo ConversionEPI(1857S.Context.getDefaultCallingConvention(1858/*IsVariadic=*/false, /*IsCXXMethod=*/true));1859ConversionEPI.TypeQuals = Qualifiers();1860ConversionEPI.TypeQuals.addConst();1861QualType ConvTy =1862S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);18631864SourceLocation Loc = IntroducerRange.getBegin();1865DeclarationName Name1866= S.Context.DeclarationNames.getCXXConversionFunctionName(1867S.Context.getCanonicalType(BlockPtrTy));1868DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(1869S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));1870CXXConversionDecl *Conversion = CXXConversionDecl::Create(1871S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,1872S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),1873S.getCurFPFeatures().isFPConstrained(),1874/*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,1875CallOperator->getBody()->getEndLoc());1876Conversion->setAccess(AS_public);1877Conversion->setImplicit(true);1878Class->addDecl(Conversion);1879}18801881ExprResult Sema::BuildCaptureInit(const Capture &Cap,1882SourceLocation ImplicitCaptureLoc,1883bool IsOpenMPMapping) {1884// VLA captures don't have a stored initialization expression.1885if (Cap.isVLATypeCapture())1886return ExprResult();18871888// An init-capture is initialized directly from its stored initializer.1889if (Cap.isInitCapture())1890return cast<VarDecl>(Cap.getVariable())->getInit();18911892// For anything else, build an initialization expression. For an implicit1893// capture, the capture notionally happens at the capture-default, so use1894// that location here.1895SourceLocation Loc =1896ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();18971898// C++11 [expr.prim.lambda]p21:1899// When the lambda-expression is evaluated, the entities that1900// are captured by copy are used to direct-initialize each1901// corresponding non-static data member of the resulting closure1902// object. (For array members, the array elements are1903// direct-initialized in increasing subscript order.) These1904// initializations are performed in the (unspecified) order in1905// which the non-static data members are declared.19061907// C++ [expr.prim.lambda]p12:1908// An entity captured by a lambda-expression is odr-used (3.2) in1909// the scope containing the lambda-expression.1910ExprResult Init;1911IdentifierInfo *Name = nullptr;1912if (Cap.isThisCapture()) {1913QualType ThisTy = getCurrentThisType();1914Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());1915if (Cap.isCopyCapture())1916Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);1917else1918Init = This;1919} else {1920assert(Cap.isVariableCapture() && "unknown kind of capture");1921ValueDecl *Var = Cap.getVariable();1922Name = Var->getIdentifier();1923Init = BuildDeclarationNameExpr(1924CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);1925}19261927// In OpenMP, the capture kind doesn't actually describe how to capture:1928// variables are "mapped" onto the device in a process that does not formally1929// make a copy, even for a "copy capture".1930if (IsOpenMPMapping)1931return Init;19321933if (Init.isInvalid())1934return ExprError();19351936Expr *InitExpr = Init.get();1937InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(1938Name, Cap.getCaptureType(), Loc);1939InitializationKind InitKind =1940InitializationKind::CreateDirect(Loc, Loc, Loc);1941InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);1942return InitSeq.Perform(*this, Entity, InitKind, InitExpr);1943}19441945ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) {1946LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());1947ActOnFinishFunctionBody(LSI.CallOperator, Body);1948return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);1949}19501951static LambdaCaptureDefault1952mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {1953switch (ICS) {1954case CapturingScopeInfo::ImpCap_None:1955return LCD_None;1956case CapturingScopeInfo::ImpCap_LambdaByval:1957return LCD_ByCopy;1958case CapturingScopeInfo::ImpCap_CapturedRegion:1959case CapturingScopeInfo::ImpCap_LambdaByref:1960return LCD_ByRef;1961case CapturingScopeInfo::ImpCap_Block:1962llvm_unreachable("block capture in lambda");1963}1964llvm_unreachable("Unknown implicit capture style");1965}19661967bool Sema::CaptureHasSideEffects(const Capture &From) {1968if (From.isInitCapture()) {1969Expr *Init = cast<VarDecl>(From.getVariable())->getInit();1970if (Init && Init->HasSideEffects(Context))1971return true;1972}19731974if (!From.isCopyCapture())1975return false;19761977const QualType T = From.isThisCapture()1978? getCurrentThisType()->getPointeeType()1979: From.getCaptureType();19801981if (T.isVolatileQualified())1982return true;19831984const Type *BaseT = T->getBaseElementTypeUnsafe();1985if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())1986return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||1987!RD->hasTrivialDestructor();19881989return false;1990}19911992bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,1993const Capture &From) {1994if (CaptureHasSideEffects(From))1995return false;19961997if (From.isVLATypeCapture())1998return false;19992000// FIXME: maybe we should warn on these if we can find a sensible diagnostic2001// message2002if (From.isInitCapture() &&2003From.getVariable()->isPlaceholderVar(getLangOpts()))2004return false;20052006auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);2007if (From.isThisCapture())2008diag << "'this'";2009else2010diag << From.getVariable();2011diag << From.isNonODRUsed();2012diag << FixItHint::CreateRemoval(CaptureRange);2013return true;2014}20152016/// Create a field within the lambda class or captured statement record for the2017/// given capture.2018FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,2019const sema::Capture &Capture) {2020SourceLocation Loc = Capture.getLocation();2021QualType FieldType = Capture.getCaptureType();20222023TypeSourceInfo *TSI = nullptr;2024if (Capture.isVariableCapture()) {2025const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());2026if (Var && Var->isInitCapture())2027TSI = Var->getTypeSourceInfo();2028}20292030// FIXME: Should we really be doing this? A null TypeSourceInfo seems more2031// appropriate, at least for an implicit capture.2032if (!TSI)2033TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);20342035// Build the non-static data member.2036FieldDecl *Field =2037FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,2038/*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,2039/*Mutable=*/false, ICIS_NoInit);2040// If the variable being captured has an invalid type, mark the class as2041// invalid as well.2042if (!FieldType->isDependentType()) {2043if (RequireCompleteSizedType(Loc, FieldType,2044diag::err_field_incomplete_or_sizeless)) {2045RD->setInvalidDecl();2046Field->setInvalidDecl();2047} else {2048NamedDecl *Def;2049FieldType->isIncompleteType(&Def);2050if (Def && Def->isInvalidDecl()) {2051RD->setInvalidDecl();2052Field->setInvalidDecl();2053}2054}2055}2056Field->setImplicit(true);2057Field->setAccess(AS_private);2058RD->addDecl(Field);20592060if (Capture.isVLATypeCapture())2061Field->setCapturedVLAType(Capture.getCapturedVLAType());20622063return Field;2064}20652066ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,2067LambdaScopeInfo *LSI) {2068// Collect information from the lambda scope.2069SmallVector<LambdaCapture, 4> Captures;2070SmallVector<Expr *, 4> CaptureInits;2071SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;2072LambdaCaptureDefault CaptureDefault =2073mapImplicitCaptureStyle(LSI->ImpCaptureStyle);2074CXXRecordDecl *Class;2075CXXMethodDecl *CallOperator;2076SourceRange IntroducerRange;2077bool ExplicitParams;2078bool ExplicitResultType;2079CleanupInfo LambdaCleanup;2080bool ContainsUnexpandedParameterPack;2081bool IsGenericLambda;2082{2083CallOperator = LSI->CallOperator;2084Class = LSI->Lambda;2085IntroducerRange = LSI->IntroducerRange;2086ExplicitParams = LSI->ExplicitParams;2087ExplicitResultType = !LSI->HasImplicitReturnType;2088LambdaCleanup = LSI->Cleanup;2089ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;2090IsGenericLambda = Class->isGenericLambda();20912092CallOperator->setLexicalDeclContext(Class);2093Decl *TemplateOrNonTemplateCallOperatorDecl =2094CallOperator->getDescribedFunctionTemplate()2095? CallOperator->getDescribedFunctionTemplate()2096: cast<Decl>(CallOperator);20972098// FIXME: Is this really the best choice? Keeping the lexical decl context2099// set as CurContext seems more faithful to the source.2100TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);21012102PopExpressionEvaluationContext();21032104// True if the current capture has a used capture or default before it.2105bool CurHasPreviousCapture = CaptureDefault != LCD_None;2106SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?2107CaptureDefaultLoc : IntroducerRange.getBegin();21082109for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {2110const Capture &From = LSI->Captures[I];21112112if (From.isInvalid())2113return ExprError();21142115assert(!From.isBlockCapture() && "Cannot capture __block variables");2116bool IsImplicit = I >= LSI->NumExplicitCaptures;2117SourceLocation ImplicitCaptureLoc =2118IsImplicit ? CaptureDefaultLoc : SourceLocation();21192120// Use source ranges of explicit captures for fixits where available.2121SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];21222123// Warn about unused explicit captures.2124bool IsCaptureUsed = true;2125if (!CurContext->isDependentContext() && !IsImplicit &&2126!From.isODRUsed()) {2127// Initialized captures that are non-ODR used may not be eliminated.2128// FIXME: Where did the IsGenericLambda here come from?2129bool NonODRUsedInitCapture =2130IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();2131if (!NonODRUsedInitCapture) {2132bool IsLast = (I + 1) == LSI->NumExplicitCaptures;2133SourceRange FixItRange;2134if (CaptureRange.isValid()) {2135if (!CurHasPreviousCapture && !IsLast) {2136// If there are no captures preceding this capture, remove the2137// following comma.2138FixItRange = SourceRange(CaptureRange.getBegin(),2139getLocForEndOfToken(CaptureRange.getEnd()));2140} else {2141// Otherwise, remove the comma since the last used capture.2142FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),2143CaptureRange.getEnd());2144}2145}21462147IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);2148}2149}21502151if (CaptureRange.isValid()) {2152CurHasPreviousCapture |= IsCaptureUsed;2153PrevCaptureLoc = CaptureRange.getEnd();2154}21552156// Map the capture to our AST representation.2157LambdaCapture Capture = [&] {2158if (From.isThisCapture()) {2159// Capturing 'this' implicitly with a default of '[=]' is deprecated,2160// because it results in a reference capture. Don't warn prior to2161// C++2a; there's nothing that can be done about it before then.2162if (getLangOpts().CPlusPlus20 && IsImplicit &&2163CaptureDefault == LCD_ByCopy) {2164Diag(From.getLocation(), diag::warn_deprecated_this_capture);2165Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)2166<< FixItHint::CreateInsertion(2167getLocForEndOfToken(CaptureDefaultLoc), ", this");2168}2169return LambdaCapture(From.getLocation(), IsImplicit,2170From.isCopyCapture() ? LCK_StarThis : LCK_This);2171} else if (From.isVLATypeCapture()) {2172return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);2173} else {2174assert(From.isVariableCapture() && "unknown kind of capture");2175ValueDecl *Var = From.getVariable();2176LambdaCaptureKind Kind =2177From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;2178return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,2179From.getEllipsisLoc());2180}2181}();21822183// Form the initializer for the capture field.2184ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);21852186// FIXME: Skip this capture if the capture is not used, the initializer2187// has no side-effects, the type of the capture is trivial, and the2188// lambda is not externally visible.21892190// Add a FieldDecl for the capture and form its initializer.2191BuildCaptureField(Class, From);2192Captures.push_back(Capture);2193CaptureInits.push_back(Init.get());21942195if (LangOpts.CUDA)2196CUDA().CheckLambdaCapture(CallOperator, From);2197}21982199Class->setCaptures(Context, Captures);22002201// C++11 [expr.prim.lambda]p6:2202// The closure type for a lambda-expression with no lambda-capture2203// has a public non-virtual non-explicit const conversion function2204// to pointer to function having the same parameter and return2205// types as the closure type's function call operator.2206if (Captures.empty() && CaptureDefault == LCD_None)2207addFunctionPointerConversions(*this, IntroducerRange, Class,2208CallOperator);22092210// Objective-C++:2211// The closure type for a lambda-expression has a public non-virtual2212// non-explicit const conversion function to a block pointer having the2213// same parameter and return types as the closure type's function call2214// operator.2215// FIXME: Fix generic lambda to block conversions.2216if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)2217addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);22182219// Finalize the lambda class.2220SmallVector<Decl*, 4> Fields(Class->fields());2221ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),2222SourceLocation(), ParsedAttributesView());2223CheckCompletedCXXClass(nullptr, Class);2224}22252226Cleanup.mergeFrom(LambdaCleanup);22272228LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,2229CaptureDefault, CaptureDefaultLoc,2230ExplicitParams, ExplicitResultType,2231CaptureInits, EndLoc,2232ContainsUnexpandedParameterPack);2233// If the lambda expression's call operator is not explicitly marked constexpr2234// and we are not in a dependent context, analyze the call operator to infer2235// its constexpr-ness, suppressing diagnostics while doing so.2236if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&2237!CallOperator->isConstexpr() &&2238!isa<CoroutineBodyStmt>(CallOperator->getBody()) &&2239!Class->getDeclContext()->isDependentContext()) {2240CallOperator->setConstexprKind(2241CheckConstexprFunctionDefinition(CallOperator,2242CheckConstexprKind::CheckValid)2243? ConstexprSpecKind::Constexpr2244: ConstexprSpecKind::Unspecified);2245}22462247// Emit delayed shadowing warnings now that the full capture list is known.2248DiagnoseShadowingLambdaDecls(LSI);22492250if (!CurContext->isDependentContext()) {2251switch (ExprEvalContexts.back().Context) {2252// C++11 [expr.prim.lambda]p2:2253// A lambda-expression shall not appear in an unevaluated operand2254// (Clause 5).2255case ExpressionEvaluationContext::Unevaluated:2256case ExpressionEvaluationContext::UnevaluatedList:2257case ExpressionEvaluationContext::UnevaluatedAbstract:2258// C++1y [expr.const]p2:2259// A conditional-expression e is a core constant expression unless the2260// evaluation of e, following the rules of the abstract machine, would2261// evaluate [...] a lambda-expression.2262//2263// This is technically incorrect, there are some constant evaluated contexts2264// where this should be allowed. We should probably fix this when DR1607 is2265// ratified, it lays out the exact set of conditions where we shouldn't2266// allow a lambda-expression.2267case ExpressionEvaluationContext::ConstantEvaluated:2268case ExpressionEvaluationContext::ImmediateFunctionContext:2269// We don't actually diagnose this case immediately, because we2270// could be within a context where we might find out later that2271// the expression is potentially evaluated (e.g., for typeid).2272ExprEvalContexts.back().Lambdas.push_back(Lambda);2273break;22742275case ExpressionEvaluationContext::DiscardedStatement:2276case ExpressionEvaluationContext::PotentiallyEvaluated:2277case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:2278break;2279}2280}22812282return MaybeBindToTemporary(Lambda);2283}22842285ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,2286SourceLocation ConvLocation,2287CXXConversionDecl *Conv,2288Expr *Src) {2289// Make sure that the lambda call operator is marked used.2290CXXRecordDecl *Lambda = Conv->getParent();2291CXXMethodDecl *CallOperator2292= cast<CXXMethodDecl>(2293Lambda->lookup(2294Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());2295CallOperator->setReferenced();2296CallOperator->markUsed(Context);22972298ExprResult Init = PerformCopyInitialization(2299InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),2300CurrentLocation, Src);2301if (!Init.isInvalid())2302Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);23032304if (Init.isInvalid())2305return ExprError();23062307// Create the new block to be returned.2308BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);23092310// Set the type information.2311Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());2312Block->setIsVariadic(CallOperator->isVariadic());2313Block->setBlockMissingReturnType(false);23142315// Add parameters.2316SmallVector<ParmVarDecl *, 4> BlockParams;2317for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {2318ParmVarDecl *From = CallOperator->getParamDecl(I);2319BlockParams.push_back(ParmVarDecl::Create(2320Context, Block, From->getBeginLoc(), From->getLocation(),2321From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),2322From->getStorageClass(),2323/*DefArg=*/nullptr));2324}2325Block->setParams(BlockParams);23262327Block->setIsConversionFromLambda(true);23282329// Add capture. The capture uses a fake variable, which doesn't correspond2330// to any actual memory location. However, the initializer copy-initializes2331// the lambda object.2332TypeSourceInfo *CapVarTSI =2333Context.getTrivialTypeSourceInfo(Src->getType());2334VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,2335ConvLocation, nullptr,2336Src->getType(), CapVarTSI,2337SC_None);2338BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,2339/*nested=*/false, /*copy=*/Init.get());2340Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);23412342// Add a fake function body to the block. IR generation is responsible2343// for filling in the actual body, which cannot be expressed as an AST.2344Block->setBody(new (Context) CompoundStmt(ConvLocation));23452346// Create the block literal expression.2347Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());2348ExprCleanupObjects.push_back(Block);2349Cleanup.setExprNeedsCleanups(true);23502351return BuildBlock;2352}23532354static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) {2355if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) {2356while (FD->getInstantiatedFromMemberFunction())2357FD = FD->getInstantiatedFromMemberFunction();2358return FD;2359}23602361if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)2362return FD->getInstantiatedFromDecl();23632364FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();2365if (!FTD)2366return nullptr;23672368while (FTD->getInstantiatedFromMemberTemplate())2369FTD = FTD->getInstantiatedFromMemberTemplate();23702371return FTD->getTemplatedDecl();2372}23732374Sema::LambdaScopeForCallOperatorInstantiationRAII::2375LambdaScopeForCallOperatorInstantiationRAII(2376Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,2377LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)2378: FunctionScopeRAII(SemaRef) {2379if (!isLambdaCallOperator(FD)) {2380FunctionScopeRAII::disable();2381return;2382}23832384SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));23852386FunctionDecl *FDPattern = getPatternFunctionDecl(FD);2387if (!FDPattern)2388return;23892390SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);23912392if (!ShouldAddDeclsFromParentScope)2393return;23942395llvm::SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 4>2396ParentInstantiations;2397while (true) {2398FDPattern =2399dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));2400FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));24012402if (!FDPattern || !FD)2403break;24042405ParentInstantiations.emplace_back(FDPattern, FD);2406}24072408// Add instantiated parameters and local vars to scopes, starting from the2409// outermost lambda to the innermost lambda. This ordering ensures that2410// parameters in inner lambdas can correctly depend on those defined2411// in outer lambdas, e.g. auto L = [](auto... x) {2412// return [](decltype(x)... y) { }; // `y` depends on `x`2413// };24142415for (const auto &[FDPattern, FD] : llvm::reverse(ParentInstantiations)) {2416SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);2417SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);2418}2419}242024212422