blob: 6c78d83612db8dbff8c7518dda5b3530aa2bd204 [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"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000016#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/AST/ExprCXX.h"
21using namespace clang;
22using namespace sema;
23
Douglas Gregorf4b7de12012-02-21 19:11:17 +000024CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000026 DeclContext *DC = CurContext;
27 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
28 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000029
Douglas Gregore2a7ad02012-02-08 21:18:48 +000030 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000031 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000032 IntroducerRange.getBegin(),
33 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000034 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000035
36 return Class;
37}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000038
Douglas Gregorf54486a2012-04-04 17:40:10 +000039/// \brief Determine whether the given context is or is enclosed in an inline
40/// function.
41static bool isInInlineFunction(const DeclContext *DC) {
42 while (!DC->isFileContext()) {
43 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
44 if (FD->isInlined())
45 return true;
46
47 DC = DC->getLexicalParent();
48 }
49
50 return false;
51}
52
Douglas Gregordfca6f52012-02-13 22:00:16 +000053CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000054 SourceRange IntroducerRange,
55 TypeSourceInfo *MethodType,
56 SourceLocation EndLoc,
57 llvm::ArrayRef<ParmVarDecl *> Params,
58 llvm::Optional<unsigned> ManglingNumber,
59 Decl *ContextDecl) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000060 // C++11 [expr.prim.lambda]p5:
61 // The closure type for a lambda-expression has a public inline function
62 // call operator (13.5.4) whose parameters and return type are described by
63 // the lambda-expression's parameter-declaration-clause and
64 // trailing-return-type respectively.
65 DeclarationName MethodName
66 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67 DeclarationNameLoc MethodNameLoc;
68 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69 = IntroducerRange.getBegin().getRawEncoding();
70 MethodNameLoc.CXXOperatorName.EndOpNameLoc
71 = IntroducerRange.getEnd().getRawEncoding();
72 CXXMethodDecl *Method
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
76 MethodNameLoc),
77 MethodType->getType(), MethodType,
78 /*isStatic=*/false,
79 SC_None,
80 /*isInline=*/true,
81 /*isConstExpr=*/false,
82 EndLoc);
83 Method->setAccess(AS_public);
84
85 // Temporarily set the lexical declaration context to the current
86 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000087 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000088
Douglas Gregorc6889e72012-02-14 22:28:59 +000089 // Add parameters.
90 if (!Params.empty()) {
91 Method->setParams(Params);
92 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93 const_cast<ParmVarDecl **>(Params.end()),
94 /*CheckParameterNames=*/false);
95
96 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97 PEnd = Method->param_end();
98 P != PEnd; ++P)
99 (*P)->setOwningFunction(Method);
100 }
101
Douglas Gregorf54486a2012-04-04 17:40:10 +0000102 // If we don't already have a mangling number for this lambda expression,
103 // allocate one now.
104 if (!ManglingNumber) {
105 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
106
107 enum ContextKind {
108 Normal,
109 DefaultArgument,
110 DataMember,
111 StaticDataMember
112 } Kind = Normal;
113
114 // Default arguments of member function parameters that appear in a class
115 // definition, as well as the initializers of data members, receive special
116 // treatment. Identify them.
117 if (ContextDecl) {
118 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
119 if (const DeclContext *LexicalDC
120 = Param->getDeclContext()->getLexicalParent())
121 if (LexicalDC->isRecord())
122 Kind = DefaultArgument;
123 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
124 if (Var->getDeclContext()->isRecord())
125 Kind = StaticDataMember;
126 } else if (isa<FieldDecl>(ContextDecl)) {
127 Kind = DataMember;
128 }
129 }
130
131 switch (Kind) {
132 case Normal:
133 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134 ManglingNumber = Context.getLambdaManglingNumber(Method);
135 else
136 ManglingNumber = 0;
137
138 // There is no special context for this lambda.
139 ContextDecl = 0;
140 break;
141
142 case StaticDataMember:
143 if (!CurContext->isDependentContext()) {
144 ManglingNumber = 0;
145 ContextDecl = 0;
146 break;
147 }
148 // Fall through to assign a mangling number.
149
150 case DataMember:
151 case DefaultArgument:
152 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153 .getManglingNumber(Method);
154 break;
155 }
156 }
157
158 Class->setLambdaMangling(*ManglingNumber, ContextDecl);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 return Method;
160}
161
162LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163 SourceRange IntroducerRange,
164 LambdaCaptureDefault CaptureDefault,
165 bool ExplicitParams,
166 bool ExplicitResultType,
167 bool Mutable) {
168 PushLambdaScope(CallOperator->getParent(), CallOperator);
169 LambdaScopeInfo *LSI = getCurLambda();
170 if (CaptureDefault == LCD_ByCopy)
171 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
172 else if (CaptureDefault == LCD_ByRef)
173 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
174 LSI->IntroducerRange = IntroducerRange;
175 LSI->ExplicitParams = ExplicitParams;
176 LSI->Mutable = Mutable;
177
178 if (ExplicitResultType) {
179 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000180
181 if (!LSI->ReturnType->isDependentType() &&
182 !LSI->ReturnType->isVoidType()) {
183 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184 diag::err_lambda_incomplete_result)) {
185 // Do nothing.
186 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
188 << LSI->ReturnType;
189 }
190 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 } else {
192 LSI->HasImplicitReturnType = true;
193 }
194
195 return LSI;
196}
197
198void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199 LSI->finishedExplicitCaptures();
200}
201
Douglas Gregorc6889e72012-02-14 22:28:59 +0000202void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000203 // Introduce our parameters into the function scope
204 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
205 p < NumParams; ++p) {
206 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000207
208 // If this has an identifier, add it to the scope stack.
209 if (CurScope && Param->getIdentifier()) {
210 CheckShadow(CurScope, Param);
211
212 PushOnScopeChains(Param, CurScope);
213 }
214 }
215}
216
Jordan Rose7dd900e2012-07-02 21:19:23 +0000217static bool checkReturnValueType(const ASTContext &Ctx, const Expr *E,
218 QualType &DeducedType,
219 QualType &AlternateType) {
220 // Handle ReturnStmts with no expressions.
221 if (!E) {
222 if (AlternateType.isNull())
223 AlternateType = Ctx.VoidTy;
224
225 return Ctx.hasSameType(DeducedType, Ctx.VoidTy);
226 }
227
228 QualType StrictType = E->getType();
229 QualType LooseType = StrictType;
230
231 // In C, enum constants have the type of their underlying integer type,
232 // not the enum. When inferring block return types, we should allow
233 // the enum type if an enum constant is used, unless the enum is
234 // anonymous (in which case there can be no variables of its type).
235 if (!Ctx.getLangOpts().CPlusPlus) {
236 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
237 if (DRE) {
238 const Decl *D = DRE->getDecl();
239 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
240 const EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
241 if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl())
242 LooseType = Ctx.getTypeDeclType(Enum);
243 }
244 }
245 }
246
247 // Special case for the first return statement we find.
248 // The return type has already been tentatively set, but we might still
249 // have an alternate type we should prefer.
250 if (AlternateType.isNull())
251 AlternateType = LooseType;
252
253 if (Ctx.hasSameType(DeducedType, StrictType)) {
254 // FIXME: The loose type is different when there are constants from two
255 // different enums. We could consider warning here.
256 if (AlternateType != Ctx.DependentTy)
257 if (!Ctx.hasSameType(AlternateType, LooseType))
258 AlternateType = Ctx.VoidTy;
259 return true;
260 }
261
262 if (Ctx.hasSameType(DeducedType, LooseType)) {
263 // Use DependentTy to signal that we're using an alternate type and may
264 // need to add casts somewhere.
265 AlternateType = Ctx.DependentTy;
266 return true;
267 }
268
269 if (Ctx.hasSameType(AlternateType, StrictType) ||
270 Ctx.hasSameType(AlternateType, LooseType)) {
271 DeducedType = AlternateType;
272 // Use DependentTy to signal that we're using an alternate type and may
273 // need to add casts somewhere.
274 AlternateType = Ctx.DependentTy;
275 return true;
276 }
277
278 return false;
279}
280
281void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
282 assert(CSI.HasImplicitReturnType);
283
284 // First case: no return statements, implicit void return type.
285 ASTContext &Ctx = getASTContext();
286 if (CSI.Returns.empty()) {
287 // It's possible there were simply no /valid/ return statements.
288 // In this case, the first one we found may have at least given us a type.
289 if (CSI.ReturnType.isNull())
290 CSI.ReturnType = Ctx.VoidTy;
291 return;
292 }
293
294 // Second case: at least one return statement has dependent type.
295 // Delay type checking until instantiation.
296 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
297 if (CSI.ReturnType->isDependentType())
298 return;
299
300 // Third case: only one return statement. Don't bother doing extra work!
301 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
302 E = CSI.Returns.end();
303 if (I+1 == E)
304 return;
305
306 // General case: many return statements.
307 // Check that they all have compatible return types.
308 // For now, that means "identical", with an exception for enum constants.
309 // (In C, enum constants have the type of their underlying integer type,
310 // not the type of the enum. C++ uses the type of the enum.)
311 QualType AlternateType;
312
313 // We require the return types to strictly match here.
314 for (; I != E; ++I) {
315 const ReturnStmt *RS = *I;
316 const Expr *RetE = RS->getRetValue();
317 if (!checkReturnValueType(Ctx, RetE, CSI.ReturnType, AlternateType)) {
318 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
319 Diag(RS->getLocStart(),
320 diag::err_typecheck_missing_return_type_incompatible)
321 << (RetE ? RetE->getType() : Ctx.VoidTy) << CSI.ReturnType
322 << isa<LambdaScopeInfo>(CSI);
323 // Don't bother fixing up the return statements in the block if some of
324 // them are unfixable anyway.
325 AlternateType = Ctx.VoidTy;
326 // Continue iterating so that we keep emitting diagnostics.
327 }
328 }
329
330 // If our return statements turned out to be compatible, but we needed to
331 // pick a different return type, go through and fix the ones that need it.
332 if (AlternateType == Ctx.DependentTy) {
333 for (SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
334 E = CSI.Returns.end();
335 I != E; ++I) {
336 ReturnStmt *RS = *I;
337 Expr *RetE = RS->getRetValue();
338 if (RetE->getType() == CSI.ReturnType)
339 continue;
340
341 // Right now we only support integral fixup casts.
342 assert(CSI.ReturnType->isIntegralOrUnscopedEnumerationType());
343 assert(RetE->getType()->isIntegralOrUnscopedEnumerationType());
344 ExprResult Casted = ImpCastExprToType(RetE, CSI.ReturnType,
345 CK_IntegralCast);
346 assert(Casted.isUsable());
347 RS->setRetValue(Casted.take());
348 }
349 }
350}
351
Douglas Gregordfca6f52012-02-13 22:00:16 +0000352void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
353 Declarator &ParamInfo,
354 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000355 // Determine if we're within a context where we know that the lambda will
356 // be dependent, because there are template parameters in scope.
357 bool KnownDependent = false;
358 if (Scope *TmplScope = CurScope->getTemplateParamParent())
359 if (!TmplScope->decl_empty())
360 KnownDependent = true;
361
362 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000363
364 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000365 TypeSourceInfo *MethodTyInfo;
366 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000367 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000368 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000369 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000370 if (ParamInfo.getNumTypeObjects() == 0) {
371 // C++11 [expr.prim.lambda]p4:
372 // If a lambda-expression does not include a lambda-declarator, it is as
373 // if the lambda-declarator were ().
374 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000375 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000376 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000377 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
378 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000379 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
380 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000381 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000382 EndLoc = Intro.Range.getEnd();
383 } else {
384 assert(ParamInfo.isFunctionDeclarator() &&
385 "lambda-declarator is a function");
386 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
387
388 // C++11 [expr.prim.lambda]p5:
389 // This function call operator is declared const (9.3.1) if and only if
390 // the lambda-expression's parameter-declaration-clause is not followed
391 // by mutable. It is neither virtual nor declared volatile. [...]
392 if (!FTI.hasMutableQualifier())
393 FTI.TypeQuals |= DeclSpec::TQ_const;
394
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000395 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000396 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000397 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000398
399 ExplicitResultType
400 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
401 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000402
403 TypeLoc TL = MethodTyInfo->getTypeLoc();
404 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
405 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
406 Proto.getNumArgs());
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000407
408 // Check for unexpanded parameter packs in the method type.
409 // FIXME: We should allow unexpanded parameter packs here, but that would,
410 // in turn, make the lambda expression contain unexpanded parameter packs.
411 if (DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
412 UPPC_Lambda)) {
413 // Drop the parameters.
414 Params = llvm::ArrayRef<ParmVarDecl *>();
415 FunctionProtoType::ExtProtoInfo EPI;
416 EPI.HasTrailingReturn = false;
417 EPI.TypeQuals |= DeclSpec::TQ_const;
418 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
419 /*Args=*/0, /*NumArgs=*/0, EPI);
420 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
421 ExplicitParams = false;
422 ExplicitResultType = false;
423 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000424 }
425
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000426 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000427 MethodTyInfo, EndLoc, Params);
428
429 if (ExplicitParams)
430 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000431
Douglas Gregor503384f2012-02-09 00:47:04 +0000432 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000433 ProcessDeclAttributes(CurScope, Method, ParamInfo);
434
Douglas Gregor503384f2012-02-09 00:47:04 +0000435 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000436 PushDeclContext(CurScope, Method);
437
438 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000439 LambdaScopeInfo *LSI
440 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
441 ExplicitResultType,
442 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000443
444 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000445 SourceLocation PrevCaptureLoc
446 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000447 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
448 C = Intro.Captures.begin(),
449 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000450 C != E;
451 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000452 if (C->Kind == LCK_This) {
453 // C++11 [expr.prim.lambda]p8:
454 // An identifier or this shall not appear more than once in a
455 // lambda-capture.
456 if (LSI->isCXXThisCaptured()) {
457 Diag(C->Loc, diag::err_capture_more_than_once)
458 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000459 << SourceRange(LSI->getCXXThisCapture().getLocation())
460 << FixItHint::CreateRemoval(
461 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000462 continue;
463 }
464
465 // C++11 [expr.prim.lambda]p8:
466 // If a lambda-capture includes a capture-default that is =, the
467 // lambda-capture shall not contain this [...].
468 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000469 Diag(C->Loc, diag::err_this_capture_with_copy_default)
470 << FixItHint::CreateRemoval(
471 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000472 continue;
473 }
474
475 // C++11 [expr.prim.lambda]p12:
476 // If this is captured by a local lambda expression, its nearest
477 // enclosing function shall be a non-static member function.
478 QualType ThisCaptureType = getCurrentThisType();
479 if (ThisCaptureType.isNull()) {
480 Diag(C->Loc, diag::err_this_capture) << true;
481 continue;
482 }
483
484 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
485 continue;
486 }
487
488 assert(C->Id && "missing identifier for capture");
489
490 // C++11 [expr.prim.lambda]p8:
491 // If a lambda-capture includes a capture-default that is &, the
492 // identifiers in the lambda-capture shall not be preceded by &.
493 // If a lambda-capture includes a capture-default that is =, [...]
494 // each identifier it contains shall be preceded by &.
495 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000496 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
497 << FixItHint::CreateRemoval(
498 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000499 continue;
500 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000501 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
502 << FixItHint::CreateRemoval(
503 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000504 continue;
505 }
506
507 DeclarationNameInfo Name(C->Id, C->Loc);
508 LookupResult R(*this, Name, LookupOrdinaryName);
509 LookupName(R, CurScope);
510 if (R.isAmbiguous())
511 continue;
512 if (R.empty()) {
513 // FIXME: Disable corrections that would add qualification?
514 CXXScopeSpec ScopeSpec;
515 DeclFilterCCC<VarDecl> Validator;
516 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
517 continue;
518 }
519
520 // C++11 [expr.prim.lambda]p10:
521 // The identifiers in a capture-list are looked up using the usual rules
522 // for unqualified name lookup (3.4.1); each such lookup shall find a
523 // variable with automatic storage duration declared in the reaching
524 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000525 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000526 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000527 VarDecl *Var = R.getAsSingle<VarDecl>();
528 if (!Var) {
529 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
530 continue;
531 }
532
533 if (!Var->hasLocalStorage()) {
534 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
535 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
536 continue;
537 }
538
539 // C++11 [expr.prim.lambda]p8:
540 // An identifier or this shall not appear more than once in a
541 // lambda-capture.
542 if (LSI->isCaptured(Var)) {
543 Diag(C->Loc, diag::err_capture_more_than_once)
544 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000545 << SourceRange(LSI->getCapture(Var).getLocation())
546 << FixItHint::CreateRemoval(
547 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000548 continue;
549 }
550
Douglas Gregora7365242012-02-14 19:27:52 +0000551 // C++11 [expr.prim.lambda]p23:
552 // A capture followed by an ellipsis is a pack expansion (14.5.3).
553 SourceLocation EllipsisLoc;
554 if (C->EllipsisLoc.isValid()) {
555 if (Var->isParameterPack()) {
556 EllipsisLoc = C->EllipsisLoc;
557 } else {
558 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
559 << SourceRange(C->Loc);
560
561 // Just ignore the ellipsis.
562 }
563 } else if (Var->isParameterPack()) {
564 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
565 continue;
566 }
567
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000568 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
569 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000570 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000571 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000572 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000573
Douglas Gregorc6889e72012-02-14 22:28:59 +0000574 // Add lambda parameters into scope.
575 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000576
Douglas Gregordfca6f52012-02-13 22:00:16 +0000577 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000578 // cleanups from the enclosing full-expression.
579 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580}
581
Douglas Gregordfca6f52012-02-13 22:00:16 +0000582void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
583 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000584 // Leave the expression-evaluation context.
585 DiscardCleanupsInEvaluationContext();
586 PopExpressionEvaluationContext();
587
588 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000589 if (!IsInstantiation)
590 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000591
592 // Finalize the lambda.
593 LambdaScopeInfo *LSI = getCurLambda();
594 CXXRecordDecl *Class = LSI->Lambda;
595 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000596 SmallVector<Decl*, 4> Fields;
597 for (RecordDecl::field_iterator i = Class->field_begin(),
598 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000599 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000600 ActOnFields(0, Class->getLocation(), Class, Fields,
601 SourceLocation(), SourceLocation(), 0);
602 CheckCompletedCXXClass(Class);
603
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000604 PopFunctionScopeInfo();
605}
606
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000607/// \brief Add a lambda's conversion to function pointer, as described in
608/// C++11 [expr.prim.lambda]p6.
609static void addFunctionPointerConversion(Sema &S,
610 SourceRange IntroducerRange,
611 CXXRecordDecl *Class,
612 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000613 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000614 const FunctionProtoType *Proto
615 = CallOperator->getType()->getAs<FunctionProtoType>();
616 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000617 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000618 {
619 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
620 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000621 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
622 Proto->arg_type_begin(),
623 Proto->getNumArgs(),
624 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000625 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
626 }
627
628 FunctionProtoType::ExtProtoInfo ExtInfo;
629 ExtInfo.TypeQuals = Qualifiers::Const;
630 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
631
632 SourceLocation Loc = IntroducerRange.getBegin();
633 DeclarationName Name
634 = S.Context.DeclarationNames.getCXXConversionFunctionName(
635 S.Context.getCanonicalType(FunctionPtrTy));
636 DeclarationNameLoc NameLoc;
637 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
638 Loc);
639 CXXConversionDecl *Conversion
640 = CXXConversionDecl::Create(S.Context, Class, Loc,
641 DeclarationNameInfo(Name, Loc, NameLoc),
642 ConvTy,
643 S.Context.getTrivialTypeSourceInfo(ConvTy,
644 Loc),
645 /*isInline=*/false, /*isExplicit=*/false,
646 /*isConstexpr=*/false,
647 CallOperator->getBody()->getLocEnd());
648 Conversion->setAccess(AS_public);
649 Conversion->setImplicit(true);
650 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000651
652 // Add a non-static member function "__invoke" that will be the result of
653 // the conversion.
654 Name = &S.Context.Idents.get("__invoke");
655 CXXMethodDecl *Invoke
656 = CXXMethodDecl::Create(S.Context, Class, Loc,
657 DeclarationNameInfo(Name, Loc), FunctionTy,
658 CallOperator->getTypeSourceInfo(),
659 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
660 /*IsConstexpr=*/false,
661 CallOperator->getBody()->getLocEnd());
662 SmallVector<ParmVarDecl *, 4> InvokeParams;
663 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
664 ParmVarDecl *From = CallOperator->getParamDecl(I);
665 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
666 From->getLocStart(),
667 From->getLocation(),
668 From->getIdentifier(),
669 From->getType(),
670 From->getTypeSourceInfo(),
671 From->getStorageClass(),
672 From->getStorageClassAsWritten(),
673 /*DefaultArg=*/0));
674 }
675 Invoke->setParams(InvokeParams);
676 Invoke->setAccess(AS_private);
677 Invoke->setImplicit(true);
678 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000679}
680
Douglas Gregorc2956e52012-02-15 22:08:38 +0000681/// \brief Add a lambda's conversion to block pointer.
682static void addBlockPointerConversion(Sema &S,
683 SourceRange IntroducerRange,
684 CXXRecordDecl *Class,
685 CXXMethodDecl *CallOperator) {
686 const FunctionProtoType *Proto
687 = CallOperator->getType()->getAs<FunctionProtoType>();
688 QualType BlockPtrTy;
689 {
690 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
691 ExtInfo.TypeQuals = 0;
692 QualType FunctionTy
693 = S.Context.getFunctionType(Proto->getResultType(),
694 Proto->arg_type_begin(),
695 Proto->getNumArgs(),
696 ExtInfo);
697 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
698 }
699
700 FunctionProtoType::ExtProtoInfo ExtInfo;
701 ExtInfo.TypeQuals = Qualifiers::Const;
702 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
703
704 SourceLocation Loc = IntroducerRange.getBegin();
705 DeclarationName Name
706 = S.Context.DeclarationNames.getCXXConversionFunctionName(
707 S.Context.getCanonicalType(BlockPtrTy));
708 DeclarationNameLoc NameLoc;
709 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
710 CXXConversionDecl *Conversion
711 = CXXConversionDecl::Create(S.Context, Class, Loc,
712 DeclarationNameInfo(Name, Loc, NameLoc),
713 ConvTy,
714 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
715 /*isInline=*/false, /*isExplicit=*/false,
716 /*isConstexpr=*/false,
717 CallOperator->getBody()->getLocEnd());
718 Conversion->setAccess(AS_public);
719 Conversion->setImplicit(true);
720 Class->addDecl(Conversion);
721}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000722
Douglas Gregordfca6f52012-02-13 22:00:16 +0000723ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000724 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000725 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000726 // Collect information from the lambda scope.
727 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
728 llvm::SmallVector<Expr *, 4> CaptureInits;
729 LambdaCaptureDefault CaptureDefault;
730 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000731 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000732 SourceRange IntroducerRange;
733 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000734 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000735 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000736 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
737 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000738 {
739 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000740 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000741 Class = LSI->Lambda;
742 IntroducerRange = LSI->IntroducerRange;
743 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000744 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000745 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000746 ArrayIndexVars.swap(LSI->ArrayIndexVars);
747 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
748
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000749 // Translate captures.
750 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
751 LambdaScopeInfo::Capture From = LSI->Captures[I];
752 assert(!From.isBlockCapture() && "Cannot capture __block variables");
753 bool IsImplicit = I >= LSI->NumExplicitCaptures;
754
755 // Handle 'this' capture.
756 if (From.isThisCapture()) {
757 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
758 IsImplicit,
759 LCK_This));
760 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
761 getCurrentThisType(),
762 /*isImplicit=*/true));
763 continue;
764 }
765
766 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000767 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
768 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000769 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000770 CaptureInits.push_back(From.getCopyExpr());
771 }
772
773 switch (LSI->ImpCaptureStyle) {
774 case CapturingScopeInfo::ImpCap_None:
775 CaptureDefault = LCD_None;
776 break;
777
778 case CapturingScopeInfo::ImpCap_LambdaByval:
779 CaptureDefault = LCD_ByCopy;
780 break;
781
782 case CapturingScopeInfo::ImpCap_LambdaByref:
783 CaptureDefault = LCD_ByRef;
784 break;
785
786 case CapturingScopeInfo::ImpCap_Block:
787 llvm_unreachable("block capture in lambda");
788 break;
789 }
790
Douglas Gregor54042f12012-02-09 10:18:50 +0000791 // C++11 [expr.prim.lambda]p4:
792 // If a lambda-expression does not include a
793 // trailing-return-type, it is as if the trailing-return-type
794 // denotes the following type:
795 // FIXME: Assumes current resolution to core issue 975.
796 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000797 deduceClosureReturnType(*LSI);
798
Douglas Gregor54042f12012-02-09 10:18:50 +0000799 // - if there are no return statements in the
800 // compound-statement, or all return statements return
801 // either an expression of type void or no expression or
802 // braced-init-list, the type void;
803 if (LSI->ReturnType.isNull()) {
804 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000805 }
806
807 // Create a function type with the inferred return type.
808 const FunctionProtoType *Proto
809 = CallOperator->getType()->getAs<FunctionProtoType>();
810 QualType FunctionTy
811 = Context.getFunctionType(LSI->ReturnType,
812 Proto->arg_type_begin(),
813 Proto->getNumArgs(),
814 Proto->getExtProtoInfo());
815 CallOperator->setType(FunctionTy);
816 }
817
Douglas Gregor215e4e12012-02-12 17:34:23 +0000818 // C++ [expr.prim.lambda]p7:
819 // The lambda-expression's compound-statement yields the
820 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000821 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000822 CallOperator->setLexicalDeclContext(Class);
823 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000824 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000825
Douglas Gregorb5559712012-02-10 16:13:20 +0000826 // C++11 [expr.prim.lambda]p6:
827 // The closure type for a lambda-expression with no lambda-capture
828 // has a public non-virtual non-explicit const conversion function
829 // to pointer to function having the same parameter and return
830 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000831 if (Captures.empty() && CaptureDefault == LCD_None)
832 addFunctionPointerConversion(*this, IntroducerRange, Class,
833 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000834
Douglas Gregorc2956e52012-02-15 22:08:38 +0000835 // Objective-C++:
836 // The closure type for a lambda-expression has a public non-virtual
837 // non-explicit const conversion function to a block pointer having the
838 // same parameter and return types as the closure type's function call
839 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000840 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000841 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
842
Douglas Gregorb5559712012-02-10 16:13:20 +0000843 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000844 SmallVector<Decl*, 4> Fields;
845 for (RecordDecl::field_iterator i = Class->field_begin(),
846 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000847 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000848 ActOnFields(0, Class->getLocation(), Class, Fields,
849 SourceLocation(), SourceLocation(), 0);
850 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000851 }
852
Douglas Gregor503384f2012-02-09 00:47:04 +0000853 if (LambdaExprNeedsCleanups)
854 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000855
Douglas Gregore2c59132012-02-09 08:14:43 +0000856 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
857 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000858 ExplicitParams, ExplicitResultType,
859 CaptureInits, ArrayIndexVars,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000860 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000861
862 // C++11 [expr.prim.lambda]p2:
863 // A lambda-expression shall not appear in an unevaluated operand
864 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000865 if (!CurContext->isDependentContext()) {
866 switch (ExprEvalContexts.back().Context) {
867 case Unevaluated:
868 // We don't actually diagnose this case immediately, because we
869 // could be within a context where we might find out later that
870 // the expression is potentially evaluated (e.g., for typeid).
871 ExprEvalContexts.back().Lambdas.push_back(Lambda);
872 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000873
Douglas Gregord5387e82012-02-14 00:00:48 +0000874 case ConstantEvaluated:
875 case PotentiallyEvaluated:
876 case PotentiallyEvaluatedIfUsed:
877 break;
878 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000879 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000880
Douglas Gregor503384f2012-02-09 00:47:04 +0000881 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000882}
Eli Friedman23f02672012-03-01 04:01:32 +0000883
884ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
885 SourceLocation ConvLocation,
886 CXXConversionDecl *Conv,
887 Expr *Src) {
888 // Make sure that the lambda call operator is marked used.
889 CXXRecordDecl *Lambda = Conv->getParent();
890 CXXMethodDecl *CallOperator
891 = cast<CXXMethodDecl>(
892 *Lambda->lookup(
893 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
894 CallOperator->setReferenced();
895 CallOperator->setUsed();
896
897 ExprResult Init = PerformCopyInitialization(
898 InitializedEntity::InitializeBlock(ConvLocation,
899 Src->getType(),
900 /*NRVO=*/false),
901 CurrentLocation, Src);
902 if (!Init.isInvalid())
903 Init = ActOnFinishFullExpr(Init.take());
904
905 if (Init.isInvalid())
906 return ExprError();
907
908 // Create the new block to be returned.
909 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
910
911 // Set the type information.
912 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
913 Block->setIsVariadic(CallOperator->isVariadic());
914 Block->setBlockMissingReturnType(false);
915
916 // Add parameters.
917 SmallVector<ParmVarDecl *, 4> BlockParams;
918 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
919 ParmVarDecl *From = CallOperator->getParamDecl(I);
920 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
921 From->getLocStart(),
922 From->getLocation(),
923 From->getIdentifier(),
924 From->getType(),
925 From->getTypeSourceInfo(),
926 From->getStorageClass(),
927 From->getStorageClassAsWritten(),
928 /*DefaultArg=*/0));
929 }
930 Block->setParams(BlockParams);
931
932 Block->setIsConversionFromLambda(true);
933
934 // Add capture. The capture uses a fake variable, which doesn't correspond
935 // to any actual memory location. However, the initializer copy-initializes
936 // the lambda object.
937 TypeSourceInfo *CapVarTSI =
938 Context.getTrivialTypeSourceInfo(Src->getType());
939 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
940 ConvLocation, 0,
941 Src->getType(), CapVarTSI,
942 SC_None, SC_None);
943 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
944 /*Nested=*/false, /*Copy=*/Init.take());
945 Block->setCaptures(Context, &Capture, &Capture + 1,
946 /*CapturesCXXThis=*/false);
947
948 // Add a fake function body to the block. IR generation is responsible
949 // for filling in the actual body, which cannot be expressed as an AST.
950 Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
951 ConvLocation,
952 ConvLocation));
953
954 // Create the block literal expression.
955 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
956 ExprCleanupObjects.push_back(Block);
957 ExprNeedsCleanups = true;
958
959 return BuildBlock;
960}