1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ lambda expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 #include "clang/Sema/SemaLambda.h" 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTLambda.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/ExprCXX.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Sema/DeclSpec.h" 19 #include "clang/Sema/Initialization.h" 20 #include "clang/Sema/Lookup.h" 21 #include "clang/Sema/Scope.h" 22 #include "clang/Sema/ScopeInfo.h" 23 #include "clang/Sema/SemaCUDA.h" 24 #include "clang/Sema/SemaInternal.h" 25 #include "clang/Sema/SemaOpenMP.h" 26 #include "clang/Sema/Template.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include <optional> 29 using namespace clang; 30 using namespace sema; 31 32 /// Examines the FunctionScopeInfo stack to determine the nearest 33 /// enclosing lambda (to the current lambda) that is 'capture-ready' for 34 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 35 /// If successful, returns the index into Sema's FunctionScopeInfo stack 36 /// of the capture-ready lambda's LambdaScopeInfo. 37 /// 38 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current 39 /// lambda - is on top) to determine the index of the nearest enclosing/outer 40 /// lambda that is ready to capture the \p VarToCapture being referenced in 41 /// the current lambda. 42 /// As we climb down the stack, we want the index of the first such lambda - 43 /// that is the lambda with the highest index that is 'capture-ready'. 44 /// 45 /// A lambda 'L' is capture-ready for 'V' (var or this) if: 46 /// - its enclosing context is non-dependent 47 /// - and if the chain of lambdas between L and the lambda in which 48 /// V is potentially used (i.e. the lambda at the top of the scope info 49 /// stack), can all capture or have already captured V. 50 /// If \p VarToCapture is 'null' then we are trying to capture 'this'. 51 /// 52 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked 53 /// for whether it is 'capture-capable' (see 54 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly 55 /// capture. 56 /// 57 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 58 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 59 /// is at the top of the stack and has the highest index. 60 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 61 /// 62 /// \returns An std::optional<unsigned> Index that if evaluates to 'true' 63 /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost 64 /// lambda which is capture-ready. If the return value evaluates to 'false' 65 /// then no lambda is capture-ready for \p VarToCapture. 66 67 static inline std::optional<unsigned> 68 getStackIndexOfNearestEnclosingCaptureReadyLambda( 69 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, 70 ValueDecl *VarToCapture) { 71 // Label failure to capture. 72 const std::optional<unsigned> NoLambdaIsCaptureReady; 73 74 // Ignore all inner captured regions. 75 unsigned CurScopeIndex = FunctionScopes.size() - 1; 76 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>( 77 FunctionScopes[CurScopeIndex])) 78 --CurScopeIndex; 79 assert( 80 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && 81 "The function on the top of sema's function-info stack must be a lambda"); 82 83 // If VarToCapture is null, we are attempting to capture 'this'. 84 const bool IsCapturingThis = !VarToCapture; 85 const bool IsCapturingVariable = !IsCapturingThis; 86 87 // Start with the current lambda at the top of the stack (highest index). 88 DeclContext *EnclosingDC = 89 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator; 90 91 do { 92 const clang::sema::LambdaScopeInfo *LSI = 93 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]); 94 // IF we have climbed down to an intervening enclosing lambda that contains 95 // the variable declaration - it obviously can/must not capture the 96 // variable. 97 // Since its enclosing DC is dependent, all the lambdas between it and the 98 // innermost nested lambda are dependent (otherwise we wouldn't have 99 // arrived here) - so we don't yet have a lambda that can capture the 100 // variable. 101 if (IsCapturingVariable && 102 VarToCapture->getDeclContext()->Equals(EnclosingDC)) 103 return NoLambdaIsCaptureReady; 104 105 // For an enclosing lambda to be capture ready for an entity, all 106 // intervening lambda's have to be able to capture that entity. If even 107 // one of the intervening lambda's is not capable of capturing the entity 108 // then no enclosing lambda can ever capture that entity. 109 // For e.g. 110 // const int x = 10; 111 // [=](auto a) { #1 112 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x' 113 // [=](auto c) { #3 114 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2 115 // }; }; }; 116 // If they do not have a default implicit capture, check to see 117 // if the entity has already been explicitly captured. 118 // If even a single dependent enclosing lambda lacks the capability 119 // to ever capture this variable, there is no further enclosing 120 // non-dependent lambda that can capture this variable. 121 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) { 122 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture)) 123 return NoLambdaIsCaptureReady; 124 if (IsCapturingThis && !LSI->isCXXThisCaptured()) 125 return NoLambdaIsCaptureReady; 126 } 127 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); 128 129 assert(CurScopeIndex); 130 --CurScopeIndex; 131 } while (!EnclosingDC->isTranslationUnit() && 132 EnclosingDC->isDependentContext() && 133 isLambdaCallOperator(EnclosingDC)); 134 135 assert(CurScopeIndex < (FunctionScopes.size() - 1)); 136 // If the enclosingDC is not dependent, then the immediately nested lambda 137 // (one index above) is capture-ready. 138 if (!EnclosingDC->isDependentContext()) 139 return CurScopeIndex + 1; 140 return NoLambdaIsCaptureReady; 141 } 142 143 /// Examines the FunctionScopeInfo stack to determine the nearest 144 /// enclosing lambda (to the current lambda) that is 'capture-capable' for 145 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 146 /// If successful, returns the index into Sema's FunctionScopeInfo stack 147 /// of the capture-capable lambda's LambdaScopeInfo. 148 /// 149 /// Given the current stack of lambdas being processed by Sema and 150 /// the variable of interest, to identify the nearest enclosing lambda (to the 151 /// current lambda at the top of the stack) that can truly capture 152 /// a variable, it has to have the following two properties: 153 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': 154 /// - climb down the stack (i.e. starting from the innermost and examining 155 /// each outer lambda step by step) checking if each enclosing 156 /// lambda can either implicitly or explicitly capture the variable. 157 /// Record the first such lambda that is enclosed in a non-dependent 158 /// context. If no such lambda currently exists return failure. 159 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly 160 /// capture the variable by checking all its enclosing lambdas: 161 /// - check if all outer lambdas enclosing the 'capture-ready' lambda 162 /// identified above in 'a' can also capture the variable (this is done 163 /// via tryCaptureVariable for variables and CheckCXXThisCapture for 164 /// 'this' by passing in the index of the Lambda identified in step 'a') 165 /// 166 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 167 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 168 /// is at the top of the stack. 169 /// 170 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 171 /// 172 /// 173 /// \returns An std::optional<unsigned> Index that if evaluates to 'true' 174 /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost 175 /// lambda which is capture-capable. If the return value evaluates to 'false' 176 /// then no lambda is capture-capable for \p VarToCapture. 177 178 std::optional<unsigned> 179 clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( 180 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, 181 ValueDecl *VarToCapture, Sema &S) { 182 183 const std::optional<unsigned> NoLambdaIsCaptureCapable; 184 185 const std::optional<unsigned> OptionalStackIndex = 186 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, 187 VarToCapture); 188 if (!OptionalStackIndex) 189 return NoLambdaIsCaptureCapable; 190 191 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex; 192 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || 193 S.getCurGenericLambda()) && 194 "The capture ready lambda for a potential capture can only be the " 195 "current lambda if it is a generic lambda"); 196 197 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = 198 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); 199 200 // If VarToCapture is null, we are attempting to capture 'this' 201 const bool IsCapturingThis = !VarToCapture; 202 const bool IsCapturingVariable = !IsCapturingThis; 203 204 if (IsCapturingVariable) { 205 // Check if the capture-ready lambda can truly capture the variable, by 206 // checking whether all enclosing lambdas of the capture-ready lambda allow 207 // the capture - i.e. make sure it is capture-capable. 208 QualType CaptureType, DeclRefType; 209 const bool CanCaptureVariable = 210 !S.tryCaptureVariable(VarToCapture, 211 /*ExprVarIsUsedInLoc*/ SourceLocation(), 212 clang::Sema::TryCapture_Implicit, 213 /*EllipsisLoc*/ SourceLocation(), 214 /*BuildAndDiagnose*/ false, CaptureType, 215 DeclRefType, &IndexOfCaptureReadyLambda); 216 if (!CanCaptureVariable) 217 return NoLambdaIsCaptureCapable; 218 } else { 219 // Check if the capture-ready lambda can truly capture 'this' by checking 220 // whether all enclosing lambdas of the capture-ready lambda can capture 221 // 'this'. 222 const bool CanCaptureThis = 223 !S.CheckCXXThisCapture( 224 CaptureReadyLambdaLSI->PotentialThisCaptureLocation, 225 /*Explicit*/ false, /*BuildAndDiagnose*/ false, 226 &IndexOfCaptureReadyLambda); 227 if (!CanCaptureThis) 228 return NoLambdaIsCaptureCapable; 229 } 230 return IndexOfCaptureReadyLambda; 231 } 232 233 static inline TemplateParameterList * 234 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { 235 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) { 236 LSI->GLTemplateParameterList = TemplateParameterList::Create( 237 SemaRef.Context, 238 /*Template kw loc*/ SourceLocation(), 239 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(), 240 LSI->TemplateParams, 241 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(), 242 LSI->RequiresClause.get()); 243 } 244 return LSI->GLTemplateParameterList; 245 } 246 247 CXXRecordDecl * 248 Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, 249 unsigned LambdaDependencyKind, 250 LambdaCaptureDefault CaptureDefault) { 251 DeclContext *DC = CurContext; 252 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 253 DC = DC->getParent(); 254 255 bool IsGenericLambda = 256 Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this); 257 // Start constructing the lambda class. 258 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda( 259 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind, 260 IsGenericLambda, CaptureDefault); 261 DC->addDecl(Class); 262 263 return Class; 264 } 265 266 /// Determine whether the given context is or is enclosed in an inline 267 /// function. 268 static bool isInInlineFunction(const DeclContext *DC) { 269 while (!DC->isFileContext()) { 270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 271 if (FD->isInlined()) 272 return true; 273 274 DC = DC->getLexicalParent(); 275 } 276 277 return false; 278 } 279 280 std::tuple<MangleNumberingContext *, Decl *> 281 Sema::getCurrentMangleNumberContext(const DeclContext *DC) { 282 // Compute the context for allocating mangling numbers in the current 283 // expression, if the ABI requires them. 284 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; 285 286 enum ContextKind { 287 Normal, 288 DefaultArgument, 289 DataMember, 290 InlineVariable, 291 TemplatedVariable, 292 Concept 293 } Kind = Normal; 294 295 bool IsInNonspecializedTemplate = 296 inTemplateInstantiation() || CurContext->isDependentContext(); 297 298 // Default arguments of member function parameters that appear in a class 299 // definition, as well as the initializers of data members, receive special 300 // treatment. Identify them. 301 if (ManglingContextDecl) { 302 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { 303 if (const DeclContext *LexicalDC 304 = Param->getDeclContext()->getLexicalParent()) 305 if (LexicalDC->isRecord()) 306 Kind = DefaultArgument; 307 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { 308 if (Var->getMostRecentDecl()->isInline()) 309 Kind = InlineVariable; 310 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate) 311 Kind = TemplatedVariable; 312 else if (Var->getDescribedVarTemplate()) 313 Kind = TemplatedVariable; 314 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 315 if (!VTS->isExplicitSpecialization()) 316 Kind = TemplatedVariable; 317 } 318 } else if (isa<FieldDecl>(ManglingContextDecl)) { 319 Kind = DataMember; 320 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) { 321 Kind = Concept; 322 } 323 } 324 325 // Itanium ABI [5.1.7]: 326 // In the following contexts [...] the one-definition rule requires closure 327 // types in different translation units to "correspond": 328 switch (Kind) { 329 case Normal: { 330 // -- the bodies of inline or templated functions 331 if ((IsInNonspecializedTemplate && 332 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) || 333 isInInlineFunction(CurContext)) { 334 while (auto *CD = dyn_cast<CapturedDecl>(DC)) 335 DC = CD->getParent(); 336 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr); 337 } 338 339 return std::make_tuple(nullptr, nullptr); 340 } 341 342 case Concept: 343 // Concept definitions aren't code generated and thus aren't mangled, 344 // however the ManglingContextDecl is important for the purposes of 345 // re-forming the template argument list of the lambda for constraint 346 // evaluation. 347 case DataMember: 348 // -- default member initializers 349 case DefaultArgument: 350 // -- default arguments appearing in class definitions 351 case InlineVariable: 352 case TemplatedVariable: 353 // -- the initializers of inline or templated variables 354 return std::make_tuple( 355 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl, 356 ManglingContextDecl), 357 ManglingContextDecl); 358 } 359 360 llvm_unreachable("unexpected context"); 361 } 362 363 static QualType 364 buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, 365 TemplateParameterList *TemplateParams, 366 TypeSourceInfo *MethodTypeInfo) { 367 assert(MethodTypeInfo && "expected a non null type"); 368 369 QualType MethodType = MethodTypeInfo->getType(); 370 // If a lambda appears in a dependent context or is a generic lambda (has 371 // template parameters) and has an 'auto' return type, deduce it to a 372 // dependent type. 373 if (Class->isDependentContext() || TemplateParams) { 374 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); 375 QualType Result = FPT->getReturnType(); 376 if (Result->isUndeducedType()) { 377 Result = S.SubstAutoTypeDependent(Result); 378 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(), 379 FPT->getExtProtoInfo()); 380 } 381 } 382 return MethodType; 383 } 384 385 // [C++2b] [expr.prim.lambda.closure] p4 386 // Given a lambda with a lambda-capture, the type of the explicit object 387 // parameter, if any, of the lambda's function call operator (possibly 388 // instantiated from a function call operator template) shall be either: 389 // - the closure type, 390 // - class type publicly and unambiguously derived from the closure type, or 391 // - a reference to a possibly cv-qualified such type. 392 bool Sema::DiagnoseInvalidExplicitObjectParameterInLambda( 393 CXXMethodDecl *Method, SourceLocation CallLoc) { 394 if (!isLambdaCallWithExplicitObjectParameter(Method)) 395 return false; 396 CXXRecordDecl *RD = Method->getParent(); 397 if (Method->getType()->isDependentType()) 398 return false; 399 if (RD->isCapturelessLambda()) 400 return false; 401 402 ParmVarDecl *Param = Method->getParamDecl(0); 403 QualType ExplicitObjectParameterType = Param->getType() 404 .getNonReferenceType() 405 .getUnqualifiedType() 406 .getDesugaredType(getASTContext()); 407 QualType LambdaType = getASTContext().getRecordType(RD); 408 if (LambdaType == ExplicitObjectParameterType) 409 return false; 410 411 // Don't check the same instantiation twice. 412 // 413 // If this call operator is ill-formed, there is no point in issuing 414 // a diagnostic every time it is called because the problem is in the 415 // definition of the derived type, not at the call site. 416 // 417 // FIXME: Move this check to where we instantiate the method? This should 418 // be possible, but the naive approach of just marking the method as invalid 419 // leads to us emitting more diagnostics than we should have to for this case 420 // (1 error here *and* 1 error about there being no matching overload at the 421 // call site). It might be possible to avoid that by also checking if there 422 // is an empty cast path for the method stored in the context (signalling that 423 // we've already diagnosed it) and then just not building the call, but that 424 // doesn't really seem any simpler than diagnosing it at the call site... 425 if (auto It = Context.LambdaCastPaths.find(Method); 426 It != Context.LambdaCastPaths.end()) 427 return It->second.empty(); 428 429 CXXCastPath &Path = Context.LambdaCastPaths[Method]; 430 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 431 /*DetectVirtual=*/false); 432 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType, 433 Paths)) { 434 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda) 435 << ExplicitObjectParameterType; 436 return true; 437 } 438 439 if (Paths.isAmbiguous(LambdaType->getCanonicalTypeUnqualified())) { 440 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths); 441 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base) 442 << LambdaType << PathsDisplay; 443 return true; 444 } 445 446 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType, 447 Paths.front(), 448 diag::err_explicit_object_lambda_inaccessible_base)) 449 return true; 450 451 BuildBasePathArray(Paths, Path); 452 return false; 453 } 454 455 void Sema::handleLambdaNumbering( 456 CXXRecordDecl *Class, CXXMethodDecl *Method, 457 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) { 458 if (NumberingOverride) { 459 Class->setLambdaNumbering(*NumberingOverride); 460 return; 461 } 462 463 ContextRAII ManglingContext(*this, Class->getDeclContext()); 464 465 auto getMangleNumberingContext = 466 [this](CXXRecordDecl *Class, 467 Decl *ManglingContextDecl) -> MangleNumberingContext * { 468 // Get mangle numbering context if there's any extra decl context. 469 if (ManglingContextDecl) 470 return &Context.getManglingNumberContext( 471 ASTContext::NeedExtraManglingDecl, ManglingContextDecl); 472 // Otherwise, from that lambda's decl context. 473 auto DC = Class->getDeclContext(); 474 while (auto *CD = dyn_cast<CapturedDecl>(DC)) 475 DC = CD->getParent(); 476 return &Context.getManglingNumberContext(DC); 477 }; 478 479 CXXRecordDecl::LambdaNumbering Numbering; 480 MangleNumberingContext *MCtx; 481 std::tie(MCtx, Numbering.ContextDecl) = 482 getCurrentMangleNumberContext(Class->getDeclContext()); 483 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice || 484 getLangOpts().SYCLIsHost)) { 485 // Force lambda numbering in CUDA/HIP as we need to name lambdas following 486 // ODR. Both device- and host-compilation need to have a consistent naming 487 // on kernel functions. As lambdas are potential part of these `__global__` 488 // function names, they needs numbering following ODR. 489 // Also force for SYCL, since we need this for the 490 // __builtin_sycl_unique_stable_name implementation, which depends on lambda 491 // mangling. 492 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl); 493 assert(MCtx && "Retrieving mangle numbering context failed!"); 494 Numbering.HasKnownInternalLinkage = true; 495 } 496 if (MCtx) { 497 Numbering.IndexInContext = MCtx->getNextLambdaIndex(); 498 Numbering.ManglingNumber = MCtx->getManglingNumber(Method); 499 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method); 500 Class->setLambdaNumbering(Numbering); 501 502 if (auto *Source = 503 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 504 Source->AssignedLambdaNumbering(Class); 505 } 506 } 507 508 static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, 509 CXXMethodDecl *CallOperator, 510 bool ExplicitResultType) { 511 if (ExplicitResultType) { 512 LSI->HasImplicitReturnType = false; 513 LSI->ReturnType = CallOperator->getReturnType(); 514 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType()) 515 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType, 516 diag::err_lambda_incomplete_result); 517 } else { 518 LSI->HasImplicitReturnType = true; 519 } 520 } 521 522 void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, 523 SourceRange IntroducerRange, 524 LambdaCaptureDefault CaptureDefault, 525 SourceLocation CaptureDefaultLoc, 526 bool ExplicitParams, bool Mutable) { 527 LSI->CallOperator = CallOperator; 528 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 529 LSI->Lambda = LambdaClass; 530 if (CaptureDefault == LCD_ByCopy) 531 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 532 else if (CaptureDefault == LCD_ByRef) 533 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 534 LSI->CaptureDefaultLoc = CaptureDefaultLoc; 535 LSI->IntroducerRange = IntroducerRange; 536 LSI->ExplicitParams = ExplicitParams; 537 LSI->Mutable = Mutable; 538 } 539 540 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 541 LSI->finishedExplicitCaptures(); 542 } 543 544 void Sema::ActOnLambdaExplicitTemplateParameterList( 545 LambdaIntroducer &Intro, SourceLocation LAngleLoc, 546 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, 547 ExprResult RequiresClause) { 548 LambdaScopeInfo *LSI = getCurLambda(); 549 assert(LSI && "Expected a lambda scope"); 550 assert(LSI->NumExplicitTemplateParams == 0 && 551 "Already acted on explicit template parameters"); 552 assert(LSI->TemplateParams.empty() && 553 "Explicit template parameters should come " 554 "before invented (auto) ones"); 555 assert(!TParams.empty() && 556 "No template parameters to act on"); 557 LSI->TemplateParams.append(TParams.begin(), TParams.end()); 558 LSI->NumExplicitTemplateParams = TParams.size(); 559 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc}; 560 LSI->RequiresClause = RequiresClause; 561 } 562 563 /// If this expression is an enumerator-like expression of some type 564 /// T, return the type T; otherwise, return null. 565 /// 566 /// Pointer comparisons on the result here should always work because 567 /// it's derived from either the parent of an EnumConstantDecl 568 /// (i.e. the definition) or the declaration returned by 569 /// EnumType::getDecl() (i.e. the definition). 570 static EnumDecl *findEnumForBlockReturn(Expr *E) { 571 // An expression is an enumerator-like expression of type T if, 572 // ignoring parens and parens-like expressions: 573 E = E->IgnoreParens(); 574 575 // - it is an enumerator whose enum type is T or 576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 577 if (EnumConstantDecl *D 578 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 579 return cast<EnumDecl>(D->getDeclContext()); 580 } 581 return nullptr; 582 } 583 584 // - it is a comma expression whose RHS is an enumerator-like 585 // expression of type T or 586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 587 if (BO->getOpcode() == BO_Comma) 588 return findEnumForBlockReturn(BO->getRHS()); 589 return nullptr; 590 } 591 592 // - it is a statement-expression whose value expression is an 593 // enumerator-like expression of type T or 594 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 595 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) 596 return findEnumForBlockReturn(last); 597 return nullptr; 598 } 599 600 // - it is a ternary conditional operator (not the GNU ?: 601 // extension) whose second and third operands are 602 // enumerator-like expressions of type T or 603 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 604 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) 605 if (ED == findEnumForBlockReturn(CO->getFalseExpr())) 606 return ED; 607 return nullptr; 608 } 609 610 // (implicitly:) 611 // - it is an implicit integral conversion applied to an 612 // enumerator-like expression of type T or 613 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 614 // We can sometimes see integral conversions in valid 615 // enumerator-like expressions. 616 if (ICE->getCastKind() == CK_IntegralCast) 617 return findEnumForBlockReturn(ICE->getSubExpr()); 618 619 // Otherwise, just rely on the type. 620 } 621 622 // - it is an expression of that formal enum type. 623 if (const EnumType *ET = E->getType()->getAs<EnumType>()) { 624 return ET->getDecl(); 625 } 626 627 // Otherwise, nope. 628 return nullptr; 629 } 630 631 /// Attempt to find a type T for which the returned expression of the 632 /// given statement is an enumerator-like expression of that type. 633 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { 634 if (Expr *retValue = ret->getRetValue()) 635 return findEnumForBlockReturn(retValue); 636 return nullptr; 637 } 638 639 /// Attempt to find a common type T for which all of the returned 640 /// expressions in a block are enumerator-like expressions of that 641 /// type. 642 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { 643 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); 644 645 // Try to find one for the first return. 646 EnumDecl *ED = findEnumForBlockReturn(*i); 647 if (!ED) return nullptr; 648 649 // Check that the rest of the returns have the same enum. 650 for (++i; i != e; ++i) { 651 if (findEnumForBlockReturn(*i) != ED) 652 return nullptr; 653 } 654 655 // Never infer an anonymous enum type. 656 if (!ED->hasNameForLinkage()) return nullptr; 657 658 return ED; 659 } 660 661 /// Adjust the given return statements so that they formally return 662 /// the given type. It should require, at most, an IntegralCast. 663 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, 664 QualType returnType) { 665 for (ArrayRef<ReturnStmt*>::iterator 666 i = returns.begin(), e = returns.end(); i != e; ++i) { 667 ReturnStmt *ret = *i; 668 Expr *retValue = ret->getRetValue(); 669 if (S.Context.hasSameType(retValue->getType(), returnType)) 670 continue; 671 672 // Right now we only support integral fixup casts. 673 assert(returnType->isIntegralOrUnscopedEnumerationType()); 674 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); 675 676 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); 677 678 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue); 679 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E, 680 /*base path*/ nullptr, VK_PRValue, 681 FPOptionsOverride()); 682 if (cleanups) { 683 cleanups->setSubExpr(E); 684 } else { 685 ret->setRetValue(E); 686 } 687 } 688 } 689 690 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { 691 assert(CSI.HasImplicitReturnType); 692 // If it was ever a placeholder, it had to been deduced to DependentTy. 693 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 694 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && 695 "lambda expressions use auto deduction in C++14 onwards"); 696 697 // C++ core issue 975: 698 // If a lambda-expression does not include a trailing-return-type, 699 // it is as if the trailing-return-type denotes the following type: 700 // - if there are no return statements in the compound-statement, 701 // or all return statements return either an expression of type 702 // void or no expression or braced-init-list, the type void; 703 // - otherwise, if all return statements return an expression 704 // and the types of the returned expressions after 705 // lvalue-to-rvalue conversion (4.1 [conv.lval]), 706 // array-to-pointer conversion (4.2 [conv.array]), and 707 // function-to-pointer conversion (4.3 [conv.func]) are the 708 // same, that common type; 709 // - otherwise, the program is ill-formed. 710 // 711 // C++ core issue 1048 additionally removes top-level cv-qualifiers 712 // from the types of returned expressions to match the C++14 auto 713 // deduction rules. 714 // 715 // In addition, in blocks in non-C++ modes, if all of the return 716 // statements are enumerator-like expressions of some type T, where 717 // T has a name for linkage, then we infer the return type of the 718 // block to be that type. 719 720 // First case: no return statements, implicit void return type. 721 ASTContext &Ctx = getASTContext(); 722 if (CSI.Returns.empty()) { 723 // It's possible there were simply no /valid/ return statements. 724 // In this case, the first one we found may have at least given us a type. 725 if (CSI.ReturnType.isNull()) 726 CSI.ReturnType = Ctx.VoidTy; 727 return; 728 } 729 730 // Second case: at least one return statement has dependent type. 731 // Delay type checking until instantiation. 732 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); 733 if (CSI.ReturnType->isDependentType()) 734 return; 735 736 // Try to apply the enum-fuzz rule. 737 if (!getLangOpts().CPlusPlus) { 738 assert(isa<BlockScopeInfo>(CSI)); 739 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); 740 if (ED) { 741 CSI.ReturnType = Context.getTypeDeclType(ED); 742 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); 743 return; 744 } 745 } 746 747 // Third case: only one return statement. Don't bother doing extra work! 748 if (CSI.Returns.size() == 1) 749 return; 750 751 // General case: many return statements. 752 // Check that they all have compatible return types. 753 754 // We require the return types to strictly match here. 755 // Note that we've already done the required promotions as part of 756 // processing the return statement. 757 for (const ReturnStmt *RS : CSI.Returns) { 758 const Expr *RetE = RS->getRetValue(); 759 760 QualType ReturnType = 761 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType(); 762 if (Context.getCanonicalFunctionResultType(ReturnType) == 763 Context.getCanonicalFunctionResultType(CSI.ReturnType)) { 764 // Use the return type with the strictest possible nullability annotation. 765 auto RetTyNullability = ReturnType->getNullability(); 766 auto BlockNullability = CSI.ReturnType->getNullability(); 767 if (BlockNullability && 768 (!RetTyNullability || 769 hasWeakerNullability(*RetTyNullability, *BlockNullability))) 770 CSI.ReturnType = ReturnType; 771 continue; 772 } 773 774 // FIXME: This is a poor diagnostic for ReturnStmts without expressions. 775 // TODO: It's possible that the *first* return is the divergent one. 776 Diag(RS->getBeginLoc(), 777 diag::err_typecheck_missing_return_type_incompatible) 778 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI); 779 // Continue iterating so that we keep emitting diagnostics. 780 } 781 } 782 783 QualType Sema::buildLambdaInitCaptureInitialization( 784 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 785 std::optional<unsigned> NumExpansions, IdentifierInfo *Id, 786 bool IsDirectInit, Expr *&Init) { 787 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to 788 // deduce against. 789 QualType DeductType = Context.getAutoDeductType(); 790 TypeLocBuilder TLB; 791 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType); 792 TL.setNameLoc(Loc); 793 if (ByRef) { 794 DeductType = BuildReferenceType(DeductType, true, Loc, Id); 795 assert(!DeductType.isNull() && "can't build reference to auto"); 796 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); 797 } 798 if (EllipsisLoc.isValid()) { 799 if (Init->containsUnexpandedParameterPack()) { 800 Diag(EllipsisLoc, getLangOpts().CPlusPlus20 801 ? diag::warn_cxx17_compat_init_capture_pack 802 : diag::ext_init_capture_pack); 803 DeductType = Context.getPackExpansionType(DeductType, NumExpansions, 804 /*ExpectPackInType=*/false); 805 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc); 806 } else { 807 // Just ignore the ellipsis for now and form a non-pack variable. We'll 808 // diagnose this later when we try to capture it. 809 } 810 } 811 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); 812 813 // Deduce the type of the init capture. 814 QualType DeducedType = deduceVarTypeFromInitializer( 815 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI, 816 SourceRange(Loc, Loc), IsDirectInit, Init); 817 if (DeducedType.isNull()) 818 return QualType(); 819 820 // Are we a non-list direct initialization? 821 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 822 823 // Perform initialization analysis and ensure any implicit conversions 824 // (such as lvalue-to-rvalue) are enforced. 825 InitializedEntity Entity = 826 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); 827 InitializationKind Kind = 828 IsDirectInit 829 ? (CXXDirectInit ? InitializationKind::CreateDirect( 830 Loc, Init->getBeginLoc(), Init->getEndLoc()) 831 : InitializationKind::CreateDirectList(Loc)) 832 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc()); 833 834 MultiExprArg Args = Init; 835 if (CXXDirectInit) 836 Args = 837 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); 838 QualType DclT; 839 InitializationSequence InitSeq(*this, Entity, Kind, Args); 840 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 841 842 if (Result.isInvalid()) 843 return QualType(); 844 845 Init = Result.getAs<Expr>(); 846 return DeducedType; 847 } 848 849 VarDecl *Sema::createLambdaInitCaptureVarDecl( 850 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, 851 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) { 852 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization 853 // rather than reconstructing it here. 854 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc); 855 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) 856 PETL.setEllipsisLoc(EllipsisLoc); 857 858 // Create a dummy variable representing the init-capture. This is not actually 859 // used as a variable, and only exists as a way to name and refer to the 860 // init-capture. 861 // FIXME: Pass in separate source locations for '&' and identifier. 862 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id, 863 InitCaptureType, TSI, SC_Auto); 864 NewVD->setInitCapture(true); 865 NewVD->setReferenced(true); 866 // FIXME: Pass in a VarDecl::InitializationStyle. 867 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle)); 868 NewVD->markUsed(Context); 869 NewVD->setInit(Init); 870 if (NewVD->isParameterPack()) 871 getCurLambda()->LocalPacks.push_back(NewVD); 872 return NewVD; 873 } 874 875 void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) { 876 assert(Var->isInitCapture() && "init capture flag should be set"); 877 LSI->addCapture(Var, /*isBlock=*/false, ByRef, 878 /*isNested=*/false, Var->getLocation(), SourceLocation(), 879 Var->getType(), /*Invalid=*/false); 880 } 881 882 // Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't 883 // check that the current lambda is in a consistent or fully constructed state. 884 static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) { 885 assert(!S.FunctionScopes.empty()); 886 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]); 887 } 888 889 static TypeSourceInfo * 890 getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) { 891 // C++11 [expr.prim.lambda]p4: 892 // If a lambda-expression does not include a lambda-declarator, it is as 893 // if the lambda-declarator were (). 894 FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention( 895 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 896 EPI.HasTrailingReturn = true; 897 EPI.TypeQuals.addConst(); 898 LangAS AS = S.getDefaultCXXMethodAddrSpace(); 899 if (AS != LangAS::Default) 900 EPI.TypeQuals.addAddressSpace(AS); 901 902 // C++1y [expr.prim.lambda]: 903 // The lambda return type is 'auto', which is replaced by the 904 // trailing-return type if provided and/or deduced from 'return' 905 // statements 906 // We don't do this before C++1y, because we don't support deduced return 907 // types there. 908 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14 909 ? S.Context.getAutoDeductType() 910 : S.Context.DependentTy; 911 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, 912 std::nullopt, EPI); 913 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc); 914 } 915 916 static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro, 917 Declarator &ParamInfo, Scope *CurScope, 918 SourceLocation Loc, 919 bool &ExplicitResultType) { 920 921 ExplicitResultType = false; 922 923 assert( 924 (ParamInfo.getDeclSpec().getStorageClassSpec() == 925 DeclSpec::SCS_unspecified || 926 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && 927 "Unexpected storage specifier"); 928 bool IsLambdaStatic = 929 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static; 930 931 TypeSourceInfo *MethodTyInfo; 932 933 if (ParamInfo.getNumTypeObjects() == 0) { 934 MethodTyInfo = getDummyLambdaType(S, Loc); 935 } else { 936 // Check explicit parameters 937 S.CheckExplicitObjectLambda(ParamInfo); 938 939 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 940 941 bool HasExplicitObjectParameter = 942 ParamInfo.isExplicitObjectMemberFunction(); 943 944 ExplicitResultType = FTI.hasTrailingReturnType(); 945 if (!FTI.hasMutableQualifier() && !IsLambdaStatic && 946 !HasExplicitObjectParameter) 947 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc); 948 949 if (ExplicitResultType && S.getLangOpts().HLSL) { 950 QualType RetTy = FTI.getTrailingReturnType().get(); 951 if (!RetTy.isNull()) { 952 // HLSL does not support specifying an address space on a lambda return 953 // type. 954 LangAS AddressSpace = RetTy.getAddressSpace(); 955 if (AddressSpace != LangAS::Default) 956 S.Diag(FTI.getTrailingReturnTypeLoc(), 957 diag::err_return_value_with_address_space); 958 } 959 } 960 961 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo); 962 assert(MethodTyInfo && "no type from lambda-declarator"); 963 964 // Check for unexpanded parameter packs in the method type. 965 if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) 966 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo, 967 S.UPPC_DeclarationType); 968 } 969 return MethodTyInfo; 970 } 971 972 CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange, 973 CXXRecordDecl *Class) { 974 975 // C++20 [expr.prim.lambda.closure]p3: 976 // The closure type for a lambda-expression has a public inline function 977 // call operator (for a non-generic lambda) or function call operator 978 // template (for a generic lambda) whose parameters and return type are 979 // described by the lambda-expression's parameter-declaration-clause 980 // and trailing-return-type respectively. 981 DeclarationName MethodName = 982 Context.DeclarationNames.getCXXOperatorName(OO_Call); 983 DeclarationNameLoc MethodNameLoc = 984 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin()); 985 CXXMethodDecl *Method = CXXMethodDecl::Create( 986 Context, Class, SourceLocation(), 987 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), 988 MethodNameLoc), 989 QualType(), /*Tinfo=*/nullptr, SC_None, 990 getCurFPFeatures().isFPConstrained(), 991 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(), 992 /*TrailingRequiresClause=*/nullptr); 993 Method->setAccess(AS_public); 994 return Method; 995 } 996 997 void Sema::AddTemplateParametersToLambdaCallOperator( 998 CXXMethodDecl *CallOperator, CXXRecordDecl *Class, 999 TemplateParameterList *TemplateParams) { 1000 assert(TemplateParams && "no template parameters"); 1001 FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create( 1002 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(), 1003 TemplateParams, CallOperator); 1004 TemplateMethod->setAccess(AS_public); 1005 CallOperator->setDescribedFunctionTemplate(TemplateMethod); 1006 } 1007 1008 void Sema::CompleteLambdaCallOperator( 1009 CXXMethodDecl *Method, SourceLocation LambdaLoc, 1010 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, 1011 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, 1012 StorageClass SC, ArrayRef<ParmVarDecl *> Params, 1013 bool HasExplicitResultType) { 1014 1015 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); 1016 1017 if (TrailingRequiresClause) 1018 Method->setTrailingRequiresClause(TrailingRequiresClause); 1019 1020 TemplateParameterList *TemplateParams = 1021 getGenericLambdaTemplateParameterList(LSI, *this); 1022 1023 DeclContext *DC = Method->getLexicalDeclContext(); 1024 Method->setLexicalDeclContext(LSI->Lambda); 1025 if (TemplateParams) { 1026 FunctionTemplateDecl *TemplateMethod = 1027 Method->getDescribedFunctionTemplate(); 1028 assert(TemplateMethod && 1029 "AddTemplateParametersToLambdaCallOperator should have been called"); 1030 1031 LSI->Lambda->addDecl(TemplateMethod); 1032 TemplateMethod->setLexicalDeclContext(DC); 1033 } else { 1034 LSI->Lambda->addDecl(Method); 1035 } 1036 LSI->Lambda->setLambdaIsGeneric(TemplateParams); 1037 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo); 1038 1039 Method->setLexicalDeclContext(DC); 1040 Method->setLocation(LambdaLoc); 1041 Method->setInnerLocStart(CallOperatorLoc); 1042 Method->setTypeSourceInfo(MethodTyInfo); 1043 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda, 1044 TemplateParams, MethodTyInfo)); 1045 Method->setConstexprKind(ConstexprKind); 1046 Method->setStorageClass(SC); 1047 if (!Params.empty()) { 1048 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false); 1049 Method->setParams(Params); 1050 for (auto P : Method->parameters()) { 1051 assert(P && "null in a parameter list"); 1052 P->setOwningFunction(Method); 1053 } 1054 } 1055 1056 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType); 1057 } 1058 1059 void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, 1060 Scope *CurrentScope) { 1061 1062 LambdaScopeInfo *LSI = getCurLambda(); 1063 assert(LSI && "LambdaScopeInfo should be on stack!"); 1064 1065 if (Intro.Default == LCD_ByCopy) 1066 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 1067 else if (Intro.Default == LCD_ByRef) 1068 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 1069 LSI->CaptureDefaultLoc = Intro.DefaultLoc; 1070 LSI->IntroducerRange = Intro.Range; 1071 LSI->AfterParameterList = false; 1072 1073 assert(LSI->NumExplicitTemplateParams == 0); 1074 1075 // Determine if we're within a context where we know that the lambda will 1076 // be dependent, because there are template parameters in scope. 1077 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind = 1078 CXXRecordDecl::LDK_Unknown; 1079 if (CurScope->getTemplateParamParent() != nullptr) { 1080 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; 1081 } else if (Scope *P = CurScope->getParent()) { 1082 // Given a lambda defined inside a requires expression, 1083 // 1084 // struct S { 1085 // S(auto var) requires requires { [&] -> decltype(var) { }; } 1086 // {} 1087 // }; 1088 // 1089 // The parameter var is not injected into the function Decl at the point of 1090 // parsing lambda. In such scenarios, perceiving it as dependent could 1091 // result in the constraint being evaluated, which matches what GCC does. 1092 while (P->getEntity() && P->getEntity()->isRequiresExprBody()) 1093 P = P->getParent(); 1094 if (P->isFunctionDeclarationScope() && 1095 llvm::any_of(P->decls(), [](Decl *D) { 1096 return isa<ParmVarDecl>(D) && 1097 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType(); 1098 })) 1099 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; 1100 } 1101 1102 CXXRecordDecl *Class = createLambdaClosureType( 1103 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default); 1104 LSI->Lambda = Class; 1105 1106 CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class); 1107 LSI->CallOperator = Method; 1108 Method->setLexicalDeclContext(CurContext); 1109 1110 PushDeclContext(CurScope, Method); 1111 1112 bool ContainsUnexpandedParameterPack = false; 1113 1114 // Distinct capture names, for diagnostics. 1115 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames; 1116 1117 // Handle explicit captures. 1118 SourceLocation PrevCaptureLoc = 1119 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc; 1120 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; 1121 PrevCaptureLoc = C->Loc, ++C) { 1122 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { 1123 if (C->Kind == LCK_StarThis) 1124 Diag(C->Loc, !getLangOpts().CPlusPlus17 1125 ? diag::ext_star_this_lambda_capture_cxx17 1126 : diag::warn_cxx14_compat_star_this_lambda_capture); 1127 1128 // C++11 [expr.prim.lambda]p8: 1129 // An identifier or this shall not appear more than once in a 1130 // lambda-capture. 1131 if (LSI->isCXXThisCaptured()) { 1132 Diag(C->Loc, diag::err_capture_more_than_once) 1133 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) 1134 << FixItHint::CreateRemoval( 1135 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1136 continue; 1137 } 1138 1139 // C++20 [expr.prim.lambda]p8: 1140 // If a lambda-capture includes a capture-default that is =, 1141 // each simple-capture of that lambda-capture shall be of the form 1142 // "&identifier", "this", or "* this". [ Note: The form [&,this] is 1143 // redundant but accepted for compatibility with ISO C++14. --end note ] 1144 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis) 1145 Diag(C->Loc, !getLangOpts().CPlusPlus20 1146 ? diag::ext_equals_this_lambda_capture_cxx20 1147 : diag::warn_cxx17_compat_equals_this_lambda_capture); 1148 1149 // C++11 [expr.prim.lambda]p12: 1150 // If this is captured by a local lambda expression, its nearest 1151 // enclosing function shall be a non-static member function. 1152 QualType ThisCaptureType = getCurrentThisType(); 1153 if (ThisCaptureType.isNull()) { 1154 Diag(C->Loc, diag::err_this_capture) << true; 1155 continue; 1156 } 1157 1158 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, 1159 /*FunctionScopeIndexToStopAtPtr*/ nullptr, 1160 C->Kind == LCK_StarThis); 1161 if (!LSI->Captures.empty()) 1162 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; 1163 continue; 1164 } 1165 1166 assert(C->Id && "missing identifier for capture"); 1167 1168 if (C->Init.isInvalid()) 1169 continue; 1170 1171 ValueDecl *Var = nullptr; 1172 if (C->Init.isUsable()) { 1173 Diag(C->Loc, getLangOpts().CPlusPlus14 1174 ? diag::warn_cxx11_compat_init_capture 1175 : diag::ext_init_capture); 1176 1177 // If the initializer expression is usable, but the InitCaptureType 1178 // is not, then an error has occurred - so ignore the capture for now. 1179 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. 1180 // FIXME: we should create the init capture variable and mark it invalid 1181 // in this case. 1182 if (C->InitCaptureType.get().isNull()) 1183 continue; 1184 1185 if (C->Init.get()->containsUnexpandedParameterPack() && 1186 !C->InitCaptureType.get()->getAs<PackExpansionType>()) 1187 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer); 1188 1189 unsigned InitStyle; 1190 switch (C->InitKind) { 1191 case LambdaCaptureInitKind::NoInit: 1192 llvm_unreachable("not an init-capture?"); 1193 case LambdaCaptureInitKind::CopyInit: 1194 InitStyle = VarDecl::CInit; 1195 break; 1196 case LambdaCaptureInitKind::DirectInit: 1197 InitStyle = VarDecl::CallInit; 1198 break; 1199 case LambdaCaptureInitKind::ListInit: 1200 InitStyle = VarDecl::ListInit; 1201 break; 1202 } 1203 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), 1204 C->EllipsisLoc, C->Id, InitStyle, 1205 C->Init.get(), Method); 1206 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?"); 1207 if (auto *V = dyn_cast<VarDecl>(Var)) 1208 CheckShadow(CurrentScope, V); 1209 PushOnScopeChains(Var, CurrentScope, false); 1210 } else { 1211 assert(C->InitKind == LambdaCaptureInitKind::NoInit && 1212 "init capture has valid but null init?"); 1213 1214 // C++11 [expr.prim.lambda]p8: 1215 // If a lambda-capture includes a capture-default that is &, the 1216 // identifiers in the lambda-capture shall not be preceded by &. 1217 // If a lambda-capture includes a capture-default that is =, [...] 1218 // each identifier it contains shall be preceded by &. 1219 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 1220 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 1221 << FixItHint::CreateRemoval( 1222 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1223 continue; 1224 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 1225 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 1226 << FixItHint::CreateRemoval( 1227 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1228 continue; 1229 } 1230 1231 // C++11 [expr.prim.lambda]p10: 1232 // The identifiers in a capture-list are looked up using the usual 1233 // rules for unqualified name lookup (3.4.1) 1234 DeclarationNameInfo Name(C->Id, C->Loc); 1235 LookupResult R(*this, Name, LookupOrdinaryName); 1236 LookupName(R, CurScope); 1237 if (R.isAmbiguous()) 1238 continue; 1239 if (R.empty()) { 1240 // FIXME: Disable corrections that would add qualification? 1241 CXXScopeSpec ScopeSpec; 1242 DeclFilterCCC<VarDecl> Validator{}; 1243 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 1244 continue; 1245 } 1246 1247 if (auto *BD = R.getAsSingle<BindingDecl>()) 1248 Var = BD; 1249 else if (R.getAsSingle<FieldDecl>()) { 1250 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable) 1251 << C->Id; 1252 continue; 1253 } else 1254 Var = R.getAsSingle<VarDecl>(); 1255 if (Var && DiagnoseUseOfDecl(Var, C->Loc)) 1256 continue; 1257 } 1258 1259 // C++11 [expr.prim.lambda]p10: 1260 // [...] each such lookup shall find a variable with automatic storage 1261 // duration declared in the reaching scope of the local lambda expression. 1262 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 1263 if (!Var) { 1264 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 1265 continue; 1266 } 1267 1268 // C++11 [expr.prim.lambda]p8: 1269 // An identifier or this shall not appear more than once in a 1270 // lambda-capture. 1271 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var}); 1272 !Inserted) { 1273 if (C->InitKind == LambdaCaptureInitKind::NoInit && 1274 !Var->isInitCapture()) { 1275 Diag(C->Loc, diag::err_capture_more_than_once) 1276 << C->Id << It->second->getBeginLoc() 1277 << FixItHint::CreateRemoval( 1278 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 1279 Var->setInvalidDecl(); 1280 } else if (Var && Var->isPlaceholderVar(getLangOpts())) { 1281 DiagPlaceholderVariableDefinition(C->Loc); 1282 } else { 1283 // Previous capture captured something different (one or both was 1284 // an init-capture): no fixit. 1285 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 1286 continue; 1287 } 1288 } 1289 1290 // Ignore invalid decls; they'll just confuse the code later. 1291 if (Var->isInvalidDecl()) 1292 continue; 1293 1294 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); 1295 1296 if (!Underlying->hasLocalStorage()) { 1297 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 1298 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 1299 continue; 1300 } 1301 1302 // C++11 [expr.prim.lambda]p23: 1303 // A capture followed by an ellipsis is a pack expansion (14.5.3). 1304 SourceLocation EllipsisLoc; 1305 if (C->EllipsisLoc.isValid()) { 1306 if (Var->isParameterPack()) { 1307 EllipsisLoc = C->EllipsisLoc; 1308 } else { 1309 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1310 << (C->Init.isUsable() ? C->Init.get()->getSourceRange() 1311 : SourceRange(C->Loc)); 1312 1313 // Just ignore the ellipsis. 1314 } 1315 } else if (Var->isParameterPack()) { 1316 ContainsUnexpandedParameterPack = true; 1317 } 1318 1319 if (C->Init.isUsable()) { 1320 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef); 1321 } else { 1322 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef 1323 : TryCapture_ExplicitByVal; 1324 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 1325 } 1326 if (!LSI->Captures.empty()) 1327 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; 1328 } 1329 finishLambdaExplicitCaptures(LSI); 1330 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack; 1331 PopDeclContext(); 1332 } 1333 1334 void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, 1335 SourceLocation MutableLoc) { 1336 1337 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); 1338 LSI->Mutable = MutableLoc.isValid(); 1339 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false); 1340 1341 // C++11 [expr.prim.lambda]p9: 1342 // A lambda-expression whose smallest enclosing scope is a block scope is a 1343 // local lambda expression; any other lambda expression shall not have a 1344 // capture-default or simple-capture in its lambda-introducer. 1345 // 1346 // For simple-captures, this is covered by the check below that any named 1347 // entity is a variable that can be captured. 1348 // 1349 // For DR1632, we also allow a capture-default in any context where we can 1350 // odr-use 'this' (in particular, in a default initializer for a non-static 1351 // data member). 1352 if (Intro.Default != LCD_None && 1353 !LSI->Lambda->getParent()->isFunctionOrMethod() && 1354 (getCurrentThisType().isNull() || 1355 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true, 1356 /*BuildAndDiagnose=*/false))) 1357 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); 1358 } 1359 1360 void Sema::ActOnLambdaClosureParameters( 1361 Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) { 1362 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); 1363 PushDeclContext(LambdaScope, LSI->CallOperator); 1364 1365 for (const DeclaratorChunk::ParamInfo &P : Params) { 1366 auto *Param = cast<ParmVarDecl>(P.Param); 1367 Param->setOwningFunction(LSI->CallOperator); 1368 if (Param->getIdentifier()) 1369 PushOnScopeChains(Param, LambdaScope, false); 1370 } 1371 1372 // After the parameter list, we may parse a noexcept/requires/trailing return 1373 // type which need to know whether the call operator constiture a dependent 1374 // context, so we need to setup the FunctionTemplateDecl of generic lambdas 1375 // now. 1376 TemplateParameterList *TemplateParams = 1377 getGenericLambdaTemplateParameterList(LSI, *this); 1378 if (TemplateParams) { 1379 AddTemplateParametersToLambdaCallOperator(LSI->CallOperator, LSI->Lambda, 1380 TemplateParams); 1381 LSI->Lambda->setLambdaIsGeneric(true); 1382 LSI->ContainsUnexpandedParameterPack |= 1383 TemplateParams->containsUnexpandedParameterPack(); 1384 } 1385 LSI->AfterParameterList = true; 1386 } 1387 1388 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 1389 Declarator &ParamInfo, 1390 const DeclSpec &DS) { 1391 1392 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); 1393 LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier()); 1394 1395 SmallVector<ParmVarDecl *, 8> Params; 1396 bool ExplicitResultType; 1397 1398 SourceLocation TypeLoc, CallOperatorLoc; 1399 if (ParamInfo.getNumTypeObjects() == 0) { 1400 CallOperatorLoc = TypeLoc = Intro.Range.getEnd(); 1401 } else { 1402 unsigned Index; 1403 ParamInfo.isFunctionDeclarator(Index); 1404 const auto &Object = ParamInfo.getTypeObject(Index); 1405 TypeLoc = 1406 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd(); 1407 CallOperatorLoc = ParamInfo.getSourceRange().getEnd(); 1408 } 1409 1410 CXXRecordDecl *Class = LSI->Lambda; 1411 CXXMethodDecl *Method = LSI->CallOperator; 1412 1413 TypeSourceInfo *MethodTyInfo = getLambdaType( 1414 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType); 1415 1416 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0; 1417 1418 if (ParamInfo.isFunctionDeclarator() != 0 && 1419 !FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())) { 1420 const auto &FTI = ParamInfo.getFunctionTypeInfo(); 1421 Params.reserve(Params.size()); 1422 for (unsigned I = 0; I < FTI.NumParams; ++I) { 1423 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param); 1424 Param->setScopeInfo(0, Params.size()); 1425 Params.push_back(Param); 1426 } 1427 } 1428 1429 bool IsLambdaStatic = 1430 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static; 1431 1432 CompleteLambdaCallOperator( 1433 Method, Intro.Range.getBegin(), CallOperatorLoc, 1434 ParamInfo.getTrailingRequiresClause(), MethodTyInfo, 1435 ParamInfo.getDeclSpec().getConstexprSpecifier(), 1436 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType); 1437 1438 CheckCXXDefaultArguments(Method); 1439 1440 // This represents the function body for the lambda function, check if we 1441 // have to apply optnone due to a pragma. 1442 AddRangeBasedOptnone(Method); 1443 1444 // code_seg attribute on lambda apply to the method. 1445 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction( 1446 Method, /*IsDefinition=*/true)) 1447 Method->addAttr(A); 1448 1449 // Attributes on the lambda apply to the method. 1450 ProcessDeclAttributes(CurScope, Method, ParamInfo); 1451 1452 // CUDA lambdas get implicit host and device attributes. 1453 if (getLangOpts().CUDA) 1454 CUDA().SetLambdaAttrs(Method); 1455 1456 // OpenMP lambdas might get assumumption attributes. 1457 if (LangOpts.OpenMP) 1458 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method); 1459 1460 handleLambdaNumbering(Class, Method); 1461 1462 for (auto &&C : LSI->Captures) { 1463 if (!C.isVariableCapture()) 1464 continue; 1465 ValueDecl *Var = C.getVariable(); 1466 if (Var && Var->isInitCapture()) { 1467 PushOnScopeChains(Var, CurScope, false); 1468 } 1469 } 1470 1471 auto CheckRedefinition = [&](ParmVarDecl *Param) { 1472 for (const auto &Capture : Intro.Captures) { 1473 if (Capture.Id == Param->getIdentifier()) { 1474 Diag(Param->getLocation(), diag::err_parameter_shadow_capture); 1475 Diag(Capture.Loc, diag::note_var_explicitly_captured_here) 1476 << Capture.Id << true; 1477 return false; 1478 } 1479 } 1480 return true; 1481 }; 1482 1483 for (ParmVarDecl *P : Params) { 1484 if (!P->getIdentifier()) 1485 continue; 1486 if (CheckRedefinition(P)) 1487 CheckShadow(CurScope, P); 1488 PushOnScopeChains(P, CurScope); 1489 } 1490 1491 // C++23 [expr.prim.lambda.capture]p5: 1492 // If an identifier in a capture appears as the declarator-id of a parameter 1493 // of the lambda-declarator's parameter-declaration-clause or as the name of a 1494 // template parameter of the lambda-expression's template-parameter-list, the 1495 // program is ill-formed. 1496 TemplateParameterList *TemplateParams = 1497 getGenericLambdaTemplateParameterList(LSI, *this); 1498 if (TemplateParams) { 1499 for (const auto *TP : TemplateParams->asArray()) { 1500 if (!TP->getIdentifier()) 1501 continue; 1502 for (const auto &Capture : Intro.Captures) { 1503 if (Capture.Id == TP->getIdentifier()) { 1504 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id; 1505 NoteTemplateParameterLocation(*TP); 1506 } 1507 } 1508 } 1509 } 1510 1511 // C++20: dcl.decl.general p4: 1512 // The optional requires-clause ([temp.pre]) in an init-declarator or 1513 // member-declarator shall be present only if the declarator declares a 1514 // templated function ([dcl.fct]). 1515 if (Expr *TRC = Method->getTrailingRequiresClause()) { 1516 // [temp.pre]/8: 1517 // An entity is templated if it is 1518 // - a template, 1519 // - an entity defined ([basic.def]) or created ([class.temporary]) in a 1520 // templated entity, 1521 // - a member of a templated entity, 1522 // - an enumerator for an enumeration that is a templated entity, or 1523 // - the closure type of a lambda-expression ([expr.prim.lambda.closure]) 1524 // appearing in the declaration of a templated entity. [Note 6: A local 1525 // class, a local or block variable, or a friend function defined in a 1526 // templated entity is a templated entity. — end note] 1527 // 1528 // A templated function is a function template or a function that is 1529 // templated. A templated class is a class template or a class that is 1530 // templated. A templated variable is a variable template or a variable 1531 // that is templated. 1532 1533 // Note: we only have to check if this is defined in a template entity, OR 1534 // if we are a template, since the rest don't apply. The requires clause 1535 // applies to the call operator, which we already know is a member function, 1536 // AND defined. 1537 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) { 1538 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 1539 } 1540 } 1541 1542 // Enter a new evaluation context to insulate the lambda from any 1543 // cleanups from the enclosing full-expression. 1544 PushExpressionEvaluationContext( 1545 LSI->CallOperator->isConsteval() 1546 ? ExpressionEvaluationContext::ImmediateFunctionContext 1547 : ExpressionEvaluationContext::PotentiallyEvaluated); 1548 ExprEvalContexts.back().InImmediateFunctionContext = 1549 LSI->CallOperator->isConsteval(); 1550 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 1551 getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating(); 1552 } 1553 1554 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 1555 bool IsInstantiation) { 1556 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back()); 1557 1558 // Leave the expression-evaluation context. 1559 DiscardCleanupsInEvaluationContext(); 1560 PopExpressionEvaluationContext(); 1561 1562 // Leave the context of the lambda. 1563 if (!IsInstantiation) 1564 PopDeclContext(); 1565 1566 // Finalize the lambda. 1567 CXXRecordDecl *Class = LSI->Lambda; 1568 Class->setInvalidDecl(); 1569 SmallVector<Decl*, 4> Fields(Class->fields()); 1570 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 1571 SourceLocation(), ParsedAttributesView()); 1572 CheckCompletedCXXClass(nullptr, Class); 1573 1574 PopFunctionScopeInfo(); 1575 } 1576 1577 template <typename Func> 1578 static void repeatForLambdaConversionFunctionCallingConvs( 1579 Sema &S, const FunctionProtoType &CallOpProto, Func F) { 1580 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 1581 CallOpProto.isVariadic(), /*IsCXXMethod=*/false); 1582 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 1583 CallOpProto.isVariadic(), /*IsCXXMethod=*/true); 1584 CallingConv CallOpCC = CallOpProto.getCallConv(); 1585 1586 /// Implement emitting a version of the operator for many of the calling 1587 /// conventions for MSVC, as described here: 1588 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623. 1589 /// Experimentally, we determined that cdecl, stdcall, fastcall, and 1590 /// vectorcall are generated by MSVC when it is supported by the target. 1591 /// Additionally, we are ensuring that the default-free/default-member and 1592 /// call-operator calling convention are generated as well. 1593 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the 1594 /// 'member default', despite MSVC not doing so. We do this in order to ensure 1595 /// that someone who intentionally places 'thiscall' on the lambda call 1596 /// operator will still get that overload, since we don't have the a way of 1597 /// detecting the attribute by the time we get here. 1598 if (S.getLangOpts().MSVCCompat) { 1599 CallingConv Convs[] = { 1600 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall, 1601 DefaultFree, DefaultMember, CallOpCC}; 1602 llvm::sort(Convs); 1603 llvm::iterator_range<CallingConv *> Range( 1604 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs))); 1605 const TargetInfo &TI = S.getASTContext().getTargetInfo(); 1606 1607 for (CallingConv C : Range) { 1608 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK) 1609 F(C); 1610 } 1611 return; 1612 } 1613 1614 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) { 1615 F(DefaultFree); 1616 F(DefaultMember); 1617 } else { 1618 F(CallOpCC); 1619 } 1620 } 1621 1622 // Returns the 'standard' calling convention to be used for the lambda 1623 // conversion function, that is, the 'free' function calling convention unless 1624 // it is overridden by a non-default calling convention attribute. 1625 static CallingConv 1626 getLambdaConversionFunctionCallConv(Sema &S, 1627 const FunctionProtoType *CallOpProto) { 1628 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 1629 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 1630 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 1631 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 1632 CallingConv CallOpCC = CallOpProto->getCallConv(); 1633 1634 // If the call-operator hasn't been changed, return both the 'free' and 1635 // 'member' function calling convention. 1636 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) 1637 return DefaultFree; 1638 return CallOpCC; 1639 } 1640 1641 QualType Sema::getLambdaConversionFunctionResultType( 1642 const FunctionProtoType *CallOpProto, CallingConv CC) { 1643 const FunctionProtoType::ExtProtoInfo CallOpExtInfo = 1644 CallOpProto->getExtProtoInfo(); 1645 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; 1646 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); 1647 InvokerExtInfo.TypeQuals = Qualifiers(); 1648 assert(InvokerExtInfo.RefQualifier == RQ_None && 1649 "Lambda's call operator should not have a reference qualifier"); 1650 return Context.getFunctionType(CallOpProto->getReturnType(), 1651 CallOpProto->getParamTypes(), InvokerExtInfo); 1652 } 1653 1654 /// Add a lambda's conversion to function pointer, as described in 1655 /// C++11 [expr.prim.lambda]p6. 1656 static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, 1657 CXXRecordDecl *Class, 1658 CXXMethodDecl *CallOperator, 1659 QualType InvokerFunctionTy) { 1660 // This conversion is explicitly disabled if the lambda's function has 1661 // pass_object_size attributes on any of its parameters. 1662 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) { 1663 return P->hasAttr<PassObjectSizeAttr>(); 1664 }; 1665 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr)) 1666 return; 1667 1668 // Add the conversion to function pointer. 1669 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); 1670 1671 // Create the type of the conversion function. 1672 FunctionProtoType::ExtProtoInfo ConvExtInfo( 1673 S.Context.getDefaultCallingConvention( 1674 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1675 // The conversion function is always const and noexcept. 1676 ConvExtInfo.TypeQuals = Qualifiers(); 1677 ConvExtInfo.TypeQuals.addConst(); 1678 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept; 1679 QualType ConvTy = 1680 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo); 1681 1682 SourceLocation Loc = IntroducerRange.getBegin(); 1683 DeclarationName ConversionName 1684 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1685 S.Context.getCanonicalType(PtrToFunctionTy)); 1686 // Construct a TypeSourceInfo for the conversion function, and wire 1687 // all the parameters appropriately for the FunctionProtoTypeLoc 1688 // so that everything works during transformation/instantiation of 1689 // generic lambdas. 1690 // The main reason for wiring up the parameters of the conversion 1691 // function with that of the call operator is so that constructs 1692 // like the following work: 1693 // auto L = [](auto b) { <-- 1 1694 // return [](auto a) -> decltype(a) { <-- 2 1695 // return a; 1696 // }; 1697 // }; 1698 // int (*fp)(int) = L(5); 1699 // Because the trailing return type can contain DeclRefExprs that refer 1700 // to the original call operator's variables, we hijack the call 1701 // operators ParmVarDecls below. 1702 TypeSourceInfo *ConvNamePtrToFunctionTSI = 1703 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); 1704 DeclarationNameLoc ConvNameLoc = 1705 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI); 1706 1707 // The conversion function is a conversion to a pointer-to-function. 1708 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); 1709 FunctionProtoTypeLoc ConvTL = 1710 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); 1711 // Get the result of the conversion function which is a pointer-to-function. 1712 PointerTypeLoc PtrToFunctionTL = 1713 ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); 1714 // Do the same for the TypeSourceInfo that is used to name the conversion 1715 // operator. 1716 PointerTypeLoc ConvNamePtrToFunctionTL = 1717 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); 1718 1719 // Get the underlying function types that the conversion function will 1720 // be converting to (should match the type of the call operator). 1721 FunctionProtoTypeLoc CallOpConvTL = 1722 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1723 FunctionProtoTypeLoc CallOpConvNameTL = 1724 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 1725 1726 // Wire up the FunctionProtoTypeLocs with the call operator's parameters. 1727 // These parameter's are essentially used to transform the name and 1728 // the type of the conversion operator. By using the same parameters 1729 // as the call operator's we don't have to fix any back references that 1730 // the trailing return type of the call operator's uses (such as 1731 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) 1732 // - we can simply use the return type of the call operator, and 1733 // everything should work. 1734 SmallVector<ParmVarDecl *, 4> InvokerParams; 1735 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 1736 ParmVarDecl *From = CallOperator->getParamDecl(I); 1737 1738 InvokerParams.push_back(ParmVarDecl::Create( 1739 S.Context, 1740 // Temporarily add to the TU. This is set to the invoker below. 1741 S.Context.getTranslationUnitDecl(), From->getBeginLoc(), 1742 From->getLocation(), From->getIdentifier(), From->getType(), 1743 From->getTypeSourceInfo(), From->getStorageClass(), 1744 /*DefArg=*/nullptr)); 1745 CallOpConvTL.setParam(I, From); 1746 CallOpConvNameTL.setParam(I, From); 1747 } 1748 1749 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1750 S.Context, Class, Loc, 1751 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI, 1752 S.getCurFPFeatures().isFPConstrained(), 1753 /*isInline=*/true, ExplicitSpecifier(), 1754 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr 1755 : ConstexprSpecKind::Unspecified, 1756 CallOperator->getBody()->getEndLoc()); 1757 Conversion->setAccess(AS_public); 1758 Conversion->setImplicit(true); 1759 1760 // A non-generic lambda may still be a templated entity. We need to preserve 1761 // constraints when converting the lambda to a function pointer. See GH63181. 1762 if (Expr *Requires = CallOperator->getTrailingRequiresClause()) 1763 Conversion->setTrailingRequiresClause(Requires); 1764 1765 if (Class->isGenericLambda()) { 1766 // Create a template version of the conversion operator, using the template 1767 // parameter list of the function call operator. 1768 FunctionTemplateDecl *TemplateCallOperator = 1769 CallOperator->getDescribedFunctionTemplate(); 1770 FunctionTemplateDecl *ConversionTemplate = 1771 FunctionTemplateDecl::Create(S.Context, Class, 1772 Loc, ConversionName, 1773 TemplateCallOperator->getTemplateParameters(), 1774 Conversion); 1775 ConversionTemplate->setAccess(AS_public); 1776 ConversionTemplate->setImplicit(true); 1777 Conversion->setDescribedFunctionTemplate(ConversionTemplate); 1778 Class->addDecl(ConversionTemplate); 1779 } else 1780 Class->addDecl(Conversion); 1781 1782 // If the lambda is not static, we need to add a static member 1783 // function that will be the result of the conversion with a 1784 // certain unique ID. 1785 // When it is static we just return the static call operator instead. 1786 if (CallOperator->isImplicitObjectMemberFunction()) { 1787 DeclarationName InvokerName = 1788 &S.Context.Idents.get(getLambdaStaticInvokerName()); 1789 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() 1790 // we should get a prebuilt TrivialTypeSourceInfo from Context 1791 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc 1792 // then rewire the parameters accordingly, by hoisting up the InvokeParams 1793 // loop below and then use its Params to set Invoke->setParams(...) below. 1794 // This would avoid the 'const' qualifier of the calloperator from 1795 // contaminating the type of the invoker, which is currently adjusted 1796 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the 1797 // trailing return type of the invoker would require a visitor to rebuild 1798 // the trailing return type and adjusting all back DeclRefExpr's to refer 1799 // to the new static invoker parameters - not the call operator's. 1800 CXXMethodDecl *Invoke = CXXMethodDecl::Create( 1801 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc), 1802 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static, 1803 S.getCurFPFeatures().isFPConstrained(), 1804 /*isInline=*/true, CallOperator->getConstexprKind(), 1805 CallOperator->getBody()->getEndLoc()); 1806 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) 1807 InvokerParams[I]->setOwningFunction(Invoke); 1808 Invoke->setParams(InvokerParams); 1809 Invoke->setAccess(AS_private); 1810 Invoke->setImplicit(true); 1811 if (Class->isGenericLambda()) { 1812 FunctionTemplateDecl *TemplateCallOperator = 1813 CallOperator->getDescribedFunctionTemplate(); 1814 FunctionTemplateDecl *StaticInvokerTemplate = 1815 FunctionTemplateDecl::Create( 1816 S.Context, Class, Loc, InvokerName, 1817 TemplateCallOperator->getTemplateParameters(), Invoke); 1818 StaticInvokerTemplate->setAccess(AS_private); 1819 StaticInvokerTemplate->setImplicit(true); 1820 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); 1821 Class->addDecl(StaticInvokerTemplate); 1822 } else 1823 Class->addDecl(Invoke); 1824 } 1825 } 1826 1827 /// Add a lambda's conversion to function pointers, as described in 1828 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a 1829 /// single pointer conversion. In the event that the default calling convention 1830 /// for free and member functions is different, it will emit both conventions. 1831 static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, 1832 CXXRecordDecl *Class, 1833 CXXMethodDecl *CallOperator) { 1834 const FunctionProtoType *CallOpProto = 1835 CallOperator->getType()->castAs<FunctionProtoType>(); 1836 1837 repeatForLambdaConversionFunctionCallingConvs( 1838 S, *CallOpProto, [&](CallingConv CC) { 1839 QualType InvokerFunctionTy = 1840 S.getLambdaConversionFunctionResultType(CallOpProto, CC); 1841 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator, 1842 InvokerFunctionTy); 1843 }); 1844 } 1845 1846 /// Add a lambda's conversion to block pointer. 1847 static void addBlockPointerConversion(Sema &S, 1848 SourceRange IntroducerRange, 1849 CXXRecordDecl *Class, 1850 CXXMethodDecl *CallOperator) { 1851 const FunctionProtoType *CallOpProto = 1852 CallOperator->getType()->castAs<FunctionProtoType>(); 1853 QualType FunctionTy = S.getLambdaConversionFunctionResultType( 1854 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto)); 1855 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 1856 1857 FunctionProtoType::ExtProtoInfo ConversionEPI( 1858 S.Context.getDefaultCallingConvention( 1859 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 1860 ConversionEPI.TypeQuals = Qualifiers(); 1861 ConversionEPI.TypeQuals.addConst(); 1862 QualType ConvTy = 1863 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI); 1864 1865 SourceLocation Loc = IntroducerRange.getBegin(); 1866 DeclarationName Name 1867 = S.Context.DeclarationNames.getCXXConversionFunctionName( 1868 S.Context.getCanonicalType(BlockPtrTy)); 1869 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc( 1870 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc)); 1871 CXXConversionDecl *Conversion = CXXConversionDecl::Create( 1872 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy, 1873 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 1874 S.getCurFPFeatures().isFPConstrained(), 1875 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, 1876 CallOperator->getBody()->getEndLoc()); 1877 Conversion->setAccess(AS_public); 1878 Conversion->setImplicit(true); 1879 Class->addDecl(Conversion); 1880 } 1881 1882 ExprResult Sema::BuildCaptureInit(const Capture &Cap, 1883 SourceLocation ImplicitCaptureLoc, 1884 bool IsOpenMPMapping) { 1885 // VLA captures don't have a stored initialization expression. 1886 if (Cap.isVLATypeCapture()) 1887 return ExprResult(); 1888 1889 // An init-capture is initialized directly from its stored initializer. 1890 if (Cap.isInitCapture()) 1891 return cast<VarDecl>(Cap.getVariable())->getInit(); 1892 1893 // For anything else, build an initialization expression. For an implicit 1894 // capture, the capture notionally happens at the capture-default, so use 1895 // that location here. 1896 SourceLocation Loc = 1897 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation(); 1898 1899 // C++11 [expr.prim.lambda]p21: 1900 // When the lambda-expression is evaluated, the entities that 1901 // are captured by copy are used to direct-initialize each 1902 // corresponding non-static data member of the resulting closure 1903 // object. (For array members, the array elements are 1904 // direct-initialized in increasing subscript order.) These 1905 // initializations are performed in the (unspecified) order in 1906 // which the non-static data members are declared. 1907 1908 // C++ [expr.prim.lambda]p12: 1909 // An entity captured by a lambda-expression is odr-used (3.2) in 1910 // the scope containing the lambda-expression. 1911 ExprResult Init; 1912 IdentifierInfo *Name = nullptr; 1913 if (Cap.isThisCapture()) { 1914 QualType ThisTy = getCurrentThisType(); 1915 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid()); 1916 if (Cap.isCopyCapture()) 1917 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 1918 else 1919 Init = This; 1920 } else { 1921 assert(Cap.isVariableCapture() && "unknown kind of capture"); 1922 ValueDecl *Var = Cap.getVariable(); 1923 Name = Var->getIdentifier(); 1924 Init = BuildDeclarationNameExpr( 1925 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 1926 } 1927 1928 // In OpenMP, the capture kind doesn't actually describe how to capture: 1929 // variables are "mapped" onto the device in a process that does not formally 1930 // make a copy, even for a "copy capture". 1931 if (IsOpenMPMapping) 1932 return Init; 1933 1934 if (Init.isInvalid()) 1935 return ExprError(); 1936 1937 Expr *InitExpr = Init.get(); 1938 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture( 1939 Name, Cap.getCaptureType(), Loc); 1940 InitializationKind InitKind = 1941 InitializationKind::CreateDirect(Loc, Loc, Loc); 1942 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr); 1943 return InitSeq.Perform(*this, Entity, InitKind, InitExpr); 1944 } 1945 1946 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) { 1947 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); 1948 ActOnFinishFunctionBody(LSI.CallOperator, Body); 1949 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); 1950 } 1951 1952 static LambdaCaptureDefault 1953 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) { 1954 switch (ICS) { 1955 case CapturingScopeInfo::ImpCap_None: 1956 return LCD_None; 1957 case CapturingScopeInfo::ImpCap_LambdaByval: 1958 return LCD_ByCopy; 1959 case CapturingScopeInfo::ImpCap_CapturedRegion: 1960 case CapturingScopeInfo::ImpCap_LambdaByref: 1961 return LCD_ByRef; 1962 case CapturingScopeInfo::ImpCap_Block: 1963 llvm_unreachable("block capture in lambda"); 1964 } 1965 llvm_unreachable("Unknown implicit capture style"); 1966 } 1967 1968 bool Sema::CaptureHasSideEffects(const Capture &From) { 1969 if (From.isInitCapture()) { 1970 Expr *Init = cast<VarDecl>(From.getVariable())->getInit(); 1971 if (Init && Init->HasSideEffects(Context)) 1972 return true; 1973 } 1974 1975 if (!From.isCopyCapture()) 1976 return false; 1977 1978 const QualType T = From.isThisCapture() 1979 ? getCurrentThisType()->getPointeeType() 1980 : From.getCaptureType(); 1981 1982 if (T.isVolatileQualified()) 1983 return true; 1984 1985 const Type *BaseT = T->getBaseElementTypeUnsafe(); 1986 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl()) 1987 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() || 1988 !RD->hasTrivialDestructor(); 1989 1990 return false; 1991 } 1992 1993 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 1994 const Capture &From) { 1995 if (CaptureHasSideEffects(From)) 1996 return false; 1997 1998 if (From.isVLATypeCapture()) 1999 return false; 2000 2001 // FIXME: maybe we should warn on these if we can find a sensible diagnostic 2002 // message 2003 if (From.isInitCapture() && 2004 From.getVariable()->isPlaceholderVar(getLangOpts())) 2005 return false; 2006 2007 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture); 2008 if (From.isThisCapture()) 2009 diag << "'this'"; 2010 else 2011 diag << From.getVariable(); 2012 diag << From.isNonODRUsed(); 2013 diag << FixItHint::CreateRemoval(CaptureRange); 2014 return true; 2015 } 2016 2017 /// Create a field within the lambda class or captured statement record for the 2018 /// given capture. 2019 FieldDecl *Sema::BuildCaptureField(RecordDecl *RD, 2020 const sema::Capture &Capture) { 2021 SourceLocation Loc = Capture.getLocation(); 2022 QualType FieldType = Capture.getCaptureType(); 2023 2024 TypeSourceInfo *TSI = nullptr; 2025 if (Capture.isVariableCapture()) { 2026 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable()); 2027 if (Var && Var->isInitCapture()) 2028 TSI = Var->getTypeSourceInfo(); 2029 } 2030 2031 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more 2032 // appropriate, at least for an implicit capture. 2033 if (!TSI) 2034 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc); 2035 2036 // Build the non-static data member. 2037 FieldDecl *Field = 2038 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc, 2039 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr, 2040 /*Mutable=*/false, ICIS_NoInit); 2041 // If the variable being captured has an invalid type, mark the class as 2042 // invalid as well. 2043 if (!FieldType->isDependentType()) { 2044 if (RequireCompleteSizedType(Loc, FieldType, 2045 diag::err_field_incomplete_or_sizeless)) { 2046 RD->setInvalidDecl(); 2047 Field->setInvalidDecl(); 2048 } else { 2049 NamedDecl *Def; 2050 FieldType->isIncompleteType(&Def); 2051 if (Def && Def->isInvalidDecl()) { 2052 RD->setInvalidDecl(); 2053 Field->setInvalidDecl(); 2054 } 2055 } 2056 } 2057 Field->setImplicit(true); 2058 Field->setAccess(AS_private); 2059 RD->addDecl(Field); 2060 2061 if (Capture.isVLATypeCapture()) 2062 Field->setCapturedVLAType(Capture.getCapturedVLAType()); 2063 2064 return Field; 2065 } 2066 2067 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 2068 LambdaScopeInfo *LSI) { 2069 // Collect information from the lambda scope. 2070 SmallVector<LambdaCapture, 4> Captures; 2071 SmallVector<Expr *, 4> CaptureInits; 2072 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc; 2073 LambdaCaptureDefault CaptureDefault = 2074 mapImplicitCaptureStyle(LSI->ImpCaptureStyle); 2075 CXXRecordDecl *Class; 2076 CXXMethodDecl *CallOperator; 2077 SourceRange IntroducerRange; 2078 bool ExplicitParams; 2079 bool ExplicitResultType; 2080 CleanupInfo LambdaCleanup; 2081 bool ContainsUnexpandedParameterPack; 2082 bool IsGenericLambda; 2083 { 2084 CallOperator = LSI->CallOperator; 2085 Class = LSI->Lambda; 2086 IntroducerRange = LSI->IntroducerRange; 2087 ExplicitParams = LSI->ExplicitParams; 2088 ExplicitResultType = !LSI->HasImplicitReturnType; 2089 LambdaCleanup = LSI->Cleanup; 2090 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; 2091 IsGenericLambda = Class->isGenericLambda(); 2092 2093 CallOperator->setLexicalDeclContext(Class); 2094 Decl *TemplateOrNonTemplateCallOperatorDecl = 2095 CallOperator->getDescribedFunctionTemplate() 2096 ? CallOperator->getDescribedFunctionTemplate() 2097 : cast<Decl>(CallOperator); 2098 2099 // FIXME: Is this really the best choice? Keeping the lexical decl context 2100 // set as CurContext seems more faithful to the source. 2101 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); 2102 2103 PopExpressionEvaluationContext(); 2104 2105 // True if the current capture has a used capture or default before it. 2106 bool CurHasPreviousCapture = CaptureDefault != LCD_None; 2107 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ? 2108 CaptureDefaultLoc : IntroducerRange.getBegin(); 2109 2110 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 2111 const Capture &From = LSI->Captures[I]; 2112 2113 if (From.isInvalid()) 2114 return ExprError(); 2115 2116 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 2117 bool IsImplicit = I >= LSI->NumExplicitCaptures; 2118 SourceLocation ImplicitCaptureLoc = 2119 IsImplicit ? CaptureDefaultLoc : SourceLocation(); 2120 2121 // Use source ranges of explicit captures for fixits where available. 2122 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I]; 2123 2124 // Warn about unused explicit captures. 2125 bool IsCaptureUsed = true; 2126 if (!CurContext->isDependentContext() && !IsImplicit && 2127 !From.isODRUsed()) { 2128 // Initialized captures that are non-ODR used may not be eliminated. 2129 // FIXME: Where did the IsGenericLambda here come from? 2130 bool NonODRUsedInitCapture = 2131 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture(); 2132 if (!NonODRUsedInitCapture) { 2133 bool IsLast = (I + 1) == LSI->NumExplicitCaptures; 2134 SourceRange FixItRange; 2135 if (CaptureRange.isValid()) { 2136 if (!CurHasPreviousCapture && !IsLast) { 2137 // If there are no captures preceding this capture, remove the 2138 // following comma. 2139 FixItRange = SourceRange(CaptureRange.getBegin(), 2140 getLocForEndOfToken(CaptureRange.getEnd())); 2141 } else { 2142 // Otherwise, remove the comma since the last used capture. 2143 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc), 2144 CaptureRange.getEnd()); 2145 } 2146 } 2147 2148 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From); 2149 } 2150 } 2151 2152 if (CaptureRange.isValid()) { 2153 CurHasPreviousCapture |= IsCaptureUsed; 2154 PrevCaptureLoc = CaptureRange.getEnd(); 2155 } 2156 2157 // Map the capture to our AST representation. 2158 LambdaCapture Capture = [&] { 2159 if (From.isThisCapture()) { 2160 // Capturing 'this' implicitly with a default of '[=]' is deprecated, 2161 // because it results in a reference capture. Don't warn prior to 2162 // C++2a; there's nothing that can be done about it before then. 2163 if (getLangOpts().CPlusPlus20 && IsImplicit && 2164 CaptureDefault == LCD_ByCopy) { 2165 Diag(From.getLocation(), diag::warn_deprecated_this_capture); 2166 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture) 2167 << FixItHint::CreateInsertion( 2168 getLocForEndOfToken(CaptureDefaultLoc), ", this"); 2169 } 2170 return LambdaCapture(From.getLocation(), IsImplicit, 2171 From.isCopyCapture() ? LCK_StarThis : LCK_This); 2172 } else if (From.isVLATypeCapture()) { 2173 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType); 2174 } else { 2175 assert(From.isVariableCapture() && "unknown kind of capture"); 2176 ValueDecl *Var = From.getVariable(); 2177 LambdaCaptureKind Kind = 2178 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef; 2179 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var, 2180 From.getEllipsisLoc()); 2181 } 2182 }(); 2183 2184 // Form the initializer for the capture field. 2185 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc); 2186 2187 // FIXME: Skip this capture if the capture is not used, the initializer 2188 // has no side-effects, the type of the capture is trivial, and the 2189 // lambda is not externally visible. 2190 2191 // Add a FieldDecl for the capture and form its initializer. 2192 BuildCaptureField(Class, From); 2193 Captures.push_back(Capture); 2194 CaptureInits.push_back(Init.get()); 2195 2196 if (LangOpts.CUDA) 2197 CUDA().CheckLambdaCapture(CallOperator, From); 2198 } 2199 2200 Class->setCaptures(Context, Captures); 2201 2202 // C++11 [expr.prim.lambda]p6: 2203 // The closure type for a lambda-expression with no lambda-capture 2204 // has a public non-virtual non-explicit const conversion function 2205 // to pointer to function having the same parameter and return 2206 // types as the closure type's function call operator. 2207 if (Captures.empty() && CaptureDefault == LCD_None) 2208 addFunctionPointerConversions(*this, IntroducerRange, Class, 2209 CallOperator); 2210 2211 // Objective-C++: 2212 // The closure type for a lambda-expression has a public non-virtual 2213 // non-explicit const conversion function to a block pointer having the 2214 // same parameter and return types as the closure type's function call 2215 // operator. 2216 // FIXME: Fix generic lambda to block conversions. 2217 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda) 2218 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 2219 2220 // Finalize the lambda class. 2221 SmallVector<Decl*, 4> Fields(Class->fields()); 2222 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 2223 SourceLocation(), ParsedAttributesView()); 2224 CheckCompletedCXXClass(nullptr, Class); 2225 } 2226 2227 Cleanup.mergeFrom(LambdaCleanup); 2228 2229 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 2230 CaptureDefault, CaptureDefaultLoc, 2231 ExplicitParams, ExplicitResultType, 2232 CaptureInits, EndLoc, 2233 ContainsUnexpandedParameterPack); 2234 // If the lambda expression's call operator is not explicitly marked constexpr 2235 // and we are not in a dependent context, analyze the call operator to infer 2236 // its constexpr-ness, suppressing diagnostics while doing so. 2237 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() && 2238 !CallOperator->isConstexpr() && 2239 !isa<CoroutineBodyStmt>(CallOperator->getBody()) && 2240 !Class->getDeclContext()->isDependentContext()) { 2241 CallOperator->setConstexprKind( 2242 CheckConstexprFunctionDefinition(CallOperator, 2243 CheckConstexprKind::CheckValid) 2244 ? ConstexprSpecKind::Constexpr 2245 : ConstexprSpecKind::Unspecified); 2246 } 2247 2248 // Emit delayed shadowing warnings now that the full capture list is known. 2249 DiagnoseShadowingLambdaDecls(LSI); 2250 2251 if (!CurContext->isDependentContext()) { 2252 switch (ExprEvalContexts.back().Context) { 2253 // C++11 [expr.prim.lambda]p2: 2254 // A lambda-expression shall not appear in an unevaluated operand 2255 // (Clause 5). 2256 case ExpressionEvaluationContext::Unevaluated: 2257 case ExpressionEvaluationContext::UnevaluatedList: 2258 case ExpressionEvaluationContext::UnevaluatedAbstract: 2259 // C++1y [expr.const]p2: 2260 // A conditional-expression e is a core constant expression unless the 2261 // evaluation of e, following the rules of the abstract machine, would 2262 // evaluate [...] a lambda-expression. 2263 // 2264 // This is technically incorrect, there are some constant evaluated contexts 2265 // where this should be allowed. We should probably fix this when DR1607 is 2266 // ratified, it lays out the exact set of conditions where we shouldn't 2267 // allow a lambda-expression. 2268 case ExpressionEvaluationContext::ConstantEvaluated: 2269 case ExpressionEvaluationContext::ImmediateFunctionContext: 2270 // We don't actually diagnose this case immediately, because we 2271 // could be within a context where we might find out later that 2272 // the expression is potentially evaluated (e.g., for typeid). 2273 ExprEvalContexts.back().Lambdas.push_back(Lambda); 2274 break; 2275 2276 case ExpressionEvaluationContext::DiscardedStatement: 2277 case ExpressionEvaluationContext::PotentiallyEvaluated: 2278 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 2279 break; 2280 } 2281 } 2282 2283 return MaybeBindToTemporary(Lambda); 2284 } 2285 2286 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 2287 SourceLocation ConvLocation, 2288 CXXConversionDecl *Conv, 2289 Expr *Src) { 2290 // Make sure that the lambda call operator is marked used. 2291 CXXRecordDecl *Lambda = Conv->getParent(); 2292 CXXMethodDecl *CallOperator 2293 = cast<CXXMethodDecl>( 2294 Lambda->lookup( 2295 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 2296 CallOperator->setReferenced(); 2297 CallOperator->markUsed(Context); 2298 2299 ExprResult Init = PerformCopyInitialization( 2300 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()), 2301 CurrentLocation, Src); 2302 if (!Init.isInvalid()) 2303 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 2304 2305 if (Init.isInvalid()) 2306 return ExprError(); 2307 2308 // Create the new block to be returned. 2309 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 2310 2311 // Set the type information. 2312 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 2313 Block->setIsVariadic(CallOperator->isVariadic()); 2314 Block->setBlockMissingReturnType(false); 2315 2316 // Add parameters. 2317 SmallVector<ParmVarDecl *, 4> BlockParams; 2318 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 2319 ParmVarDecl *From = CallOperator->getParamDecl(I); 2320 BlockParams.push_back(ParmVarDecl::Create( 2321 Context, Block, From->getBeginLoc(), From->getLocation(), 2322 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(), 2323 From->getStorageClass(), 2324 /*DefArg=*/nullptr)); 2325 } 2326 Block->setParams(BlockParams); 2327 2328 Block->setIsConversionFromLambda(true); 2329 2330 // Add capture. The capture uses a fake variable, which doesn't correspond 2331 // to any actual memory location. However, the initializer copy-initializes 2332 // the lambda object. 2333 TypeSourceInfo *CapVarTSI = 2334 Context.getTrivialTypeSourceInfo(Src->getType()); 2335 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 2336 ConvLocation, nullptr, 2337 Src->getType(), CapVarTSI, 2338 SC_None); 2339 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false, 2340 /*nested=*/false, /*copy=*/Init.get()); 2341 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); 2342 2343 // Add a fake function body to the block. IR generation is responsible 2344 // for filling in the actual body, which cannot be expressed as an AST. 2345 Block->setBody(new (Context) CompoundStmt(ConvLocation)); 2346 2347 // Create the block literal expression. 2348 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 2349 ExprCleanupObjects.push_back(Block); 2350 Cleanup.setExprNeedsCleanups(true); 2351 2352 return BuildBlock; 2353 } 2354 2355 static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) { 2356 if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) { 2357 while (FD->getInstantiatedFromMemberFunction()) 2358 FD = FD->getInstantiatedFromMemberFunction(); 2359 return FD; 2360 } 2361 2362 if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) 2363 return FD->getInstantiatedFromDecl(); 2364 2365 FunctionTemplateDecl *FTD = FD->getPrimaryTemplate(); 2366 if (!FTD) 2367 return nullptr; 2368 2369 while (FTD->getInstantiatedFromMemberTemplate()) 2370 FTD = FTD->getInstantiatedFromMemberTemplate(); 2371 2372 return FTD->getTemplatedDecl(); 2373 } 2374 2375 Sema::LambdaScopeForCallOperatorInstantiationRAII:: 2376 LambdaScopeForCallOperatorInstantiationRAII( 2377 Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, 2378 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope) 2379 : FunctionScopeRAII(SemaRef) { 2380 if (!isLambdaCallOperator(FD)) { 2381 FunctionScopeRAII::disable(); 2382 return; 2383 } 2384 2385 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD)); 2386 2387 FunctionDecl *FDPattern = getPatternFunctionDecl(FD); 2388 if (!FDPattern) 2389 return; 2390 2391 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL); 2392 2393 if (!ShouldAddDeclsFromParentScope) 2394 return; 2395 2396 llvm::SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 4> 2397 ParentInstantiations; 2398 while (true) { 2399 FDPattern = 2400 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern)); 2401 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD)); 2402 2403 if (!FDPattern || !FD) 2404 break; 2405 2406 ParentInstantiations.emplace_back(FDPattern, FD); 2407 } 2408 2409 // Add instantiated parameters and local vars to scopes, starting from the 2410 // outermost lambda to the innermost lambda. This ordering ensures that 2411 // parameters in inner lambdas can correctly depend on those defined 2412 // in outer lambdas, e.g. auto L = [](auto... x) { 2413 // return [](decltype(x)... y) { }; // `y` depends on `x` 2414 // }; 2415 2416 for (const auto &[FDPattern, FD] : llvm::reverse(ParentInstantiations)) { 2417 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL); 2418 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope); 2419 } 2420 } 2421