blob: a7d5b65264642390b766af972b32f8ed6d8772e1 [file] [log] [blame]
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ lambda expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/DeclSpec.h"
Faisal Valifad9e132013-09-26 19:54:12 +000014#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ExprCXX.h"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000016#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000018#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000020#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000021#include "clang/Sema/ScopeInfo.h"
22#include "clang/Sema/SemaInternal.h"
Faisal Valic00e4192013-11-07 05:17:06 +000023#include "clang/Sema/SemaLambda.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000024#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000025using namespace clang;
26using namespace sema;
27
Faisal Valic00e4192013-11-07 05:17:06 +000028// returns -1 if none of the lambdas on the scope stack can capture.
29// A lambda 'L' is capture-ready for a certain variable 'V' if,
30// - its enclosing context is non-dependent
31// - and if the chain of lambdas between L and the lambda in which
32// V is potentially used, call all capture or have captured V.
33static inline int GetScopeIndexOfNearestCaptureReadyLambda(
34 ArrayRef<clang::sema::FunctionScopeInfo*> FunctionScopes,
35 DeclContext *const CurContext, VarDecl *VD) {
36
37 DeclContext *EnclosingDC = CurContext;
38 // If VD is null, we are attempting to capture 'this'
39 const bool IsCapturingThis = !VD;
40 const bool IsCapturingVariable = !IsCapturingThis;
41 int RetIndex = -1;
42 unsigned CurScopeIndex = FunctionScopes.size() - 1;
43 while (!EnclosingDC->isTranslationUnit() &&
44 EnclosingDC->isDependentContext() && isLambdaCallOperator(EnclosingDC)) {
45 RetIndex = CurScopeIndex;
46 clang::sema::LambdaScopeInfo *LSI =
47 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
48 // We have crawled up to an intervening lambda that contains the
49 // variable declaration - so not only does it not need to capture;
50 // none of the enclosing lambdas need to capture it, and since all
51 // other nested lambdas are dependent (otherwise we wouldn't have
52 // arrived here) - we don't yet have a lambda that can capture the
53 // variable.
54 if (IsCapturingVariable && VD->getDeclContext()->Equals(EnclosingDC))
55 return -1;
56 // All intervening lambda call operators have to be able to capture.
57 // If they do not have a default implicit capture, check to see
58 // if the entity has already been explicitly captured.
59 // If even a single dependent enclosing lambda lacks the capability
60 // to ever capture this variable, there is no further enclosing
61 // non-dependent lambda that can capture this variable.
62 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
63 if (IsCapturingVariable && !LSI->isCaptured(VD))
64 return -1;
65 if (IsCapturingThis && !LSI->isCXXThisCaptured())
66 return -1;
67 }
68 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
69 --CurScopeIndex;
70 }
71 // If the enclosingDC is not dependent, then the immediately nested lambda
72 // is capture-ready.
73 if (!EnclosingDC->isDependentContext())
74 return RetIndex;
75 return -1;
76}
77// Given a lambda's call operator and a variable (or null for 'this'),
78// compute the nearest enclosing lambda that is capture-ready (i.e
79// the enclosing context is not dependent, and all intervening lambdas can
80// either implicitly or explicitly capture Var)
81//
82// The approach is as follows, for the entity VD ('this' if null):
83// - start with the current lambda
84// - if it is non-dependent and can capture VD, return it.
85// - if it is dependent and has an implicit or explicit capture, check its parent
86// whether the parent is non-depdendent and all its intervening lambdas
87// can capture, if so return the child.
88// [Note: When we hit a generic lambda specialization, do not climb up
89// the scope stack any further since not only do we not need to,
90// the scope stack will often not be synchronized with any lambdas
91// enclosing the specialized generic lambda]
92//
93// Return the CallOperator of the capturable lambda and set function scope
94// index to the correct index within the function scope stack to correspond
95// to the capturable lambda.
96// If VarDecl *VD is null, we check for 'this' capture.
97CXXMethodDecl* clang::GetInnermostEnclosingCapturableLambda(
98 ArrayRef<sema::FunctionScopeInfo*> FunctionScopes,
99 unsigned &FunctionScopeIndex,
100 DeclContext *const CurContext, VarDecl *VD,
101 Sema &S) {
102
103 const int IndexOfCaptureReadyLambda =
104 GetScopeIndexOfNearestCaptureReadyLambda(FunctionScopes,CurContext, VD);
105 if (IndexOfCaptureReadyLambda == -1) return 0;
106 assert(IndexOfCaptureReadyLambda >= 0);
107 const unsigned IndexOfCaptureReadyLambdaU =
108 static_cast<unsigned>(IndexOfCaptureReadyLambda);
109 sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
110 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambdaU]);
111 // If VD is null, we are attempting to capture 'this'
112 const bool IsCapturingThis = !VD;
113 const bool IsCapturingVariable = !IsCapturingThis;
114
115 if (IsCapturingVariable) {
116 // Now check to see if this lambda can truly capture, and also
117 // if all enclosing lambdas of this lambda allow this capture.
118 QualType CaptureType, DeclRefType;
119 const bool CanCaptureVariable = !S.tryCaptureVariable(VD,
120 /*ExprVarIsUsedInLoc*/SourceLocation(), clang::Sema::TryCapture_Implicit,
121 /*EllipsisLoc*/ SourceLocation(),
122 /*BuildAndDiagnose*/false, CaptureType, DeclRefType,
123 &IndexOfCaptureReadyLambdaU);
124 if (!CanCaptureVariable) return 0;
125 } else {
126 const bool CanCaptureThis = !S.CheckCXXThisCapture(
127 CaptureReadyLambdaLSI->PotentialThisCaptureLocation, false, false,
128 &IndexOfCaptureReadyLambdaU);
129 if (!CanCaptureThis) return 0;
130 } // end 'this' capture test
131 FunctionScopeIndex = IndexOfCaptureReadyLambdaU;
132 return CaptureReadyLambdaLSI->CallOperator;
133}
Faisal Valibef582b2013-10-23 16:10:50 +0000134
135static inline TemplateParameterList *
136getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
137 if (LSI->GLTemplateParameterList)
138 return LSI->GLTemplateParameterList;
139
140 if (LSI->AutoTemplateParams.size()) {
141 SourceRange IntroRange = LSI->IntroducerRange;
142 SourceLocation LAngleLoc = IntroRange.getBegin();
143 SourceLocation RAngleLoc = IntroRange.getEnd();
144 LSI->GLTemplateParameterList = TemplateParameterList::Create(
145 SemaRef.Context,
146 /*Template kw loc*/SourceLocation(),
147 LAngleLoc,
148 (NamedDecl**)LSI->AutoTemplateParams.data(),
149 LSI->AutoTemplateParams.size(), RAngleLoc);
150 }
151 return LSI->GLTemplateParameterList;
152}
153
154
155
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000156CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +0000157 TypeSourceInfo *Info,
Faisal Valibef582b2013-10-23 16:10:50 +0000158 bool KnownDependent,
159 LambdaCaptureDefault CaptureDefault) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000160 DeclContext *DC = CurContext;
161 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
162 DC = DC->getParent();
Faisal Valibef582b2013-10-23 16:10:50 +0000163 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
164 *this);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000165 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +0000166 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000167 IntroducerRange.getBegin(),
Faisal Valibef582b2013-10-23 16:10:50 +0000168 KnownDependent,
169 IsGenericLambda,
170 CaptureDefault);
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000171 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000172
173 return Class;
174}
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000175
Douglas Gregorf54486a2012-04-04 17:40:10 +0000176/// \brief Determine whether the given context is or is enclosed in an inline
177/// function.
178static bool isInInlineFunction(const DeclContext *DC) {
179 while (!DC->isFileContext()) {
180 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
181 if (FD->isInlined())
182 return true;
183
184 DC = DC->getLexicalParent();
185 }
186
187 return false;
188}
189
Eli Friedman07369dd2013-07-01 20:22:57 +0000190MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +0000191Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +0000192 Decl *&ManglingContextDecl) {
193 // Compute the context for allocating mangling numbers in the current
194 // expression, if the ABI requires them.
195 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
196
197 enum ContextKind {
198 Normal,
199 DefaultArgument,
200 DataMember,
201 StaticDataMember
202 } Kind = Normal;
203
204 // Default arguments of member function parameters that appear in a class
205 // definition, as well as the initializers of data members, receive special
206 // treatment. Identify them.
207 if (ManglingContextDecl) {
208 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
209 if (const DeclContext *LexicalDC
210 = Param->getDeclContext()->getLexicalParent())
211 if (LexicalDC->isRecord())
212 Kind = DefaultArgument;
213 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
214 if (Var->getDeclContext()->isRecord())
215 Kind = StaticDataMember;
216 } else if (isa<FieldDecl>(ManglingContextDecl)) {
217 Kind = DataMember;
218 }
219 }
220
221 // Itanium ABI [5.1.7]:
222 // In the following contexts [...] the one-definition rule requires closure
223 // types in different translation units to "correspond":
224 bool IsInNonspecializedTemplate =
225 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
226 switch (Kind) {
227 case Normal:
228 // -- the bodies of non-exported nonspecialized template functions
229 // -- the bodies of inline functions
230 if ((IsInNonspecializedTemplate &&
231 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
232 isInInlineFunction(CurContext)) {
233 ManglingContextDecl = 0;
234 return &Context.getManglingNumberContext(DC);
235 }
236
237 ManglingContextDecl = 0;
238 return 0;
239
240 case StaticDataMember:
241 // -- the initializers of nonspecialized static members of template classes
242 if (!IsInNonspecializedTemplate) {
243 ManglingContextDecl = 0;
244 return 0;
245 }
246 // Fall through to get the current context.
247
248 case DataMember:
249 // -- the in-class initializers of class members
250 case DefaultArgument:
251 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000252 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000253 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000254
255 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000256}
257
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000258MangleNumberingContext &
259Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
260 ASTContext &Ctx) {
261 assert(ManglingContextDecl && "Need to have a context declaration");
262 if (!MangleNumbering)
263 MangleNumbering = Ctx.createMangleNumberingContext();
264 return *MangleNumbering;
265}
266
Douglas Gregordfca6f52012-02-13 22:00:16 +0000267CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith41d09582013-09-25 05:02:54 +0000268 SourceRange IntroducerRange,
269 TypeSourceInfo *MethodTypeInfo,
270 SourceLocation EndLoc,
271 ArrayRef<ParmVarDecl *> Params) {
272 QualType MethodType = MethodTypeInfo->getType();
Faisal Valifad9e132013-09-26 19:54:12 +0000273 TemplateParameterList *TemplateParams =
274 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
275 // If a lambda appears in a dependent context or is a generic lambda (has
276 // template parameters) and has an 'auto' return type, deduce it to a
277 // dependent type.
278 if (Class->isDependentContext() || TemplateParams) {
Richard Smith41d09582013-09-25 05:02:54 +0000279 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
280 QualType Result = FPT->getResultType();
281 if (Result->isUndeducedType()) {
282 Result = SubstAutoType(Result, Context.DependentTy);
283 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
284 FPT->getExtProtoInfo());
285 }
286 }
287
Douglas Gregordfca6f52012-02-13 22:00:16 +0000288 // C++11 [expr.prim.lambda]p5:
289 // The closure type for a lambda-expression has a public inline function
290 // call operator (13.5.4) whose parameters and return type are described by
291 // the lambda-expression's parameter-declaration-clause and
292 // trailing-return-type respectively.
293 DeclarationName MethodName
294 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
295 DeclarationNameLoc MethodNameLoc;
296 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
297 = IntroducerRange.getBegin().getRawEncoding();
298 MethodNameLoc.CXXOperatorName.EndOpNameLoc
299 = IntroducerRange.getEnd().getRawEncoding();
300 CXXMethodDecl *Method
301 = CXXMethodDecl::Create(Context, Class, EndLoc,
302 DeclarationNameInfo(MethodName,
303 IntroducerRange.getBegin(),
304 MethodNameLoc),
Richard Smith41d09582013-09-25 05:02:54 +0000305 MethodType, MethodTypeInfo,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000306 SC_None,
307 /*isInline=*/true,
308 /*isConstExpr=*/false,
309 EndLoc);
310 Method->setAccess(AS_public);
311
312 // Temporarily set the lexical declaration context to the current
313 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000314 Method->setLexicalDeclContext(CurContext);
Faisal Valifad9e132013-09-26 19:54:12 +0000315 // Create a function template if we have a template parameter list
316 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
317 FunctionTemplateDecl::Create(Context, Class,
318 Method->getLocation(), MethodName,
319 TemplateParams,
320 Method) : 0;
321 if (TemplateMethod) {
322 TemplateMethod->setLexicalDeclContext(CurContext);
323 TemplateMethod->setAccess(AS_public);
324 Method->setDescribedFunctionTemplate(TemplateMethod);
325 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000326
Douglas Gregorc6889e72012-02-14 22:28:59 +0000327 // Add parameters.
328 if (!Params.empty()) {
329 Method->setParams(Params);
330 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
331 const_cast<ParmVarDecl **>(Params.end()),
332 /*CheckParameterNames=*/false);
333
334 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
335 PEnd = Method->param_end();
336 P != PEnd; ++P)
337 (*P)->setOwningFunction(Method);
338 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000339
Eli Friedman07369dd2013-07-01 20:22:57 +0000340 Decl *ManglingContextDecl;
341 if (MangleNumberingContext *MCtx =
342 getCurrentMangleNumberContext(Class->getDeclContext(),
343 ManglingContextDecl)) {
344 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
345 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000346 }
347
Douglas Gregordfca6f52012-02-13 22:00:16 +0000348 return Method;
349}
350
Faisal Valifad9e132013-09-26 19:54:12 +0000351void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
352 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000353 SourceRange IntroducerRange,
354 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000355 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000356 bool ExplicitParams,
357 bool ExplicitResultType,
358 bool Mutable) {
Faisal Valifad9e132013-09-26 19:54:12 +0000359 LSI->CallOperator = CallOperator;
Faisal Valibef582b2013-10-23 16:10:50 +0000360 CXXRecordDecl *LambdaClass = CallOperator->getParent();
361 LSI->Lambda = LambdaClass;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000362 if (CaptureDefault == LCD_ByCopy)
363 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
364 else if (CaptureDefault == LCD_ByRef)
365 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000366 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000367 LSI->IntroducerRange = IntroducerRange;
368 LSI->ExplicitParams = ExplicitParams;
369 LSI->Mutable = Mutable;
370
371 if (ExplicitResultType) {
372 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000373
374 if (!LSI->ReturnType->isDependentType() &&
375 !LSI->ReturnType->isVoidType()) {
376 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
377 diag::err_lambda_incomplete_result)) {
378 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000379 }
380 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000381 } else {
382 LSI->HasImplicitReturnType = true;
383 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000384}
385
386void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
387 LSI->finishedExplicitCaptures();
388}
389
Douglas Gregorc6889e72012-02-14 22:28:59 +0000390void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000391 // Introduce our parameters into the function scope
392 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
393 p < NumParams; ++p) {
394 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000395
396 // If this has an identifier, add it to the scope stack.
397 if (CurScope && Param->getIdentifier()) {
398 CheckShadow(CurScope, Param);
399
400 PushOnScopeChains(Param, CurScope);
401 }
402 }
403}
404
John McCall41d01642013-03-09 00:54:31 +0000405/// If this expression is an enumerator-like expression of some type
406/// T, return the type T; otherwise, return null.
407///
408/// Pointer comparisons on the result here should always work because
409/// it's derived from either the parent of an EnumConstantDecl
410/// (i.e. the definition) or the declaration returned by
411/// EnumType::getDecl() (i.e. the definition).
412static EnumDecl *findEnumForBlockReturn(Expr *E) {
413 // An expression is an enumerator-like expression of type T if,
414 // ignoring parens and parens-like expressions:
415 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000416
John McCall41d01642013-03-09 00:54:31 +0000417 // - it is an enumerator whose enum type is T or
418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
419 if (EnumConstantDecl *D
420 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
421 return cast<EnumDecl>(D->getDeclContext());
422 }
423 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000424 }
425
John McCall41d01642013-03-09 00:54:31 +0000426 // - it is a comma expression whose RHS is an enumerator-like
427 // expression of type T or
428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
429 if (BO->getOpcode() == BO_Comma)
430 return findEnumForBlockReturn(BO->getRHS());
431 return 0;
432 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000433
John McCall41d01642013-03-09 00:54:31 +0000434 // - it is a statement-expression whose value expression is an
435 // enumerator-like expression of type T or
436 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
437 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
438 return findEnumForBlockReturn(last);
439 return 0;
440 }
441
442 // - it is a ternary conditional operator (not the GNU ?:
443 // extension) whose second and third operands are
444 // enumerator-like expressions of type T or
445 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
446 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
447 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
448 return ED;
449 return 0;
450 }
451
452 // (implicitly:)
453 // - it is an implicit integral conversion applied to an
454 // enumerator-like expression of type T or
455 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000456 // We can sometimes see integral conversions in valid
457 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000458 if (ICE->getCastKind() == CK_IntegralCast)
459 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000460
461 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000462 }
463
464 // - it is an expression of that formal enum type.
465 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
466 return ET->getDecl();
467 }
468
469 // Otherwise, nope.
470 return 0;
471}
472
473/// Attempt to find a type T for which the returned expression of the
474/// given statement is an enumerator-like expression of that type.
475static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
476 if (Expr *retValue = ret->getRetValue())
477 return findEnumForBlockReturn(retValue);
478 return 0;
479}
480
481/// Attempt to find a common type T for which all of the returned
482/// expressions in a block are enumerator-like expressions of that
483/// type.
484static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
485 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
486
487 // Try to find one for the first return.
488 EnumDecl *ED = findEnumForBlockReturn(*i);
489 if (!ED) return 0;
490
491 // Check that the rest of the returns have the same enum.
492 for (++i; i != e; ++i) {
493 if (findEnumForBlockReturn(*i) != ED)
494 return 0;
495 }
496
497 // Never infer an anonymous enum type.
498 if (!ED->hasNameForLinkage()) return 0;
499
500 return ED;
501}
502
503/// Adjust the given return statements so that they formally return
504/// the given type. It should require, at most, an IntegralCast.
505static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
506 QualType returnType) {
507 for (ArrayRef<ReturnStmt*>::iterator
508 i = returns.begin(), e = returns.end(); i != e; ++i) {
509 ReturnStmt *ret = *i;
510 Expr *retValue = ret->getRetValue();
511 if (S.Context.hasSameType(retValue->getType(), returnType))
512 continue;
513
514 // Right now we only support integral fixup casts.
515 assert(returnType->isIntegralOrUnscopedEnumerationType());
516 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
517
518 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
519
520 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
521 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
522 E, /*base path*/ 0, VK_RValue);
523 if (cleanups) {
524 cleanups->setSubExpr(E);
525 } else {
526 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000527 }
528 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000529}
530
531void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000532 assert(CSI.HasImplicitReturnType);
Faisal Valifad9e132013-09-26 19:54:12 +0000533 // If it was ever a placeholder, it had to been deduced to DependentTy.
534 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000535
John McCall41d01642013-03-09 00:54:31 +0000536 // C++ Core Issue #975, proposed resolution:
537 // If a lambda-expression does not include a trailing-return-type,
538 // it is as if the trailing-return-type denotes the following type:
539 // - if there are no return statements in the compound-statement,
540 // or all return statements return either an expression of type
541 // void or no expression or braced-init-list, the type void;
542 // - otherwise, if all return statements return an expression
543 // and the types of the returned expressions after
544 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
545 // array-to-pointer conversion (4.2 [conv.array]), and
546 // function-to-pointer conversion (4.3 [conv.func]) are the
547 // same, that common type;
548 // - otherwise, the program is ill-formed.
549 //
550 // In addition, in blocks in non-C++ modes, if all of the return
551 // statements are enumerator-like expressions of some type T, where
552 // T has a name for linkage, then we infer the return type of the
553 // block to be that type.
554
Jordan Rose7dd900e2012-07-02 21:19:23 +0000555 // First case: no return statements, implicit void return type.
556 ASTContext &Ctx = getASTContext();
557 if (CSI.Returns.empty()) {
558 // It's possible there were simply no /valid/ return statements.
559 // In this case, the first one we found may have at least given us a type.
560 if (CSI.ReturnType.isNull())
561 CSI.ReturnType = Ctx.VoidTy;
562 return;
563 }
564
565 // Second case: at least one return statement has dependent type.
566 // Delay type checking until instantiation.
567 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000568 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000569 return;
570
John McCall41d01642013-03-09 00:54:31 +0000571 // Try to apply the enum-fuzz rule.
572 if (!getLangOpts().CPlusPlus) {
573 assert(isa<BlockScopeInfo>(CSI));
574 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
575 if (ED) {
576 CSI.ReturnType = Context.getTypeDeclType(ED);
577 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
578 return;
579 }
580 }
581
Jordan Rose7dd900e2012-07-02 21:19:23 +0000582 // Third case: only one return statement. Don't bother doing extra work!
583 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
584 E = CSI.Returns.end();
585 if (I+1 == E)
586 return;
587
588 // General case: many return statements.
589 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000590
591 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000592 // Note that we've already done the required promotions as part of
593 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000594 for (; I != E; ++I) {
595 const ReturnStmt *RS = *I;
596 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000597
John McCall41d01642013-03-09 00:54:31 +0000598 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
599 if (Context.hasSameType(ReturnType, CSI.ReturnType))
600 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000601
John McCall41d01642013-03-09 00:54:31 +0000602 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
603 // TODO: It's possible that the *first* return is the divergent one.
604 Diag(RS->getLocStart(),
605 diag::err_typecheck_missing_return_type_incompatible)
606 << ReturnType << CSI.ReturnType
607 << isa<LambdaScopeInfo>(CSI);
608 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000609 }
610}
611
Bill Wendling2434dcf2013-12-05 05:25:04 +0000612QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
613 bool ByRef,
614 IdentifierInfo *Id,
615 Expr *&Init) {
616
617 // We do not need to distinguish between direct-list-initialization
618 // and copy-list-initialization here, because we will always deduce
619 // std::initializer_list<T>, and direct- and copy-list-initialization
620 // always behave the same for such a type.
621 // FIXME: We should model whether an '=' was present.
622 const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
623
624 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
625 // deduce against.
Richard Smith0d8e9642013-05-16 06:20:58 +0000626 QualType DeductType = Context.getAutoDeductType();
627 TypeLocBuilder TLB;
628 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
629 if (ByRef) {
630 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
631 assert(!DeductType.isNull() && "can't build reference to auto");
632 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
633 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000634 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000635
Bill Wendling2434dcf2013-12-05 05:25:04 +0000636 // Are we a non-list direct initialization?
637 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
638
639 Expr *DeduceInit = Init;
640 // Initializer could be a C++ direct-initializer. Deduction only works if it
641 // contains exactly one expression.
642 if (CXXDirectInit) {
643 if (CXXDirectInit->getNumExprs() == 0) {
644 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
645 << DeclarationName(Id) << TSI->getType() << Loc;
646 return QualType();
647 } else if (CXXDirectInit->getNumExprs() > 1) {
648 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
649 diag::err_init_capture_multiple_expressions)
650 << DeclarationName(Id) << TSI->getType() << Loc;
651 return QualType();
652 } else {
653 DeduceInit = CXXDirectInit->getExpr(0);
654 }
655 }
656
657 // Now deduce against the initialization expression and store the deduced
658 // type below.
659 QualType DeducedType;
660 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
661 if (isa<InitListExpr>(Init))
662 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
663 << DeclarationName(Id)
664 << (DeduceInit->getType().isNull() ? TSI->getType()
665 : DeduceInit->getType())
666 << DeduceInit->getSourceRange();
667 else
668 Diag(Loc, diag::err_init_capture_deduction_failure)
669 << DeclarationName(Id) << TSI->getType()
670 << (DeduceInit->getType().isNull() ? TSI->getType()
671 : DeduceInit->getType())
672 << DeduceInit->getSourceRange();
673 }
674 if (DeducedType.isNull())
675 return QualType();
676
677 // Perform initialization analysis and ensure any implicit conversions
678 // (such as lvalue-to-rvalue) are enforced.
679 InitializedEntity Entity =
680 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
681 InitializationKind Kind =
682 IsDirectInit
683 ? (CXXDirectInit ? InitializationKind::CreateDirect(
684 Loc, Init->getLocStart(), Init->getLocEnd())
685 : InitializationKind::CreateDirectList(Loc))
686 : InitializationKind::CreateCopy(Loc, Init->getLocStart());
687
688 MultiExprArg Args = Init;
689 if (CXXDirectInit)
690 Args =
691 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
692 QualType DclT;
693 InitializationSequence InitSeq(*this, Entity, Kind, Args);
694 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
695
696 if (Result.isInvalid())
697 return QualType();
698 Init = Result.takeAs<Expr>();
699
700 // The init-capture initialization is a full-expression that must be
701 // processed as one before we enter the declcontext of the lambda's
702 // call-operator.
703 Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
704 /*IsConstexpr*/ false,
705 /*IsLambdaInitCaptureInitalizer*/ true);
706 if (Result.isInvalid())
707 return QualType();
708
709 Init = Result.takeAs<Expr>();
710 return DeducedType;
711}
712
713VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
714 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
715
716 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
717 Loc);
Richard Smith04fa7a32013-09-28 04:02:39 +0000718 // Create a dummy variable representing the init-capture. This is not actually
719 // used as a variable, and only exists as a way to name and refer to the
720 // init-capture.
721 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith39edfeb2013-09-28 04:31:26 +0000722 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Bill Wendling2434dcf2013-12-05 05:25:04 +0000723 Loc, Id, InitCaptureType, TSI, SC_Auto);
Richard Smith04fa7a32013-09-28 04:02:39 +0000724 NewVD->setInitCapture(true);
725 NewVD->setReferenced(true);
726 NewVD->markUsed(Context);
Bill Wendling2434dcf2013-12-05 05:25:04 +0000727 NewVD->setInit(Init);
Richard Smith04fa7a32013-09-28 04:02:39 +0000728 return NewVD;
Bill Wendling2434dcf2013-12-05 05:25:04 +0000729
Richard Smith04fa7a32013-09-28 04:02:39 +0000730}
Richard Smith0d8e9642013-05-16 06:20:58 +0000731
Richard Smith04fa7a32013-09-28 04:02:39 +0000732FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
733 FieldDecl *Field = FieldDecl::Create(
734 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
735 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
736 Field->setImplicit(true);
737 Field->setAccess(AS_private);
738 LSI->Lambda->addDecl(Field);
Richard Smith0d8e9642013-05-16 06:20:58 +0000739
Richard Smith04fa7a32013-09-28 04:02:39 +0000740 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
741 /*isNested*/false, Var->getLocation(), SourceLocation(),
742 Var->getType(), Var->getInit());
743 return Field;
Richard Smith0d8e9642013-05-16 06:20:58 +0000744}
745
Douglas Gregordfca6f52012-02-13 22:00:16 +0000746void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valifad9e132013-09-26 19:54:12 +0000747 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000748 // Determine if we're within a context where we know that the lambda will
749 // be dependent, because there are template parameters in scope.
750 bool KnownDependent = false;
Faisal Valifad9e132013-09-26 19:54:12 +0000751 LambdaScopeInfo *const LSI = getCurLambda();
752 assert(LSI && "LambdaScopeInfo should be on stack!");
753 TemplateParameterList *TemplateParams =
754 getGenericLambdaTemplateParameterList(LSI, *this);
755
756 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
757 // Since we have our own TemplateParams, so check if an outer scope
758 // has template params, only then are we in a dependent scope.
759 if (TemplateParams) {
760 TmplScope = TmplScope->getParent();
761 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
762 }
763 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000764 KnownDependent = true;
Faisal Valifad9e132013-09-26 19:54:12 +0000765 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000766 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000767 TypeSourceInfo *MethodTyInfo;
768 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000769 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000770 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000771 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000772 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773 if (ParamInfo.getNumTypeObjects() == 0) {
774 // C++11 [expr.prim.lambda]p4:
775 // If a lambda-expression does not include a lambda-declarator, it is as
776 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000777 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
778 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000779 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000780 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000781 // C++1y [expr.prim.lambda]:
782 // The lambda return type is 'auto', which is replaced by the
783 // trailing-return type if provided and/or deduced from 'return'
784 // statements
785 // We don't do this before C++1y, because we don't support deduced return
786 // types there.
787 QualType DefaultTypeForNoTrailingReturn =
788 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
789 : Context.DependentTy;
790 QualType MethodTy =
791 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000792 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
793 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000794 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000795 EndLoc = Intro.Range.getEnd();
796 } else {
797 assert(ParamInfo.isFunctionDeclarator() &&
798 "lambda-declarator is a function");
799 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000800
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000801 // C++11 [expr.prim.lambda]p5:
802 // This function call operator is declared const (9.3.1) if and only if
803 // the lambda-expression's parameter-declaration-clause is not followed
804 // by mutable. It is neither virtual nor declared volatile. [...]
805 if (!FTI.hasMutableQualifier())
806 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000807
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000808 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000809 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000810 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000811
812 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000813
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000814 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
815 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
816 // Empty arg list, don't push any params.
817 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
818 } else {
819 Params.reserve(FTI.NumArgs);
820 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
821 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
822 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000823
824 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000825 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
826 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000827 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000828
829 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valibef582b2013-10-23 16:10:50 +0000830 KnownDependent, Intro.Default);
Eli Friedman8da8a662012-09-19 01:18:11 +0000831
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000832 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000833 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000834 if (ExplicitParams)
835 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000836
Bill Wendlingad017fa2012-12-20 19:22:21 +0000837 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000838 ProcessDeclAttributes(CurScope, Method, ParamInfo);
839
Douglas Gregor503384f2012-02-09 00:47:04 +0000840 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000841 PushDeclContext(CurScope, Method);
842
Faisal Valifad9e132013-09-26 19:54:12 +0000843 // Build the lambda scope.
844 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000845 Intro.Range,
846 Intro.Default, Intro.DefaultLoc,
847 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000848 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000849 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000850
851 // Distinct capture names, for diagnostics.
852 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
853
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000854 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000855 SourceLocation PrevCaptureLoc
856 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000857 for (SmallVectorImpl<LambdaCapture>::const_iterator
858 C = Intro.Captures.begin(),
859 E = Intro.Captures.end();
860 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000861 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000862 if (C->Kind == LCK_This) {
863 // C++11 [expr.prim.lambda]p8:
864 // An identifier or this shall not appear more than once in a
865 // lambda-capture.
866 if (LSI->isCXXThisCaptured()) {
867 Diag(C->Loc, diag::err_capture_more_than_once)
868 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000869 << SourceRange(LSI->getCXXThisCapture().getLocation())
870 << FixItHint::CreateRemoval(
871 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000872 continue;
873 }
874
875 // C++11 [expr.prim.lambda]p8:
876 // If a lambda-capture includes a capture-default that is =, the
877 // lambda-capture shall not contain this [...].
878 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000879 Diag(C->Loc, diag::err_this_capture_with_copy_default)
880 << FixItHint::CreateRemoval(
881 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000882 continue;
883 }
884
885 // C++11 [expr.prim.lambda]p12:
886 // If this is captured by a local lambda expression, its nearest
887 // enclosing function shall be a non-static member function.
888 QualType ThisCaptureType = getCurrentThisType();
889 if (ThisCaptureType.isNull()) {
890 Diag(C->Loc, diag::err_this_capture) << true;
891 continue;
892 }
893
894 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
895 continue;
896 }
897
Richard Smith0d8e9642013-05-16 06:20:58 +0000898 assert(C->Id && "missing identifier for capture");
899
Richard Smith0a664b82013-05-09 21:36:41 +0000900 if (C->Init.isInvalid())
901 continue;
Richard Smith0d8e9642013-05-16 06:20:58 +0000902
Bill Wendling2434dcf2013-12-05 05:25:04 +0000903 VarDecl *Var = 0;
Richard Smith04fa7a32013-09-28 04:02:39 +0000904 if (C->Init.isUsable()) {
Richard Smith9beaf202013-09-28 05:38:27 +0000905 Diag(C->Loc, getLangOpts().CPlusPlus1y
906 ? diag::warn_cxx11_compat_init_capture
907 : diag::ext_init_capture);
908
Richard Smith0d8e9642013-05-16 06:20:58 +0000909 if (C->Init.get()->containsUnexpandedParameterPack())
910 ContainsUnexpandedParameterPack = true;
Bill Wendling2434dcf2013-12-05 05:25:04 +0000911 // If the initializer expression is usable, but the InitCaptureType
912 // is not, then an error has occurred - so ignore the capture for now.
913 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
914 // FIXME: we should create the init capture variable and mark it invalid
915 // in this case.
916 if (C->InitCaptureType.get().isNull())
917 continue;
918 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
919 C->Id, C->Init.take());
Richard Smith0d8e9642013-05-16 06:20:58 +0000920 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000921 // An init-capture behaves as if it declares and explicitly
922 // captures a variable [...] whose declarative region is the
923 // lambda-expression's compound-statement
924 if (Var)
925 PushOnScopeChains(Var, CurScope, false);
926 } else {
927 // C++11 [expr.prim.lambda]p8:
928 // If a lambda-capture includes a capture-default that is &, the
929 // identifiers in the lambda-capture shall not be preceded by &.
930 // If a lambda-capture includes a capture-default that is =, [...]
931 // each identifier it contains shall be preceded by &.
932 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
933 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
934 << FixItHint::CreateRemoval(
935 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000936 continue;
Richard Smith04fa7a32013-09-28 04:02:39 +0000937 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
938 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
939 << FixItHint::CreateRemoval(
940 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
941 continue;
942 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000943
Richard Smith04fa7a32013-09-28 04:02:39 +0000944 // C++11 [expr.prim.lambda]p10:
945 // The identifiers in a capture-list are looked up using the usual
946 // rules for unqualified name lookup (3.4.1)
947 DeclarationNameInfo Name(C->Id, C->Loc);
948 LookupResult R(*this, Name, LookupOrdinaryName);
949 LookupName(R, CurScope);
950 if (R.isAmbiguous())
951 continue;
952 if (R.empty()) {
953 // FIXME: Disable corrections that would add qualification?
954 CXXScopeSpec ScopeSpec;
955 DeclFilterCCC<VarDecl> Validator;
956 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
957 continue;
958 }
959
960 Var = R.getAsSingle<VarDecl>();
961 }
Richard Smith0d8e9642013-05-16 06:20:58 +0000962
963 // C++11 [expr.prim.lambda]p8:
964 // An identifier or this shall not appear more than once in a
965 // lambda-capture.
966 if (!CaptureNames.insert(C->Id)) {
967 if (Var && LSI->isCaptured(Var)) {
968 Diag(C->Loc, diag::err_capture_more_than_once)
969 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
970 << FixItHint::CreateRemoval(
971 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
972 } else
Richard Smith04fa7a32013-09-28 04:02:39 +0000973 // Previous capture captured something different (one or both was
974 // an init-cpature): no fixit.
Richard Smith0d8e9642013-05-16 06:20:58 +0000975 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
976 continue;
977 }
978
979 // C++11 [expr.prim.lambda]p10:
980 // [...] each such lookup shall find a variable with automatic storage
981 // duration declared in the reaching scope of the local lambda expression.
982 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000983 if (!Var) {
984 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
985 continue;
986 }
987
Eli Friedman9cd5b242012-09-18 21:11:30 +0000988 // Ignore invalid decls; they'll just confuse the code later.
989 if (Var->isInvalidDecl())
990 continue;
991
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000992 if (!Var->hasLocalStorage()) {
993 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
994 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
995 continue;
996 }
997
Douglas Gregora7365242012-02-14 19:27:52 +0000998 // C++11 [expr.prim.lambda]p23:
999 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1000 SourceLocation EllipsisLoc;
1001 if (C->EllipsisLoc.isValid()) {
1002 if (Var->isParameterPack()) {
1003 EllipsisLoc = C->EllipsisLoc;
1004 } else {
1005 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1006 << SourceRange(C->Loc);
1007
1008 // Just ignore the ellipsis.
1009 }
1010 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +00001011 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +00001012 }
Richard Smith04fa7a32013-09-28 04:02:39 +00001013
1014 if (C->Init.isUsable()) {
1015 buildInitCaptureField(LSI, Var);
1016 } else {
1017 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1018 TryCapture_ExplicitByVal;
1019 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1020 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001021 }
Douglas Gregordfca6f52012-02-13 22:00:16 +00001022 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001023
Richard Smith612409e2012-07-25 03:56:55 +00001024 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1025
Douglas Gregorc6889e72012-02-14 22:28:59 +00001026 // Add lambda parameters into scope.
1027 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001028
Douglas Gregordfca6f52012-02-13 22:00:16 +00001029 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +00001030 // cleanups from the enclosing full-expression.
1031 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001032}
1033
Douglas Gregordfca6f52012-02-13 22:00:16 +00001034void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1035 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001036 // Leave the expression-evaluation context.
1037 DiscardCleanupsInEvaluationContext();
1038 PopExpressionEvaluationContext();
1039
1040 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +00001041 if (!IsInstantiation)
1042 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +00001043
1044 // Finalize the lambda.
1045 LambdaScopeInfo *LSI = getCurLambda();
1046 CXXRecordDecl *Class = LSI->Lambda;
1047 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +00001048 SmallVector<Decl*, 4> Fields;
1049 for (RecordDecl::field_iterator i = Class->field_begin(),
1050 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001051 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +00001052 ActOnFields(0, Class->getLocation(), Class, Fields,
1053 SourceLocation(), SourceLocation(), 0);
1054 CheckCompletedCXXClass(Class);
1055
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001056 PopFunctionScopeInfo();
1057}
1058
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001059/// \brief Add a lambda's conversion to function pointer, as described in
1060/// C++11 [expr.prim.lambda]p6.
1061static void addFunctionPointerConversion(Sema &S,
1062 SourceRange IntroducerRange,
1063 CXXRecordDecl *Class,
1064 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001065 // Add the conversion to function pointer.
Faisal Vali605f91f2013-10-24 01:05:22 +00001066 const FunctionProtoType *CallOpProto =
1067 CallOperator->getType()->getAs<FunctionProtoType>();
1068 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1069 CallOpProto->getExtProtoInfo();
1070 QualType PtrToFunctionTy;
1071 QualType InvokerFunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001072 {
Faisal Vali605f91f2013-10-24 01:05:22 +00001073 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
Reid Kleckneref072032013-08-27 23:08:25 +00001074 CallingConv CC = S.Context.getDefaultCallingConvention(
Faisal Vali605f91f2013-10-24 01:05:22 +00001075 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1076 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1077 InvokerExtInfo.TypeQuals = 0;
1078 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1079 "Lambda's call operator should not have a reference qualifier");
1080 InvokerFunctionTy = S.Context.getFunctionType(CallOpProto->getResultType(),
1081 CallOpProto->getArgTypes(), InvokerExtInfo);
1082 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001083 }
Reid Kleckneref072032013-08-27 23:08:25 +00001084
Faisal Vali605f91f2013-10-24 01:05:22 +00001085 // Create the type of the conversion function.
1086 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1087 S.Context.getDefaultCallingConvention(
Reid Kleckneref072032013-08-27 23:08:25 +00001088 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Faisal Vali605f91f2013-10-24 01:05:22 +00001089 // The conversion function is always const.
1090 ConvExtInfo.TypeQuals = Qualifiers::Const;
1091 QualType ConvTy =
1092 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
Reid Kleckneref072032013-08-27 23:08:25 +00001093
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001094 SourceLocation Loc = IntroducerRange.getBegin();
Faisal Vali605f91f2013-10-24 01:05:22 +00001095 DeclarationName ConversionName
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001096 = S.Context.DeclarationNames.getCXXConversionFunctionName(
Faisal Vali605f91f2013-10-24 01:05:22 +00001097 S.Context.getCanonicalType(PtrToFunctionTy));
1098 DeclarationNameLoc ConvNameLoc;
1099 // Construct a TypeSourceInfo for the conversion function, and wire
1100 // all the parameters appropriately for the FunctionProtoTypeLoc
1101 // so that everything works during transformation/instantiation of
1102 // generic lambdas.
1103 // The main reason for wiring up the parameters of the conversion
1104 // function with that of the call operator is so that constructs
1105 // like the following work:
1106 // auto L = [](auto b) { <-- 1
1107 // return [](auto a) -> decltype(a) { <-- 2
1108 // return a;
1109 // };
1110 // };
1111 // int (*fp)(int) = L(5);
1112 // Because the trailing return type can contain DeclRefExprs that refer
1113 // to the original call operator's variables, we hijack the call
1114 // operators ParmVarDecls below.
1115 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1116 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1117 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1118
1119 // The conversion function is a conversion to a pointer-to-function.
1120 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1121 FunctionProtoTypeLoc ConvTL =
1122 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1123 // Get the result of the conversion function which is a pointer-to-function.
1124 PointerTypeLoc PtrToFunctionTL =
1125 ConvTL.getResultLoc().getAs<PointerTypeLoc>();
1126 // Do the same for the TypeSourceInfo that is used to name the conversion
1127 // operator.
1128 PointerTypeLoc ConvNamePtrToFunctionTL =
1129 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1130
1131 // Get the underlying function types that the conversion function will
1132 // be converting to (should match the type of the call operator).
1133 FunctionProtoTypeLoc CallOpConvTL =
1134 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1135 FunctionProtoTypeLoc CallOpConvNameTL =
1136 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1137
1138 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1139 // These parameter's are essentially used to transform the name and
1140 // the type of the conversion operator. By using the same parameters
1141 // as the call operator's we don't have to fix any back references that
1142 // the trailing return type of the call operator's uses (such as
1143 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1144 // - we can simply use the return type of the call operator, and
1145 // everything should work.
1146 SmallVector<ParmVarDecl *, 4> InvokerParams;
1147 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1148 ParmVarDecl *From = CallOperator->getParamDecl(I);
1149
1150 InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1151 // Temporarily add to the TU. This is set to the invoker below.
1152 S.Context.getTranslationUnitDecl(),
1153 From->getLocStart(),
1154 From->getLocation(),
1155 From->getIdentifier(),
1156 From->getType(),
1157 From->getTypeSourceInfo(),
1158 From->getStorageClass(),
1159 /*DefaultArg=*/0));
1160 CallOpConvTL.setArg(I, From);
1161 CallOpConvNameTL.setArg(I, From);
1162 }
1163
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001164 CXXConversionDecl *Conversion
1165 = CXXConversionDecl::Create(S.Context, Class, Loc,
Faisal Vali605f91f2013-10-24 01:05:22 +00001166 DeclarationNameInfo(ConversionName,
1167 Loc, ConvNameLoc),
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001168 ConvTy,
Faisal Vali605f91f2013-10-24 01:05:22 +00001169 ConvTSI,
Eli Friedman38fa9612013-06-13 19:39:48 +00001170 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001171 /*isConstexpr=*/false,
1172 CallOperator->getBody()->getLocEnd());
1173 Conversion->setAccess(AS_public);
1174 Conversion->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +00001175
1176 if (Class->isGenericLambda()) {
1177 // Create a template version of the conversion operator, using the template
1178 // parameter list of the function call operator.
1179 FunctionTemplateDecl *TemplateCallOperator =
1180 CallOperator->getDescribedFunctionTemplate();
1181 FunctionTemplateDecl *ConversionTemplate =
1182 FunctionTemplateDecl::Create(S.Context, Class,
Faisal Vali605f91f2013-10-24 01:05:22 +00001183 Loc, ConversionName,
Faisal Valid6992ab2013-09-29 08:45:24 +00001184 TemplateCallOperator->getTemplateParameters(),
1185 Conversion);
1186 ConversionTemplate->setAccess(AS_public);
1187 ConversionTemplate->setImplicit(true);
1188 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1189 Class->addDecl(ConversionTemplate);
1190 } else
1191 Class->addDecl(Conversion);
Faisal Valifad9e132013-09-26 19:54:12 +00001192 // Add a non-static member function that will be the result of
1193 // the conversion with a certain unique ID.
Faisal Vali605f91f2013-10-24 01:05:22 +00001194 DeclarationName InvokerName = &S.Context.Idents.get(
1195 getLambdaStaticInvokerName());
Faisal Valid6992ab2013-09-29 08:45:24 +00001196 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1197 // we should get a prebuilt TrivialTypeSourceInfo from Context
1198 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1199 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1200 // loop below and then use its Params to set Invoke->setParams(...) below.
1201 // This would avoid the 'const' qualifier of the calloperator from
1202 // contaminating the type of the invoker, which is currently adjusted
Faisal Vali605f91f2013-10-24 01:05:22 +00001203 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1204 // trailing return type of the invoker would require a visitor to rebuild
1205 // the trailing return type and adjusting all back DeclRefExpr's to refer
1206 // to the new static invoker parameters - not the call operator's.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001207 CXXMethodDecl *Invoke
1208 = CXXMethodDecl::Create(S.Context, Class, Loc,
Faisal Vali605f91f2013-10-24 01:05:22 +00001209 DeclarationNameInfo(InvokerName, Loc),
1210 InvokerFunctionTy,
1211 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001212 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001213 /*IsConstexpr=*/false,
1214 CallOperator->getBody()->getLocEnd());
Faisal Vali605f91f2013-10-24 01:05:22 +00001215 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1216 InvokerParams[I]->setOwningFunction(Invoke);
1217 Invoke->setParams(InvokerParams);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001218 Invoke->setAccess(AS_private);
1219 Invoke->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +00001220 if (Class->isGenericLambda()) {
1221 FunctionTemplateDecl *TemplateCallOperator =
1222 CallOperator->getDescribedFunctionTemplate();
1223 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
Faisal Vali605f91f2013-10-24 01:05:22 +00001224 S.Context, Class, Loc, InvokerName,
Faisal Valid6992ab2013-09-29 08:45:24 +00001225 TemplateCallOperator->getTemplateParameters(),
1226 Invoke);
1227 StaticInvokerTemplate->setAccess(AS_private);
1228 StaticInvokerTemplate->setImplicit(true);
1229 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1230 Class->addDecl(StaticInvokerTemplate);
1231 } else
1232 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001233}
1234
Douglas Gregorc2956e52012-02-15 22:08:38 +00001235/// \brief Add a lambda's conversion to block pointer.
1236static void addBlockPointerConversion(Sema &S,
1237 SourceRange IntroducerRange,
1238 CXXRecordDecl *Class,
1239 CXXMethodDecl *CallOperator) {
1240 const FunctionProtoType *Proto
1241 = CallOperator->getType()->getAs<FunctionProtoType>();
1242 QualType BlockPtrTy;
1243 {
1244 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1245 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +00001246 QualType FunctionTy = S.Context.getFunctionType(
1247 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +00001248 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1249 }
Reid Kleckneref072032013-08-27 23:08:25 +00001250
1251 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1252 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +00001253 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +00001254 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +00001255
1256 SourceLocation Loc = IntroducerRange.getBegin();
1257 DeclarationName Name
1258 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1259 S.Context.getCanonicalType(BlockPtrTy));
1260 DeclarationNameLoc NameLoc;
1261 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1262 CXXConversionDecl *Conversion
1263 = CXXConversionDecl::Create(S.Context, Class, Loc,
1264 DeclarationNameInfo(Name, Loc, NameLoc),
1265 ConvTy,
1266 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +00001267 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +00001268 /*isConstexpr=*/false,
1269 CallOperator->getBody()->getLocEnd());
1270 Conversion->setAccess(AS_public);
1271 Conversion->setImplicit(true);
1272 Class->addDecl(Conversion);
1273}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001274
Douglas Gregordfca6f52012-02-13 22:00:16 +00001275ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001276 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001277 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001278 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001279 SmallVector<LambdaExpr::Capture, 4> Captures;
1280 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001281 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001282 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001283 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001284 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001285 SourceRange IntroducerRange;
1286 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001287 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001288 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001289 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001290 SmallVector<VarDecl *, 4> ArrayIndexVars;
1291 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001292 {
1293 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001294 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001295 Class = LSI->Lambda;
1296 IntroducerRange = LSI->IntroducerRange;
1297 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001298 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001299 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001300 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001301 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1302 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1303
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001304 // Translate captures.
1305 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1306 LambdaScopeInfo::Capture From = LSI->Captures[I];
1307 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1308 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1309
1310 // Handle 'this' capture.
1311 if (From.isThisCapture()) {
1312 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1313 IsImplicit,
1314 LCK_This));
1315 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1316 getCurrentThisType(),
1317 /*isImplicit=*/true));
1318 continue;
1319 }
1320
1321 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001322 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1323 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001324 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001325 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001326 }
1327
1328 switch (LSI->ImpCaptureStyle) {
1329 case CapturingScopeInfo::ImpCap_None:
1330 CaptureDefault = LCD_None;
1331 break;
1332
1333 case CapturingScopeInfo::ImpCap_LambdaByval:
1334 CaptureDefault = LCD_ByCopy;
1335 break;
1336
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001337 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001338 case CapturingScopeInfo::ImpCap_LambdaByref:
1339 CaptureDefault = LCD_ByRef;
1340 break;
1341
1342 case CapturingScopeInfo::ImpCap_Block:
1343 llvm_unreachable("block capture in lambda");
1344 break;
1345 }
James Dennettf68af642013-08-09 23:08:25 +00001346 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001347
Douglas Gregor54042f12012-02-09 10:18:50 +00001348 // C++11 [expr.prim.lambda]p4:
1349 // If a lambda-expression does not include a
1350 // trailing-return-type, it is as if the trailing-return-type
1351 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001352 //
1353 // Skip for C++1y return type deduction semantics which uses
1354 // different machinery.
1355 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001356 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001357 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001358 deduceClosureReturnType(*LSI);
1359
Douglas Gregor54042f12012-02-09 10:18:50 +00001360 // - if there are no return statements in the
1361 // compound-statement, or all return statements return
1362 // either an expression of type void or no expression or
1363 // braced-init-list, the type void;
1364 if (LSI->ReturnType.isNull()) {
1365 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001366 }
1367
1368 // Create a function type with the inferred return type.
1369 const FunctionProtoType *Proto
1370 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001371 QualType FunctionTy = Context.getFunctionType(
1372 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001373 CallOperator->setType(FunctionTy);
1374 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001375 // C++ [expr.prim.lambda]p7:
1376 // The lambda-expression's compound-statement yields the
1377 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001378 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001379 CallOperator->setLexicalDeclContext(Class);
Faisal Valifad9e132013-09-26 19:54:12 +00001380 Decl *TemplateOrNonTemplateCallOperatorDecl =
1381 CallOperator->getDescribedFunctionTemplate()
1382 ? CallOperator->getDescribedFunctionTemplate()
1383 : cast<Decl>(CallOperator);
1384
1385 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1386 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1387
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001388 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001389
Douglas Gregorb5559712012-02-10 16:13:20 +00001390 // C++11 [expr.prim.lambda]p6:
1391 // The closure type for a lambda-expression with no lambda-capture
1392 // has a public non-virtual non-explicit const conversion function
1393 // to pointer to function having the same parameter and return
1394 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001395 if (Captures.empty() && CaptureDefault == LCD_None)
1396 addFunctionPointerConversion(*this, IntroducerRange, Class,
1397 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001398
Douglas Gregorc2956e52012-02-15 22:08:38 +00001399 // Objective-C++:
1400 // The closure type for a lambda-expression has a public non-virtual
1401 // non-explicit const conversion function to a block pointer having the
1402 // same parameter and return types as the closure type's function call
1403 // operator.
Faisal Valid6992ab2013-09-29 08:45:24 +00001404 // FIXME: Fix generic lambda to block conversions.
1405 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1406 !Class->isGenericLambda())
Douglas Gregorc2956e52012-02-15 22:08:38 +00001407 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1408
Douglas Gregorb5559712012-02-10 16:13:20 +00001409 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001410 SmallVector<Decl*, 4> Fields;
1411 for (RecordDecl::field_iterator i = Class->field_begin(),
1412 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001413 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001414 ActOnFields(0, Class->getLocation(), Class, Fields,
1415 SourceLocation(), SourceLocation(), 0);
1416 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001417 }
1418
Douglas Gregor503384f2012-02-09 00:47:04 +00001419 if (LambdaExprNeedsCleanups)
1420 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001421
Douglas Gregore2c59132012-02-09 08:14:43 +00001422 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001423 CaptureDefault, CaptureDefaultLoc,
1424 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001425 ExplicitParams, ExplicitResultType,
1426 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001427 ArrayIndexStarts, Body->getLocEnd(),
1428 ContainsUnexpandedParameterPack);
David Majnemer9d33c402013-10-25 09:12:52 +00001429
Douglas Gregord5387e82012-02-14 00:00:48 +00001430 if (!CurContext->isDependentContext()) {
1431 switch (ExprEvalContexts.back().Context) {
David Majnemer9d33c402013-10-25 09:12:52 +00001432 // C++11 [expr.prim.lambda]p2:
1433 // A lambda-expression shall not appear in an unevaluated operand
1434 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001435 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001436 case UnevaluatedAbstract:
David Majnemer9d33c402013-10-25 09:12:52 +00001437 // C++1y [expr.const]p2:
1438 // A conditional-expression e is a core constant expression unless the
1439 // evaluation of e, following the rules of the abstract machine, would
1440 // evaluate [...] a lambda-expression.
David Majnemer6bae51a2013-11-05 08:01:18 +00001441 //
1442 // This is technically incorrect, there are some constant evaluated contexts
1443 // where this should be allowed. We should probably fix this when DR1607 is
1444 // ratified, it lays out the exact set of conditions where we shouldn't
1445 // allow a lambda-expression.
David Majnemer9d33c402013-10-25 09:12:52 +00001446 case ConstantEvaluated:
Douglas Gregord5387e82012-02-14 00:00:48 +00001447 // We don't actually diagnose this case immediately, because we
1448 // could be within a context where we might find out later that
1449 // the expression is potentially evaluated (e.g., for typeid).
1450 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1451 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001452
Douglas Gregord5387e82012-02-14 00:00:48 +00001453 case PotentiallyEvaluated:
1454 case PotentiallyEvaluatedIfUsed:
1455 break;
1456 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001457 }
Faisal Valic00e4192013-11-07 05:17:06 +00001458
Douglas Gregor503384f2012-02-09 00:47:04 +00001459 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001460}
Eli Friedman23f02672012-03-01 04:01:32 +00001461
1462ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1463 SourceLocation ConvLocation,
1464 CXXConversionDecl *Conv,
1465 Expr *Src) {
1466 // Make sure that the lambda call operator is marked used.
1467 CXXRecordDecl *Lambda = Conv->getParent();
1468 CXXMethodDecl *CallOperator
1469 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001470 Lambda->lookup(
1471 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001472 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001473 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001474
1475 ExprResult Init = PerformCopyInitialization(
1476 InitializedEntity::InitializeBlock(ConvLocation,
1477 Src->getType(),
1478 /*NRVO=*/false),
1479 CurrentLocation, Src);
1480 if (!Init.isInvalid())
1481 Init = ActOnFinishFullExpr(Init.take());
1482
1483 if (Init.isInvalid())
1484 return ExprError();
1485
1486 // Create the new block to be returned.
1487 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1488
1489 // Set the type information.
1490 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1491 Block->setIsVariadic(CallOperator->isVariadic());
1492 Block->setBlockMissingReturnType(false);
1493
1494 // Add parameters.
1495 SmallVector<ParmVarDecl *, 4> BlockParams;
1496 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1497 ParmVarDecl *From = CallOperator->getParamDecl(I);
1498 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1499 From->getLocStart(),
1500 From->getLocation(),
1501 From->getIdentifier(),
1502 From->getType(),
1503 From->getTypeSourceInfo(),
1504 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001505 /*DefaultArg=*/0));
1506 }
1507 Block->setParams(BlockParams);
1508
1509 Block->setIsConversionFromLambda(true);
1510
1511 // Add capture. The capture uses a fake variable, which doesn't correspond
1512 // to any actual memory location. However, the initializer copy-initializes
1513 // the lambda object.
1514 TypeSourceInfo *CapVarTSI =
1515 Context.getTrivialTypeSourceInfo(Src->getType());
1516 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1517 ConvLocation, 0,
1518 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001519 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001520 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1521 /*Nested=*/false, /*Copy=*/Init.take());
1522 Block->setCaptures(Context, &Capture, &Capture + 1,
1523 /*CapturesCXXThis=*/false);
1524
1525 // Add a fake function body to the block. IR generation is responsible
1526 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001527 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001528
1529 // Create the block literal expression.
1530 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1531 ExprCleanupObjects.push_back(Block);
1532 ExprNeedsCleanups = true;
1533
1534 return BuildBlock;
1535}