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