clang API Documentation
00001 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for C++ lambda expressions. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 #include "clang/Sema/DeclSpec.h" 00014 #include "TypeLocBuilder.h" 00015 #include "clang/AST/ASTLambda.h" 00016 #include "clang/AST/ExprCXX.h" 00017 #include "clang/Basic/TargetInfo.h" 00018 #include "clang/Sema/Initialization.h" 00019 #include "clang/Sema/Lookup.h" 00020 #include "clang/Sema/Scope.h" 00021 #include "clang/Sema/ScopeInfo.h" 00022 #include "clang/Sema/SemaInternal.h" 00023 #include "clang/Sema/SemaLambda.h" 00024 using namespace clang; 00025 using namespace sema; 00026 00027 /// \brief Examines the FunctionScopeInfo stack to determine the nearest 00028 /// enclosing lambda (to the current lambda) that is 'capture-ready' for 00029 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 00030 /// If successful, returns the index into Sema's FunctionScopeInfo stack 00031 /// of the capture-ready lambda's LambdaScopeInfo. 00032 /// 00033 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current 00034 /// lambda - is on top) to determine the index of the nearest enclosing/outer 00035 /// lambda that is ready to capture the \p VarToCapture being referenced in 00036 /// the current lambda. 00037 /// As we climb down the stack, we want the index of the first such lambda - 00038 /// that is the lambda with the highest index that is 'capture-ready'. 00039 /// 00040 /// A lambda 'L' is capture-ready for 'V' (var or this) if: 00041 /// - its enclosing context is non-dependent 00042 /// - and if the chain of lambdas between L and the lambda in which 00043 /// V is potentially used (i.e. the lambda at the top of the scope info 00044 /// stack), can all capture or have already captured V. 00045 /// If \p VarToCapture is 'null' then we are trying to capture 'this'. 00046 /// 00047 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked 00048 /// for whether it is 'capture-capable' (see 00049 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly 00050 /// capture. 00051 /// 00052 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 00053 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 00054 /// is at the top of the stack and has the highest index. 00055 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 00056 /// 00057 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains 00058 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda 00059 /// which is capture-ready. If the return value evaluates to 'false' then 00060 /// no lambda is capture-ready for \p VarToCapture. 00061 00062 static inline Optional<unsigned> 00063 getStackIndexOfNearestEnclosingCaptureReadyLambda( 00064 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, 00065 VarDecl *VarToCapture) { 00066 // Label failure to capture. 00067 const Optional<unsigned> NoLambdaIsCaptureReady; 00068 00069 assert( 00070 isa<clang::sema::LambdaScopeInfo>( 00071 FunctionScopes[FunctionScopes.size() - 1]) && 00072 "The function on the top of sema's function-info stack must be a lambda"); 00073 00074 // If VarToCapture is null, we are attempting to capture 'this'. 00075 const bool IsCapturingThis = !VarToCapture; 00076 const bool IsCapturingVariable = !IsCapturingThis; 00077 00078 // Start with the current lambda at the top of the stack (highest index). 00079 unsigned CurScopeIndex = FunctionScopes.size() - 1; 00080 DeclContext *EnclosingDC = 00081 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator; 00082 00083 do { 00084 const clang::sema::LambdaScopeInfo *LSI = 00085 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]); 00086 // IF we have climbed down to an intervening enclosing lambda that contains 00087 // the variable declaration - it obviously can/must not capture the 00088 // variable. 00089 // Since its enclosing DC is dependent, all the lambdas between it and the 00090 // innermost nested lambda are dependent (otherwise we wouldn't have 00091 // arrived here) - so we don't yet have a lambda that can capture the 00092 // variable. 00093 if (IsCapturingVariable && 00094 VarToCapture->getDeclContext()->Equals(EnclosingDC)) 00095 return NoLambdaIsCaptureReady; 00096 00097 // For an enclosing lambda to be capture ready for an entity, all 00098 // intervening lambda's have to be able to capture that entity. If even 00099 // one of the intervening lambda's is not capable of capturing the entity 00100 // then no enclosing lambda can ever capture that entity. 00101 // For e.g. 00102 // const int x = 10; 00103 // [=](auto a) { #1 00104 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x' 00105 // [=](auto c) { #3 00106 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2 00107 // }; }; }; 00108 // If they do not have a default implicit capture, check to see 00109 // if the entity has already been explicitly captured. 00110 // If even a single dependent enclosing lambda lacks the capability 00111 // to ever capture this variable, there is no further enclosing 00112 // non-dependent lambda that can capture this variable. 00113 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) { 00114 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture)) 00115 return NoLambdaIsCaptureReady; 00116 if (IsCapturingThis && !LSI->isCXXThisCaptured()) 00117 return NoLambdaIsCaptureReady; 00118 } 00119 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); 00120 00121 assert(CurScopeIndex); 00122 --CurScopeIndex; 00123 } while (!EnclosingDC->isTranslationUnit() && 00124 EnclosingDC->isDependentContext() && 00125 isLambdaCallOperator(EnclosingDC)); 00126 00127 assert(CurScopeIndex < (FunctionScopes.size() - 1)); 00128 // If the enclosingDC is not dependent, then the immediately nested lambda 00129 // (one index above) is capture-ready. 00130 if (!EnclosingDC->isDependentContext()) 00131 return CurScopeIndex + 1; 00132 return NoLambdaIsCaptureReady; 00133 } 00134 00135 /// \brief Examines the FunctionScopeInfo stack to determine the nearest 00136 /// enclosing lambda (to the current lambda) that is 'capture-capable' for 00137 /// the variable referenced in the current lambda (i.e. \p VarToCapture). 00138 /// If successful, returns the index into Sema's FunctionScopeInfo stack 00139 /// of the capture-capable lambda's LambdaScopeInfo. 00140 /// 00141 /// Given the current stack of lambdas being processed by Sema and 00142 /// the variable of interest, to identify the nearest enclosing lambda (to the 00143 /// current lambda at the top of the stack) that can truly capture 00144 /// a variable, it has to have the following two properties: 00145 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': 00146 /// - climb down the stack (i.e. starting from the innermost and examining 00147 /// each outer lambda step by step) checking if each enclosing 00148 /// lambda can either implicitly or explicitly capture the variable. 00149 /// Record the first such lambda that is enclosed in a non-dependent 00150 /// context. If no such lambda currently exists return failure. 00151 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly 00152 /// capture the variable by checking all its enclosing lambdas: 00153 /// - check if all outer lambdas enclosing the 'capture-ready' lambda 00154 /// identified above in 'a' can also capture the variable (this is done 00155 /// via tryCaptureVariable for variables and CheckCXXThisCapture for 00156 /// 'this' by passing in the index of the Lambda identified in step 'a') 00157 /// 00158 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a 00159 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda 00160 /// is at the top of the stack. 00161 /// 00162 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. 00163 /// 00164 /// 00165 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains 00166 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda 00167 /// which is capture-capable. If the return value evaluates to 'false' then 00168 /// no lambda is capture-capable for \p VarToCapture. 00169 00170 Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( 00171 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, 00172 VarDecl *VarToCapture, Sema &S) { 00173 00174 const Optional<unsigned> NoLambdaIsCaptureCapable; 00175 00176 const Optional<unsigned> OptionalStackIndex = 00177 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, 00178 VarToCapture); 00179 if (!OptionalStackIndex) 00180 return NoLambdaIsCaptureCapable; 00181 00182 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue(); 00183 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || 00184 S.getCurGenericLambda()) && 00185 "The capture ready lambda for a potential capture can only be the " 00186 "current lambda if it is a generic lambda"); 00187 00188 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = 00189 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); 00190 00191 // If VarToCapture is null, we are attempting to capture 'this' 00192 const bool IsCapturingThis = !VarToCapture; 00193 const bool IsCapturingVariable = !IsCapturingThis; 00194 00195 if (IsCapturingVariable) { 00196 // Check if the capture-ready lambda can truly capture the variable, by 00197 // checking whether all enclosing lambdas of the capture-ready lambda allow 00198 // the capture - i.e. make sure it is capture-capable. 00199 QualType CaptureType, DeclRefType; 00200 const bool CanCaptureVariable = 00201 !S.tryCaptureVariable(VarToCapture, 00202 /*ExprVarIsUsedInLoc*/ SourceLocation(), 00203 clang::Sema::TryCapture_Implicit, 00204 /*EllipsisLoc*/ SourceLocation(), 00205 /*BuildAndDiagnose*/ false, CaptureType, 00206 DeclRefType, &IndexOfCaptureReadyLambda); 00207 if (!CanCaptureVariable) 00208 return NoLambdaIsCaptureCapable; 00209 } else { 00210 // Check if the capture-ready lambda can truly capture 'this' by checking 00211 // whether all enclosing lambdas of the capture-ready lambda can capture 00212 // 'this'. 00213 const bool CanCaptureThis = 00214 !S.CheckCXXThisCapture( 00215 CaptureReadyLambdaLSI->PotentialThisCaptureLocation, 00216 /*Explicit*/ false, /*BuildAndDiagnose*/ false, 00217 &IndexOfCaptureReadyLambda); 00218 if (!CanCaptureThis) 00219 return NoLambdaIsCaptureCapable; 00220 } 00221 return IndexOfCaptureReadyLambda; 00222 } 00223 00224 static inline TemplateParameterList * 00225 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { 00226 if (LSI->GLTemplateParameterList) 00227 return LSI->GLTemplateParameterList; 00228 00229 if (LSI->AutoTemplateParams.size()) { 00230 SourceRange IntroRange = LSI->IntroducerRange; 00231 SourceLocation LAngleLoc = IntroRange.getBegin(); 00232 SourceLocation RAngleLoc = IntroRange.getEnd(); 00233 LSI->GLTemplateParameterList = TemplateParameterList::Create( 00234 SemaRef.Context, 00235 /*Template kw loc*/ SourceLocation(), LAngleLoc, 00236 (NamedDecl **)LSI->AutoTemplateParams.data(), 00237 LSI->AutoTemplateParams.size(), RAngleLoc); 00238 } 00239 return LSI->GLTemplateParameterList; 00240 } 00241 00242 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, 00243 TypeSourceInfo *Info, 00244 bool KnownDependent, 00245 LambdaCaptureDefault CaptureDefault) { 00246 DeclContext *DC = CurContext; 00247 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 00248 DC = DC->getParent(); 00249 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(), 00250 *this); 00251 // Start constructing the lambda class. 00252 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, 00253 IntroducerRange.getBegin(), 00254 KnownDependent, 00255 IsGenericLambda, 00256 CaptureDefault); 00257 DC->addDecl(Class); 00258 00259 return Class; 00260 } 00261 00262 /// \brief Determine whether the given context is or is enclosed in an inline 00263 /// function. 00264 static bool isInInlineFunction(const DeclContext *DC) { 00265 while (!DC->isFileContext()) { 00266 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 00267 if (FD->isInlined()) 00268 return true; 00269 00270 DC = DC->getLexicalParent(); 00271 } 00272 00273 return false; 00274 } 00275 00276 MangleNumberingContext * 00277 Sema::getCurrentMangleNumberContext(const DeclContext *DC, 00278 Decl *&ManglingContextDecl) { 00279 // Compute the context for allocating mangling numbers in the current 00280 // expression, if the ABI requires them. 00281 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; 00282 00283 enum ContextKind { 00284 Normal, 00285 DefaultArgument, 00286 DataMember, 00287 StaticDataMember 00288 } Kind = Normal; 00289 00290 // Default arguments of member function parameters that appear in a class 00291 // definition, as well as the initializers of data members, receive special 00292 // treatment. Identify them. 00293 if (ManglingContextDecl) { 00294 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { 00295 if (const DeclContext *LexicalDC 00296 = Param->getDeclContext()->getLexicalParent()) 00297 if (LexicalDC->isRecord()) 00298 Kind = DefaultArgument; 00299 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { 00300 if (Var->getDeclContext()->isRecord()) 00301 Kind = StaticDataMember; 00302 } else if (isa<FieldDecl>(ManglingContextDecl)) { 00303 Kind = DataMember; 00304 } 00305 } 00306 00307 // Itanium ABI [5.1.7]: 00308 // In the following contexts [...] the one-definition rule requires closure 00309 // types in different translation units to "correspond": 00310 bool IsInNonspecializedTemplate = 00311 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext(); 00312 switch (Kind) { 00313 case Normal: 00314 // -- the bodies of non-exported nonspecialized template functions 00315 // -- the bodies of inline functions 00316 if ((IsInNonspecializedTemplate && 00317 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) || 00318 isInInlineFunction(CurContext)) { 00319 ManglingContextDecl = nullptr; 00320 return &Context.getManglingNumberContext(DC); 00321 } 00322 00323 ManglingContextDecl = nullptr; 00324 return nullptr; 00325 00326 case StaticDataMember: 00327 // -- the initializers of nonspecialized static members of template classes 00328 if (!IsInNonspecializedTemplate) { 00329 ManglingContextDecl = nullptr; 00330 return nullptr; 00331 } 00332 // Fall through to get the current context. 00333 00334 case DataMember: 00335 // -- the in-class initializers of class members 00336 case DefaultArgument: 00337 // -- default arguments appearing in class definitions 00338 return &ExprEvalContexts.back().getMangleNumberingContext(Context); 00339 } 00340 00341 llvm_unreachable("unexpected context"); 00342 } 00343 00344 MangleNumberingContext & 00345 Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext( 00346 ASTContext &Ctx) { 00347 assert(ManglingContextDecl && "Need to have a context declaration"); 00348 if (!MangleNumbering) 00349 MangleNumbering = Ctx.createMangleNumberingContext(); 00350 return *MangleNumbering; 00351 } 00352 00353 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, 00354 SourceRange IntroducerRange, 00355 TypeSourceInfo *MethodTypeInfo, 00356 SourceLocation EndLoc, 00357 ArrayRef<ParmVarDecl *> Params) { 00358 QualType MethodType = MethodTypeInfo->getType(); 00359 TemplateParameterList *TemplateParams = 00360 getGenericLambdaTemplateParameterList(getCurLambda(), *this); 00361 // If a lambda appears in a dependent context or is a generic lambda (has 00362 // template parameters) and has an 'auto' return type, deduce it to a 00363 // dependent type. 00364 if (Class->isDependentContext() || TemplateParams) { 00365 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); 00366 QualType Result = FPT->getReturnType(); 00367 if (Result->isUndeducedType()) { 00368 Result = SubstAutoType(Result, Context.DependentTy); 00369 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(), 00370 FPT->getExtProtoInfo()); 00371 } 00372 } 00373 00374 // C++11 [expr.prim.lambda]p5: 00375 // The closure type for a lambda-expression has a public inline function 00376 // call operator (13.5.4) whose parameters and return type are described by 00377 // the lambda-expression's parameter-declaration-clause and 00378 // trailing-return-type respectively. 00379 DeclarationName MethodName 00380 = Context.DeclarationNames.getCXXOperatorName(OO_Call); 00381 DeclarationNameLoc MethodNameLoc; 00382 MethodNameLoc.CXXOperatorName.BeginOpNameLoc 00383 = IntroducerRange.getBegin().getRawEncoding(); 00384 MethodNameLoc.CXXOperatorName.EndOpNameLoc 00385 = IntroducerRange.getEnd().getRawEncoding(); 00386 CXXMethodDecl *Method 00387 = CXXMethodDecl::Create(Context, Class, EndLoc, 00388 DeclarationNameInfo(MethodName, 00389 IntroducerRange.getBegin(), 00390 MethodNameLoc), 00391 MethodType, MethodTypeInfo, 00392 SC_None, 00393 /*isInline=*/true, 00394 /*isConstExpr=*/false, 00395 EndLoc); 00396 Method->setAccess(AS_public); 00397 00398 // Temporarily set the lexical declaration context to the current 00399 // context, so that the Scope stack matches the lexical nesting. 00400 Method->setLexicalDeclContext(CurContext); 00401 // Create a function template if we have a template parameter list 00402 FunctionTemplateDecl *const TemplateMethod = TemplateParams ? 00403 FunctionTemplateDecl::Create(Context, Class, 00404 Method->getLocation(), MethodName, 00405 TemplateParams, 00406 Method) : nullptr; 00407 if (TemplateMethod) { 00408 TemplateMethod->setLexicalDeclContext(CurContext); 00409 TemplateMethod->setAccess(AS_public); 00410 Method->setDescribedFunctionTemplate(TemplateMethod); 00411 } 00412 00413 // Add parameters. 00414 if (!Params.empty()) { 00415 Method->setParams(Params); 00416 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()), 00417 const_cast<ParmVarDecl **>(Params.end()), 00418 /*CheckParameterNames=*/false); 00419 00420 for (auto P : Method->params()) 00421 P->setOwningFunction(Method); 00422 } 00423 00424 Decl *ManglingContextDecl; 00425 if (MangleNumberingContext *MCtx = 00426 getCurrentMangleNumberContext(Class->getDeclContext(), 00427 ManglingContextDecl)) { 00428 unsigned ManglingNumber = MCtx->getManglingNumber(Method); 00429 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl); 00430 } 00431 00432 return Method; 00433 } 00434 00435 void Sema::buildLambdaScope(LambdaScopeInfo *LSI, 00436 CXXMethodDecl *CallOperator, 00437 SourceRange IntroducerRange, 00438 LambdaCaptureDefault CaptureDefault, 00439 SourceLocation CaptureDefaultLoc, 00440 bool ExplicitParams, 00441 bool ExplicitResultType, 00442 bool Mutable) { 00443 LSI->CallOperator = CallOperator; 00444 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 00445 LSI->Lambda = LambdaClass; 00446 if (CaptureDefault == LCD_ByCopy) 00447 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 00448 else if (CaptureDefault == LCD_ByRef) 00449 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 00450 LSI->CaptureDefaultLoc = CaptureDefaultLoc; 00451 LSI->IntroducerRange = IntroducerRange; 00452 LSI->ExplicitParams = ExplicitParams; 00453 LSI->Mutable = Mutable; 00454 00455 if (ExplicitResultType) { 00456 LSI->ReturnType = CallOperator->getReturnType(); 00457 00458 if (!LSI->ReturnType->isDependentType() && 00459 !LSI->ReturnType->isVoidType()) { 00460 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType, 00461 diag::err_lambda_incomplete_result)) { 00462 // Do nothing. 00463 } 00464 } 00465 } else { 00466 LSI->HasImplicitReturnType = true; 00467 } 00468 } 00469 00470 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 00471 LSI->finishedExplicitCaptures(); 00472 } 00473 00474 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { 00475 // Introduce our parameters into the function scope 00476 for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 00477 p < NumParams; ++p) { 00478 ParmVarDecl *Param = CallOperator->getParamDecl(p); 00479 00480 // If this has an identifier, add it to the scope stack. 00481 if (CurScope && Param->getIdentifier()) { 00482 CheckShadow(CurScope, Param); 00483 00484 PushOnScopeChains(Param, CurScope); 00485 } 00486 } 00487 } 00488 00489 /// If this expression is an enumerator-like expression of some type 00490 /// T, return the type T; otherwise, return null. 00491 /// 00492 /// Pointer comparisons on the result here should always work because 00493 /// it's derived from either the parent of an EnumConstantDecl 00494 /// (i.e. the definition) or the declaration returned by 00495 /// EnumType::getDecl() (i.e. the definition). 00496 static EnumDecl *findEnumForBlockReturn(Expr *E) { 00497 // An expression is an enumerator-like expression of type T if, 00498 // ignoring parens and parens-like expressions: 00499 E = E->IgnoreParens(); 00500 00501 // - it is an enumerator whose enum type is T or 00502 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 00503 if (EnumConstantDecl *D 00504 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 00505 return cast<EnumDecl>(D->getDeclContext()); 00506 } 00507 return nullptr; 00508 } 00509 00510 // - it is a comma expression whose RHS is an enumerator-like 00511 // expression of type T or 00512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 00513 if (BO->getOpcode() == BO_Comma) 00514 return findEnumForBlockReturn(BO->getRHS()); 00515 return nullptr; 00516 } 00517 00518 // - it is a statement-expression whose value expression is an 00519 // enumerator-like expression of type T or 00520 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 00521 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) 00522 return findEnumForBlockReturn(last); 00523 return nullptr; 00524 } 00525 00526 // - it is a ternary conditional operator (not the GNU ?: 00527 // extension) whose second and third operands are 00528 // enumerator-like expressions of type T or 00529 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 00530 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) 00531 if (ED == findEnumForBlockReturn(CO->getFalseExpr())) 00532 return ED; 00533 return nullptr; 00534 } 00535 00536 // (implicitly:) 00537 // - it is an implicit integral conversion applied to an 00538 // enumerator-like expression of type T or 00539 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 00540 // We can sometimes see integral conversions in valid 00541 // enumerator-like expressions. 00542 if (ICE->getCastKind() == CK_IntegralCast) 00543 return findEnumForBlockReturn(ICE->getSubExpr()); 00544 00545 // Otherwise, just rely on the type. 00546 } 00547 00548 // - it is an expression of that formal enum type. 00549 if (const EnumType *ET = E->getType()->getAs<EnumType>()) { 00550 return ET->getDecl(); 00551 } 00552 00553 // Otherwise, nope. 00554 return nullptr; 00555 } 00556 00557 /// Attempt to find a type T for which the returned expression of the 00558 /// given statement is an enumerator-like expression of that type. 00559 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { 00560 if (Expr *retValue = ret->getRetValue()) 00561 return findEnumForBlockReturn(retValue); 00562 return nullptr; 00563 } 00564 00565 /// Attempt to find a common type T for which all of the returned 00566 /// expressions in a block are enumerator-like expressions of that 00567 /// type. 00568 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { 00569 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); 00570 00571 // Try to find one for the first return. 00572 EnumDecl *ED = findEnumForBlockReturn(*i); 00573 if (!ED) return nullptr; 00574 00575 // Check that the rest of the returns have the same enum. 00576 for (++i; i != e; ++i) { 00577 if (findEnumForBlockReturn(*i) != ED) 00578 return nullptr; 00579 } 00580 00581 // Never infer an anonymous enum type. 00582 if (!ED->hasNameForLinkage()) return nullptr; 00583 00584 return ED; 00585 } 00586 00587 /// Adjust the given return statements so that they formally return 00588 /// the given type. It should require, at most, an IntegralCast. 00589 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, 00590 QualType returnType) { 00591 for (ArrayRef<ReturnStmt*>::iterator 00592 i = returns.begin(), e = returns.end(); i != e; ++i) { 00593 ReturnStmt *ret = *i; 00594 Expr *retValue = ret->getRetValue(); 00595 if (S.Context.hasSameType(retValue->getType(), returnType)) 00596 continue; 00597 00598 // Right now we only support integral fixup casts. 00599 assert(returnType->isIntegralOrUnscopedEnumerationType()); 00600 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); 00601 00602 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); 00603 00604 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue); 00605 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, 00606 E, /*base path*/ nullptr, VK_RValue); 00607 if (cleanups) { 00608 cleanups->setSubExpr(E); 00609 } else { 00610 ret->setRetValue(E); 00611 } 00612 } 00613 } 00614 00615 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { 00616 assert(CSI.HasImplicitReturnType); 00617 // If it was ever a placeholder, it had to been deduced to DependentTy. 00618 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 00619 00620 // C++ Core Issue #975, proposed resolution: 00621 // If a lambda-expression does not include a trailing-return-type, 00622 // it is as if the trailing-return-type denotes the following type: 00623 // - if there are no return statements in the compound-statement, 00624 // or all return statements return either an expression of type 00625 // void or no expression or braced-init-list, the type void; 00626 // - otherwise, if all return statements return an expression 00627 // and the types of the returned expressions after 00628 // lvalue-to-rvalue conversion (4.1 [conv.lval]), 00629 // array-to-pointer conversion (4.2 [conv.array]), and 00630 // function-to-pointer conversion (4.3 [conv.func]) are the 00631 // same, that common type; 00632 // - otherwise, the program is ill-formed. 00633 // 00634 // In addition, in blocks in non-C++ modes, if all of the return 00635 // statements are enumerator-like expressions of some type T, where 00636 // T has a name for linkage, then we infer the return type of the 00637 // block to be that type. 00638 00639 // First case: no return statements, implicit void return type. 00640 ASTContext &Ctx = getASTContext(); 00641 if (CSI.Returns.empty()) { 00642 // It's possible there were simply no /valid/ return statements. 00643 // In this case, the first one we found may have at least given us a type. 00644 if (CSI.ReturnType.isNull()) 00645 CSI.ReturnType = Ctx.VoidTy; 00646 return; 00647 } 00648 00649 // Second case: at least one return statement has dependent type. 00650 // Delay type checking until instantiation. 00651 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); 00652 if (CSI.ReturnType->isDependentType()) 00653 return; 00654 00655 // Try to apply the enum-fuzz rule. 00656 if (!getLangOpts().CPlusPlus) { 00657 assert(isa<BlockScopeInfo>(CSI)); 00658 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); 00659 if (ED) { 00660 CSI.ReturnType = Context.getTypeDeclType(ED); 00661 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); 00662 return; 00663 } 00664 } 00665 00666 // Third case: only one return statement. Don't bother doing extra work! 00667 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(), 00668 E = CSI.Returns.end(); 00669 if (I+1 == E) 00670 return; 00671 00672 // General case: many return statements. 00673 // Check that they all have compatible return types. 00674 00675 // We require the return types to strictly match here. 00676 // Note that we've already done the required promotions as part of 00677 // processing the return statement. 00678 for (; I != E; ++I) { 00679 const ReturnStmt *RS = *I; 00680 const Expr *RetE = RS->getRetValue(); 00681 00682 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy); 00683 if (Context.hasSameType(ReturnType, CSI.ReturnType)) 00684 continue; 00685 00686 // FIXME: This is a poor diagnostic for ReturnStmts without expressions. 00687 // TODO: It's possible that the *first* return is the divergent one. 00688 Diag(RS->getLocStart(), 00689 diag::err_typecheck_missing_return_type_incompatible) 00690 << ReturnType << CSI.ReturnType 00691 << isa<LambdaScopeInfo>(CSI); 00692 // Continue iterating so that we keep emitting diagnostics. 00693 } 00694 } 00695 00696 QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc, 00697 bool ByRef, 00698 IdentifierInfo *Id, 00699 Expr *&Init) { 00700 00701 // We do not need to distinguish between direct-list-initialization 00702 // and copy-list-initialization here, because we will always deduce 00703 // std::initializer_list<T>, and direct- and copy-list-initialization 00704 // always behave the same for such a type. 00705 // FIXME: We should model whether an '=' was present. 00706 const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init); 00707 00708 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to 00709 // deduce against. 00710 QualType DeductType = Context.getAutoDeductType(); 00711 TypeLocBuilder TLB; 00712 TLB.pushTypeSpec(DeductType).setNameLoc(Loc); 00713 if (ByRef) { 00714 DeductType = BuildReferenceType(DeductType, true, Loc, Id); 00715 assert(!DeductType.isNull() && "can't build reference to auto"); 00716 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); 00717 } 00718 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); 00719 00720 // Are we a non-list direct initialization? 00721 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 00722 00723 Expr *DeduceInit = Init; 00724 // Initializer could be a C++ direct-initializer. Deduction only works if it 00725 // contains exactly one expression. 00726 if (CXXDirectInit) { 00727 if (CXXDirectInit->getNumExprs() == 0) { 00728 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression) 00729 << DeclarationName(Id) << TSI->getType() << Loc; 00730 return QualType(); 00731 } else if (CXXDirectInit->getNumExprs() > 1) { 00732 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 00733 diag::err_init_capture_multiple_expressions) 00734 << DeclarationName(Id) << TSI->getType() << Loc; 00735 return QualType(); 00736 } else { 00737 DeduceInit = CXXDirectInit->getExpr(0); 00738 if (isa<InitListExpr>(DeduceInit)) 00739 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_paren_braces) 00740 << DeclarationName(Id) << Loc; 00741 } 00742 } 00743 00744 // Now deduce against the initialization expression and store the deduced 00745 // type below. 00746 QualType DeducedType; 00747 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 00748 if (isa<InitListExpr>(Init)) 00749 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list) 00750 << DeclarationName(Id) 00751 << (DeduceInit->getType().isNull() ? TSI->getType() 00752 : DeduceInit->getType()) 00753 << DeduceInit->getSourceRange(); 00754 else 00755 Diag(Loc, diag::err_init_capture_deduction_failure) 00756 << DeclarationName(Id) << TSI->getType() 00757 << (DeduceInit->getType().isNull() ? TSI->getType() 00758 : DeduceInit->getType()) 00759 << DeduceInit->getSourceRange(); 00760 } 00761 if (DeducedType.isNull()) 00762 return QualType(); 00763 00764 // Perform initialization analysis and ensure any implicit conversions 00765 // (such as lvalue-to-rvalue) are enforced. 00766 InitializedEntity Entity = 00767 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); 00768 InitializationKind Kind = 00769 IsDirectInit 00770 ? (CXXDirectInit ? InitializationKind::CreateDirect( 00771 Loc, Init->getLocStart(), Init->getLocEnd()) 00772 : InitializationKind::CreateDirectList(Loc)) 00773 : InitializationKind::CreateCopy(Loc, Init->getLocStart()); 00774 00775 MultiExprArg Args = Init; 00776 if (CXXDirectInit) 00777 Args = 00778 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); 00779 QualType DclT; 00780 InitializationSequence InitSeq(*this, Entity, Kind, Args); 00781 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 00782 00783 if (Result.isInvalid()) 00784 return QualType(); 00785 Init = Result.getAs<Expr>(); 00786 00787 // The init-capture initialization is a full-expression that must be 00788 // processed as one before we enter the declcontext of the lambda's 00789 // call-operator. 00790 Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false, 00791 /*IsConstexpr*/ false, 00792 /*IsLambdaInitCaptureInitalizer*/ true); 00793 if (Result.isInvalid()) 00794 return QualType(); 00795 00796 Init = Result.getAs<Expr>(); 00797 return DeducedType; 00798 } 00799 00800 VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc, 00801 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) { 00802 00803 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, 00804 Loc); 00805 // Create a dummy variable representing the init-capture. This is not actually 00806 // used as a variable, and only exists as a way to name and refer to the 00807 // init-capture. 00808 // FIXME: Pass in separate source locations for '&' and identifier. 00809 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc, 00810 Loc, Id, InitCaptureType, TSI, SC_Auto); 00811 NewVD->setInitCapture(true); 00812 NewVD->setReferenced(true); 00813 NewVD->markUsed(Context); 00814 NewVD->setInit(Init); 00815 return NewVD; 00816 00817 } 00818 00819 FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) { 00820 FieldDecl *Field = FieldDecl::Create( 00821 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(), 00822 nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false, 00823 ICIS_NoInit); 00824 Field->setImplicit(true); 00825 Field->setAccess(AS_private); 00826 LSI->Lambda->addDecl(Field); 00827 00828 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(), 00829 /*isNested*/false, Var->getLocation(), SourceLocation(), 00830 Var->getType(), Var->getInit()); 00831 return Field; 00832 } 00833 00834 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 00835 Declarator &ParamInfo, Scope *CurScope) { 00836 // Determine if we're within a context where we know that the lambda will 00837 // be dependent, because there are template parameters in scope. 00838 bool KnownDependent = false; 00839 LambdaScopeInfo *const LSI = getCurLambda(); 00840 assert(LSI && "LambdaScopeInfo should be on stack!"); 00841 TemplateParameterList *TemplateParams = 00842 getGenericLambdaTemplateParameterList(LSI, *this); 00843 00844 if (Scope *TmplScope = CurScope->getTemplateParamParent()) { 00845 // Since we have our own TemplateParams, so check if an outer scope 00846 // has template params, only then are we in a dependent scope. 00847 if (TemplateParams) { 00848 TmplScope = TmplScope->getParent(); 00849 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : nullptr; 00850 } 00851 if (TmplScope && !TmplScope->decl_empty()) 00852 KnownDependent = true; 00853 } 00854 // Determine the signature of the call operator. 00855 TypeSourceInfo *MethodTyInfo; 00856 bool ExplicitParams = true; 00857 bool ExplicitResultType = true; 00858 bool ContainsUnexpandedParameterPack = false; 00859 SourceLocation EndLoc; 00860 SmallVector<ParmVarDecl *, 8> Params; 00861 if (ParamInfo.getNumTypeObjects() == 0) { 00862 // C++11 [expr.prim.lambda]p4: 00863 // If a lambda-expression does not include a lambda-declarator, it is as 00864 // if the lambda-declarator were (). 00865 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 00866 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 00867 EPI.HasTrailingReturn = true; 00868 EPI.TypeQuals |= DeclSpec::TQ_const; 00869 // C++1y [expr.prim.lambda]: 00870 // The lambda return type is 'auto', which is replaced by the 00871 // trailing-return type if provided and/or deduced from 'return' 00872 // statements 00873 // We don't do this before C++1y, because we don't support deduced return 00874 // types there. 00875 QualType DefaultTypeForNoTrailingReturn = 00876 getLangOpts().CPlusPlus14 ? Context.getAutoDeductType() 00877 : Context.DependentTy; 00878 QualType MethodTy = 00879 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI); 00880 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); 00881 ExplicitParams = false; 00882 ExplicitResultType = false; 00883 EndLoc = Intro.Range.getEnd(); 00884 } else { 00885 assert(ParamInfo.isFunctionDeclarator() && 00886 "lambda-declarator is a function"); 00887 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 00888 00889 // C++11 [expr.prim.lambda]p5: 00890 // This function call operator is declared const (9.3.1) if and only if 00891 // the lambda-expression's parameter-declaration-clause is not followed 00892 // by mutable. It is neither virtual nor declared volatile. [...] 00893 if (!FTI.hasMutableQualifier()) 00894 FTI.TypeQuals |= DeclSpec::TQ_const; 00895 00896 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); 00897 assert(MethodTyInfo && "no type from lambda-declarator"); 00898 EndLoc = ParamInfo.getSourceRange().getEnd(); 00899 00900 ExplicitResultType = FTI.hasTrailingReturnType(); 00901 00902 if (FTIHasNonVoidParameters(FTI)) { 00903 Params.reserve(FTI.NumParams); 00904 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) 00905 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param)); 00906 } 00907 00908 // Check for unexpanded parameter packs in the method type. 00909 if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) 00910 ContainsUnexpandedParameterPack = true; 00911 } 00912 00913 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo, 00914 KnownDependent, Intro.Default); 00915 00916 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range, 00917 MethodTyInfo, EndLoc, Params); 00918 if (ExplicitParams) 00919 CheckCXXDefaultArguments(Method); 00920 00921 // Attributes on the lambda apply to the method. 00922 ProcessDeclAttributes(CurScope, Method, ParamInfo); 00923 00924 // Introduce the function call operator as the current declaration context. 00925 PushDeclContext(CurScope, Method); 00926 00927 // Build the lambda scope. 00928 buildLambdaScope(LSI, Method, 00929 Intro.Range, 00930 Intro.Default, Intro.DefaultLoc, 00931 ExplicitParams, 00932 ExplicitResultType, 00933 !Method->isConst()); 00934 00935 // C++11 [expr.prim.lambda]p9: 00936 // A lambda-expression whose smallest enclosing scope is a block scope is a 00937 // local lambda expression; any other lambda expression shall not have a 00938 // capture-default or simple-capture in its lambda-introducer. 00939 // 00940 // For simple-captures, this is covered by the check below that any named 00941 // entity is a variable that can be captured. 00942 // 00943 // For DR1632, we also allow a capture-default in any context where we can 00944 // odr-use 'this' (in particular, in a default initializer for a non-static 00945 // data member). 00946 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() && 00947 (getCurrentThisType().isNull() || 00948 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true, 00949 /*BuildAndDiagnose*/false))) 00950 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); 00951 00952 // Distinct capture names, for diagnostics. 00953 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames; 00954 00955 // Handle explicit captures. 00956 SourceLocation PrevCaptureLoc 00957 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc; 00958 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; 00959 PrevCaptureLoc = C->Loc, ++C) { 00960 if (C->Kind == LCK_This) { 00961 // C++11 [expr.prim.lambda]p8: 00962 // An identifier or this shall not appear more than once in a 00963 // lambda-capture. 00964 if (LSI->isCXXThisCaptured()) { 00965 Diag(C->Loc, diag::err_capture_more_than_once) 00966 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) 00967 << FixItHint::CreateRemoval( 00968 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 00969 continue; 00970 } 00971 00972 // C++11 [expr.prim.lambda]p8: 00973 // If a lambda-capture includes a capture-default that is =, the 00974 // lambda-capture shall not contain this [...]. 00975 if (Intro.Default == LCD_ByCopy) { 00976 Diag(C->Loc, diag::err_this_capture_with_copy_default) 00977 << FixItHint::CreateRemoval( 00978 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 00979 continue; 00980 } 00981 00982 // C++11 [expr.prim.lambda]p12: 00983 // If this is captured by a local lambda expression, its nearest 00984 // enclosing function shall be a non-static member function. 00985 QualType ThisCaptureType = getCurrentThisType(); 00986 if (ThisCaptureType.isNull()) { 00987 Diag(C->Loc, diag::err_this_capture) << true; 00988 continue; 00989 } 00990 00991 CheckCXXThisCapture(C->Loc, /*Explicit=*/true); 00992 continue; 00993 } 00994 00995 assert(C->Id && "missing identifier for capture"); 00996 00997 if (C->Init.isInvalid()) 00998 continue; 00999 01000 VarDecl *Var = nullptr; 01001 if (C->Init.isUsable()) { 01002 Diag(C->Loc, getLangOpts().CPlusPlus14 01003 ? diag::warn_cxx11_compat_init_capture 01004 : diag::ext_init_capture); 01005 01006 if (C->Init.get()->containsUnexpandedParameterPack()) 01007 ContainsUnexpandedParameterPack = true; 01008 // If the initializer expression is usable, but the InitCaptureType 01009 // is not, then an error has occurred - so ignore the capture for now. 01010 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. 01011 // FIXME: we should create the init capture variable and mark it invalid 01012 // in this case. 01013 if (C->InitCaptureType.get().isNull()) 01014 continue; 01015 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), 01016 C->Id, C->Init.get()); 01017 // C++1y [expr.prim.lambda]p11: 01018 // An init-capture behaves as if it declares and explicitly 01019 // captures a variable [...] whose declarative region is the 01020 // lambda-expression's compound-statement 01021 if (Var) 01022 PushOnScopeChains(Var, CurScope, false); 01023 } else { 01024 // C++11 [expr.prim.lambda]p8: 01025 // If a lambda-capture includes a capture-default that is &, the 01026 // identifiers in the lambda-capture shall not be preceded by &. 01027 // If a lambda-capture includes a capture-default that is =, [...] 01028 // each identifier it contains shall be preceded by &. 01029 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 01030 Diag(C->Loc, diag::err_reference_capture_with_reference_default) 01031 << FixItHint::CreateRemoval( 01032 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 01033 continue; 01034 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 01035 Diag(C->Loc, diag::err_copy_capture_with_copy_default) 01036 << FixItHint::CreateRemoval( 01037 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 01038 continue; 01039 } 01040 01041 // C++11 [expr.prim.lambda]p10: 01042 // The identifiers in a capture-list are looked up using the usual 01043 // rules for unqualified name lookup (3.4.1) 01044 DeclarationNameInfo Name(C->Id, C->Loc); 01045 LookupResult R(*this, Name, LookupOrdinaryName); 01046 LookupName(R, CurScope); 01047 if (R.isAmbiguous()) 01048 continue; 01049 if (R.empty()) { 01050 // FIXME: Disable corrections that would add qualification? 01051 CXXScopeSpec ScopeSpec; 01052 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, 01053 llvm::make_unique<DeclFilterCCC<VarDecl>>())) 01054 continue; 01055 } 01056 01057 Var = R.getAsSingle<VarDecl>(); 01058 if (Var && DiagnoseUseOfDecl(Var, C->Loc)) 01059 continue; 01060 } 01061 01062 // C++11 [expr.prim.lambda]p8: 01063 // An identifier or this shall not appear more than once in a 01064 // lambda-capture. 01065 if (!CaptureNames.insert(C->Id)) { 01066 if (Var && LSI->isCaptured(Var)) { 01067 Diag(C->Loc, diag::err_capture_more_than_once) 01068 << C->Id << SourceRange(LSI->getCapture(Var).getLocation()) 01069 << FixItHint::CreateRemoval( 01070 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 01071 } else 01072 // Previous capture captured something different (one or both was 01073 // an init-cpature): no fixit. 01074 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; 01075 continue; 01076 } 01077 01078 // C++11 [expr.prim.lambda]p10: 01079 // [...] each such lookup shall find a variable with automatic storage 01080 // duration declared in the reaching scope of the local lambda expression. 01081 // Note that the 'reaching scope' check happens in tryCaptureVariable(). 01082 if (!Var) { 01083 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 01084 continue; 01085 } 01086 01087 // Ignore invalid decls; they'll just confuse the code later. 01088 if (Var->isInvalidDecl()) 01089 continue; 01090 01091 if (!Var->hasLocalStorage()) { 01092 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 01093 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 01094 continue; 01095 } 01096 01097 // C++11 [expr.prim.lambda]p23: 01098 // A capture followed by an ellipsis is a pack expansion (14.5.3). 01099 SourceLocation EllipsisLoc; 01100 if (C->EllipsisLoc.isValid()) { 01101 if (Var->isParameterPack()) { 01102 EllipsisLoc = C->EllipsisLoc; 01103 } else { 01104 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 01105 << SourceRange(C->Loc); 01106 01107 // Just ignore the ellipsis. 01108 } 01109 } else if (Var->isParameterPack()) { 01110 ContainsUnexpandedParameterPack = true; 01111 } 01112 01113 if (C->Init.isUsable()) { 01114 buildInitCaptureField(LSI, Var); 01115 } else { 01116 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : 01117 TryCapture_ExplicitByVal; 01118 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 01119 } 01120 } 01121 finishLambdaExplicitCaptures(LSI); 01122 01123 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; 01124 01125 // Add lambda parameters into scope. 01126 addLambdaParameters(Method, CurScope); 01127 01128 // Enter a new evaluation context to insulate the lambda from any 01129 // cleanups from the enclosing full-expression. 01130 PushExpressionEvaluationContext(PotentiallyEvaluated); 01131 } 01132 01133 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 01134 bool IsInstantiation) { 01135 LambdaScopeInfo *LSI = getCurLambda(); 01136 01137 // Leave the expression-evaluation context. 01138 DiscardCleanupsInEvaluationContext(); 01139 PopExpressionEvaluationContext(); 01140 01141 // Leave the context of the lambda. 01142 if (!IsInstantiation) 01143 PopDeclContext(); 01144 01145 // Finalize the lambda. 01146 CXXRecordDecl *Class = LSI->Lambda; 01147 Class->setInvalidDecl(); 01148 SmallVector<Decl*, 4> Fields(Class->fields()); 01149 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 01150 SourceLocation(), nullptr); 01151 CheckCompletedCXXClass(Class); 01152 01153 PopFunctionScopeInfo(); 01154 } 01155 01156 /// \brief Add a lambda's conversion to function pointer, as described in 01157 /// C++11 [expr.prim.lambda]p6. 01158 static void addFunctionPointerConversion(Sema &S, 01159 SourceRange IntroducerRange, 01160 CXXRecordDecl *Class, 01161 CXXMethodDecl *CallOperator) { 01162 // Add the conversion to function pointer. 01163 const FunctionProtoType *CallOpProto = 01164 CallOperator->getType()->getAs<FunctionProtoType>(); 01165 const FunctionProtoType::ExtProtoInfo CallOpExtInfo = 01166 CallOpProto->getExtProtoInfo(); 01167 QualType PtrToFunctionTy; 01168 QualType InvokerFunctionTy; 01169 { 01170 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; 01171 CallingConv CC = S.Context.getDefaultCallingConvention( 01172 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 01173 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); 01174 InvokerExtInfo.TypeQuals = 0; 01175 assert(InvokerExtInfo.RefQualifier == RQ_None && 01176 "Lambda's call operator should not have a reference qualifier"); 01177 InvokerFunctionTy = 01178 S.Context.getFunctionType(CallOpProto->getReturnType(), 01179 CallOpProto->getParamTypes(), InvokerExtInfo); 01180 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); 01181 } 01182 01183 // Create the type of the conversion function. 01184 FunctionProtoType::ExtProtoInfo ConvExtInfo( 01185 S.Context.getDefaultCallingConvention( 01186 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 01187 // The conversion function is always const. 01188 ConvExtInfo.TypeQuals = Qualifiers::Const; 01189 QualType ConvTy = 01190 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); 01191 01192 SourceLocation Loc = IntroducerRange.getBegin(); 01193 DeclarationName ConversionName 01194 = S.Context.DeclarationNames.getCXXConversionFunctionName( 01195 S.Context.getCanonicalType(PtrToFunctionTy)); 01196 DeclarationNameLoc ConvNameLoc; 01197 // Construct a TypeSourceInfo for the conversion function, and wire 01198 // all the parameters appropriately for the FunctionProtoTypeLoc 01199 // so that everything works during transformation/instantiation of 01200 // generic lambdas. 01201 // The main reason for wiring up the parameters of the conversion 01202 // function with that of the call operator is so that constructs 01203 // like the following work: 01204 // auto L = [](auto b) { <-- 1 01205 // return [](auto a) -> decltype(a) { <-- 2 01206 // return a; 01207 // }; 01208 // }; 01209 // int (*fp)(int) = L(5); 01210 // Because the trailing return type can contain DeclRefExprs that refer 01211 // to the original call operator's variables, we hijack the call 01212 // operators ParmVarDecls below. 01213 TypeSourceInfo *ConvNamePtrToFunctionTSI = 01214 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); 01215 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI; 01216 01217 // The conversion function is a conversion to a pointer-to-function. 01218 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); 01219 FunctionProtoTypeLoc ConvTL = 01220 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); 01221 // Get the result of the conversion function which is a pointer-to-function. 01222 PointerTypeLoc PtrToFunctionTL = 01223 ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); 01224 // Do the same for the TypeSourceInfo that is used to name the conversion 01225 // operator. 01226 PointerTypeLoc ConvNamePtrToFunctionTL = 01227 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); 01228 01229 // Get the underlying function types that the conversion function will 01230 // be converting to (should match the type of the call operator). 01231 FunctionProtoTypeLoc CallOpConvTL = 01232 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 01233 FunctionProtoTypeLoc CallOpConvNameTL = 01234 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); 01235 01236 // Wire up the FunctionProtoTypeLocs with the call operator's parameters. 01237 // These parameter's are essentially used to transform the name and 01238 // the type of the conversion operator. By using the same parameters 01239 // as the call operator's we don't have to fix any back references that 01240 // the trailing return type of the call operator's uses (such as 01241 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) 01242 // - we can simply use the return type of the call operator, and 01243 // everything should work. 01244 SmallVector<ParmVarDecl *, 4> InvokerParams; 01245 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 01246 ParmVarDecl *From = CallOperator->getParamDecl(I); 01247 01248 InvokerParams.push_back(ParmVarDecl::Create(S.Context, 01249 // Temporarily add to the TU. This is set to the invoker below. 01250 S.Context.getTranslationUnitDecl(), 01251 From->getLocStart(), 01252 From->getLocation(), 01253 From->getIdentifier(), 01254 From->getType(), 01255 From->getTypeSourceInfo(), 01256 From->getStorageClass(), 01257 /*DefaultArg=*/nullptr)); 01258 CallOpConvTL.setParam(I, From); 01259 CallOpConvNameTL.setParam(I, From); 01260 } 01261 01262 CXXConversionDecl *Conversion 01263 = CXXConversionDecl::Create(S.Context, Class, Loc, 01264 DeclarationNameInfo(ConversionName, 01265 Loc, ConvNameLoc), 01266 ConvTy, 01267 ConvTSI, 01268 /*isInline=*/true, /*isExplicit=*/false, 01269 /*isConstexpr=*/false, 01270 CallOperator->getBody()->getLocEnd()); 01271 Conversion->setAccess(AS_public); 01272 Conversion->setImplicit(true); 01273 01274 if (Class->isGenericLambda()) { 01275 // Create a template version of the conversion operator, using the template 01276 // parameter list of the function call operator. 01277 FunctionTemplateDecl *TemplateCallOperator = 01278 CallOperator->getDescribedFunctionTemplate(); 01279 FunctionTemplateDecl *ConversionTemplate = 01280 FunctionTemplateDecl::Create(S.Context, Class, 01281 Loc, ConversionName, 01282 TemplateCallOperator->getTemplateParameters(), 01283 Conversion); 01284 ConversionTemplate->setAccess(AS_public); 01285 ConversionTemplate->setImplicit(true); 01286 Conversion->setDescribedFunctionTemplate(ConversionTemplate); 01287 Class->addDecl(ConversionTemplate); 01288 } else 01289 Class->addDecl(Conversion); 01290 // Add a non-static member function that will be the result of 01291 // the conversion with a certain unique ID. 01292 DeclarationName InvokerName = &S.Context.Idents.get( 01293 getLambdaStaticInvokerName()); 01294 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() 01295 // we should get a prebuilt TrivialTypeSourceInfo from Context 01296 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc 01297 // then rewire the parameters accordingly, by hoisting up the InvokeParams 01298 // loop below and then use its Params to set Invoke->setParams(...) below. 01299 // This would avoid the 'const' qualifier of the calloperator from 01300 // contaminating the type of the invoker, which is currently adjusted 01301 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the 01302 // trailing return type of the invoker would require a visitor to rebuild 01303 // the trailing return type and adjusting all back DeclRefExpr's to refer 01304 // to the new static invoker parameters - not the call operator's. 01305 CXXMethodDecl *Invoke 01306 = CXXMethodDecl::Create(S.Context, Class, Loc, 01307 DeclarationNameInfo(InvokerName, Loc), 01308 InvokerFunctionTy, 01309 CallOperator->getTypeSourceInfo(), 01310 SC_Static, /*IsInline=*/true, 01311 /*IsConstexpr=*/false, 01312 CallOperator->getBody()->getLocEnd()); 01313 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) 01314 InvokerParams[I]->setOwningFunction(Invoke); 01315 Invoke->setParams(InvokerParams); 01316 Invoke->setAccess(AS_private); 01317 Invoke->setImplicit(true); 01318 if (Class->isGenericLambda()) { 01319 FunctionTemplateDecl *TemplateCallOperator = 01320 CallOperator->getDescribedFunctionTemplate(); 01321 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( 01322 S.Context, Class, Loc, InvokerName, 01323 TemplateCallOperator->getTemplateParameters(), 01324 Invoke); 01325 StaticInvokerTemplate->setAccess(AS_private); 01326 StaticInvokerTemplate->setImplicit(true); 01327 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); 01328 Class->addDecl(StaticInvokerTemplate); 01329 } else 01330 Class->addDecl(Invoke); 01331 } 01332 01333 /// \brief Add a lambda's conversion to block pointer. 01334 static void addBlockPointerConversion(Sema &S, 01335 SourceRange IntroducerRange, 01336 CXXRecordDecl *Class, 01337 CXXMethodDecl *CallOperator) { 01338 const FunctionProtoType *Proto 01339 = CallOperator->getType()->getAs<FunctionProtoType>(); 01340 QualType BlockPtrTy; 01341 { 01342 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 01343 ExtInfo.TypeQuals = 0; 01344 QualType FunctionTy = S.Context.getFunctionType( 01345 Proto->getReturnType(), Proto->getParamTypes(), ExtInfo); 01346 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 01347 } 01348 01349 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention( 01350 /*IsVariadic=*/false, /*IsCXXMethod=*/true)); 01351 ExtInfo.TypeQuals = Qualifiers::Const; 01352 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo); 01353 01354 SourceLocation Loc = IntroducerRange.getBegin(); 01355 DeclarationName Name 01356 = S.Context.DeclarationNames.getCXXConversionFunctionName( 01357 S.Context.getCanonicalType(BlockPtrTy)); 01358 DeclarationNameLoc NameLoc; 01359 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); 01360 CXXConversionDecl *Conversion 01361 = CXXConversionDecl::Create(S.Context, Class, Loc, 01362 DeclarationNameInfo(Name, Loc, NameLoc), 01363 ConvTy, 01364 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 01365 /*isInline=*/true, /*isExplicit=*/false, 01366 /*isConstexpr=*/false, 01367 CallOperator->getBody()->getLocEnd()); 01368 Conversion->setAccess(AS_public); 01369 Conversion->setImplicit(true); 01370 Class->addDecl(Conversion); 01371 } 01372 01373 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 01374 Scope *CurScope, 01375 bool IsInstantiation) { 01376 // Collect information from the lambda scope. 01377 SmallVector<LambdaCapture, 4> Captures; 01378 SmallVector<Expr *, 4> CaptureInits; 01379 LambdaCaptureDefault CaptureDefault; 01380 SourceLocation CaptureDefaultLoc; 01381 CXXRecordDecl *Class; 01382 CXXMethodDecl *CallOperator; 01383 SourceRange IntroducerRange; 01384 bool ExplicitParams; 01385 bool ExplicitResultType; 01386 bool LambdaExprNeedsCleanups; 01387 bool ContainsUnexpandedParameterPack; 01388 SmallVector<VarDecl *, 4> ArrayIndexVars; 01389 SmallVector<unsigned, 4> ArrayIndexStarts; 01390 { 01391 LambdaScopeInfo *LSI = getCurLambda(); 01392 CallOperator = LSI->CallOperator; 01393 Class = LSI->Lambda; 01394 IntroducerRange = LSI->IntroducerRange; 01395 ExplicitParams = LSI->ExplicitParams; 01396 ExplicitResultType = !LSI->HasImplicitReturnType; 01397 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups; 01398 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; 01399 ArrayIndexVars.swap(LSI->ArrayIndexVars); 01400 ArrayIndexStarts.swap(LSI->ArrayIndexStarts); 01401 01402 // Translate captures. 01403 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 01404 LambdaScopeInfo::Capture From = LSI->Captures[I]; 01405 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 01406 bool IsImplicit = I >= LSI->NumExplicitCaptures; 01407 01408 // Handle 'this' capture. 01409 if (From.isThisCapture()) { 01410 Captures.push_back( 01411 LambdaCapture(From.getLocation(), IsImplicit, LCK_This)); 01412 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(), 01413 getCurrentThisType(), 01414 /*isImplicit=*/true)); 01415 continue; 01416 } 01417 if (From.isVLATypeCapture()) { 01418 Captures.push_back( 01419 LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType)); 01420 CaptureInits.push_back(nullptr); 01421 continue; 01422 } 01423 01424 VarDecl *Var = From.getVariable(); 01425 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef; 01426 Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind, 01427 Var, From.getEllipsisLoc())); 01428 CaptureInits.push_back(From.getInitExpr()); 01429 } 01430 01431 switch (LSI->ImpCaptureStyle) { 01432 case CapturingScopeInfo::ImpCap_None: 01433 CaptureDefault = LCD_None; 01434 break; 01435 01436 case CapturingScopeInfo::ImpCap_LambdaByval: 01437 CaptureDefault = LCD_ByCopy; 01438 break; 01439 01440 case CapturingScopeInfo::ImpCap_CapturedRegion: 01441 case CapturingScopeInfo::ImpCap_LambdaByref: 01442 CaptureDefault = LCD_ByRef; 01443 break; 01444 01445 case CapturingScopeInfo::ImpCap_Block: 01446 llvm_unreachable("block capture in lambda"); 01447 break; 01448 } 01449 CaptureDefaultLoc = LSI->CaptureDefaultLoc; 01450 01451 // C++11 [expr.prim.lambda]p4: 01452 // If a lambda-expression does not include a 01453 // trailing-return-type, it is as if the trailing-return-type 01454 // denotes the following type: 01455 // 01456 // Skip for C++1y return type deduction semantics which uses 01457 // different machinery. 01458 // FIXME: Refactor and Merge the return type deduction machinery. 01459 // FIXME: Assumes current resolution to core issue 975. 01460 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus14) { 01461 deduceClosureReturnType(*LSI); 01462 01463 // - if there are no return statements in the 01464 // compound-statement, or all return statements return 01465 // either an expression of type void or no expression or 01466 // braced-init-list, the type void; 01467 if (LSI->ReturnType.isNull()) { 01468 LSI->ReturnType = Context.VoidTy; 01469 } 01470 01471 // Create a function type with the inferred return type. 01472 const FunctionProtoType *Proto 01473 = CallOperator->getType()->getAs<FunctionProtoType>(); 01474 QualType FunctionTy = Context.getFunctionType( 01475 LSI->ReturnType, Proto->getParamTypes(), Proto->getExtProtoInfo()); 01476 CallOperator->setType(FunctionTy); 01477 } 01478 // C++ [expr.prim.lambda]p7: 01479 // The lambda-expression's compound-statement yields the 01480 // function-body (8.4) of the function call operator [...]. 01481 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation); 01482 CallOperator->setLexicalDeclContext(Class); 01483 Decl *TemplateOrNonTemplateCallOperatorDecl = 01484 CallOperator->getDescribedFunctionTemplate() 01485 ? CallOperator->getDescribedFunctionTemplate() 01486 : cast<Decl>(CallOperator); 01487 01488 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); 01489 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl); 01490 01491 PopExpressionEvaluationContext(); 01492 01493 // C++11 [expr.prim.lambda]p6: 01494 // The closure type for a lambda-expression with no lambda-capture 01495 // has a public non-virtual non-explicit const conversion function 01496 // to pointer to function having the same parameter and return 01497 // types as the closure type's function call operator. 01498 if (Captures.empty() && CaptureDefault == LCD_None) 01499 addFunctionPointerConversion(*this, IntroducerRange, Class, 01500 CallOperator); 01501 01502 // Objective-C++: 01503 // The closure type for a lambda-expression has a public non-virtual 01504 // non-explicit const conversion function to a block pointer having the 01505 // same parameter and return types as the closure type's function call 01506 // operator. 01507 // FIXME: Fix generic lambda to block conversions. 01508 if (getLangOpts().Blocks && getLangOpts().ObjC1 && 01509 !Class->isGenericLambda()) 01510 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 01511 01512 // Finalize the lambda class. 01513 SmallVector<Decl*, 4> Fields(Class->fields()); 01514 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), 01515 SourceLocation(), nullptr); 01516 CheckCompletedCXXClass(Class); 01517 } 01518 01519 if (LambdaExprNeedsCleanups) 01520 ExprNeedsCleanups = true; 01521 01522 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 01523 CaptureDefault, CaptureDefaultLoc, 01524 Captures, 01525 ExplicitParams, ExplicitResultType, 01526 CaptureInits, ArrayIndexVars, 01527 ArrayIndexStarts, Body->getLocEnd(), 01528 ContainsUnexpandedParameterPack); 01529 01530 if (!CurContext->isDependentContext()) { 01531 switch (ExprEvalContexts.back().Context) { 01532 // C++11 [expr.prim.lambda]p2: 01533 // A lambda-expression shall not appear in an unevaluated operand 01534 // (Clause 5). 01535 case Unevaluated: 01536 case UnevaluatedAbstract: 01537 // C++1y [expr.const]p2: 01538 // A conditional-expression e is a core constant expression unless the 01539 // evaluation of e, following the rules of the abstract machine, would 01540 // evaluate [...] a lambda-expression. 01541 // 01542 // This is technically incorrect, there are some constant evaluated contexts 01543 // where this should be allowed. We should probably fix this when DR1607 is 01544 // ratified, it lays out the exact set of conditions where we shouldn't 01545 // allow a lambda-expression. 01546 case ConstantEvaluated: 01547 // We don't actually diagnose this case immediately, because we 01548 // could be within a context where we might find out later that 01549 // the expression is potentially evaluated (e.g., for typeid). 01550 ExprEvalContexts.back().Lambdas.push_back(Lambda); 01551 break; 01552 01553 case PotentiallyEvaluated: 01554 case PotentiallyEvaluatedIfUsed: 01555 break; 01556 } 01557 } 01558 01559 return MaybeBindToTemporary(Lambda); 01560 } 01561 01562 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 01563 SourceLocation ConvLocation, 01564 CXXConversionDecl *Conv, 01565 Expr *Src) { 01566 // Make sure that the lambda call operator is marked used. 01567 CXXRecordDecl *Lambda = Conv->getParent(); 01568 CXXMethodDecl *CallOperator 01569 = cast<CXXMethodDecl>( 01570 Lambda->lookup( 01571 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 01572 CallOperator->setReferenced(); 01573 CallOperator->markUsed(Context); 01574 01575 ExprResult Init = PerformCopyInitialization( 01576 InitializedEntity::InitializeBlock(ConvLocation, 01577 Src->getType(), 01578 /*NRVO=*/false), 01579 CurrentLocation, Src); 01580 if (!Init.isInvalid()) 01581 Init = ActOnFinishFullExpr(Init.get()); 01582 01583 if (Init.isInvalid()) 01584 return ExprError(); 01585 01586 // Create the new block to be returned. 01587 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 01588 01589 // Set the type information. 01590 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 01591 Block->setIsVariadic(CallOperator->isVariadic()); 01592 Block->setBlockMissingReturnType(false); 01593 01594 // Add parameters. 01595 SmallVector<ParmVarDecl *, 4> BlockParams; 01596 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 01597 ParmVarDecl *From = CallOperator->getParamDecl(I); 01598 BlockParams.push_back(ParmVarDecl::Create(Context, Block, 01599 From->getLocStart(), 01600 From->getLocation(), 01601 From->getIdentifier(), 01602 From->getType(), 01603 From->getTypeSourceInfo(), 01604 From->getStorageClass(), 01605 /*DefaultArg=*/nullptr)); 01606 } 01607 Block->setParams(BlockParams); 01608 01609 Block->setIsConversionFromLambda(true); 01610 01611 // Add capture. The capture uses a fake variable, which doesn't correspond 01612 // to any actual memory location. However, the initializer copy-initializes 01613 // the lambda object. 01614 TypeSourceInfo *CapVarTSI = 01615 Context.getTrivialTypeSourceInfo(Src->getType()); 01616 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 01617 ConvLocation, nullptr, 01618 Src->getType(), CapVarTSI, 01619 SC_None); 01620 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false, 01621 /*Nested=*/false, /*Copy=*/Init.get()); 01622 Block->setCaptures(Context, &Capture, &Capture + 1, 01623 /*CapturesCXXThis=*/false); 01624 01625 // Add a fake function body to the block. IR generation is responsible 01626 // for filling in the actual body, which cannot be expressed as an AST. 01627 Block->setBody(new (Context) CompoundStmt(ConvLocation)); 01628 01629 // Create the block literal expression. 01630 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 01631 ExprCleanupObjects.push_back(Block); 01632 ExprNeedsCleanups = true; 01633 01634 return BuildBlock; 01635 }