blob: 7cbfc364f66679d85fbf1d6972267ab1f50c0664 [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,
Richard Smithadb1d4c2012-07-22 23:45:10 +000057 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000058 // C++11 [expr.prim.lambda]p5:
59 // The closure type for a lambda-expression has a public inline function
60 // call operator (13.5.4) whose parameters and return type are described by
61 // the lambda-expression's parameter-declaration-clause and
62 // trailing-return-type respectively.
63 DeclarationName MethodName
64 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
65 DeclarationNameLoc MethodNameLoc;
66 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
67 = IntroducerRange.getBegin().getRawEncoding();
68 MethodNameLoc.CXXOperatorName.EndOpNameLoc
69 = IntroducerRange.getEnd().getRawEncoding();
70 CXXMethodDecl *Method
71 = CXXMethodDecl::Create(Context, Class, EndLoc,
72 DeclarationNameInfo(MethodName,
73 IntroducerRange.getBegin(),
74 MethodNameLoc),
75 MethodType->getType(), MethodType,
76 /*isStatic=*/false,
77 SC_None,
78 /*isInline=*/true,
79 /*isConstExpr=*/false,
80 EndLoc);
81 Method->setAccess(AS_public);
82
83 // Temporarily set the lexical declaration context to the current
84 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000085 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000086
Douglas Gregorc6889e72012-02-14 22:28:59 +000087 // Add parameters.
88 if (!Params.empty()) {
89 Method->setParams(Params);
90 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
91 const_cast<ParmVarDecl **>(Params.end()),
92 /*CheckParameterNames=*/false);
93
94 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
95 PEnd = Method->param_end();
96 P != PEnd; ++P)
97 (*P)->setOwningFunction(Method);
98 }
Richard Smithadb1d4c2012-07-22 23:45:10 +000099
100 // Allocate a mangling number for this lambda expression, if the ABI
101 // requires one.
102 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
103
104 enum ContextKind {
105 Normal,
106 DefaultArgument,
107 DataMember,
108 StaticDataMember
109 } Kind = Normal;
110
111 // Default arguments of member function parameters that appear in a class
112 // definition, as well as the initializers of data members, receive special
113 // treatment. Identify them.
114 if (ContextDecl) {
115 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
116 if (const DeclContext *LexicalDC
117 = Param->getDeclContext()->getLexicalParent())
118 if (LexicalDC->isRecord())
119 Kind = DefaultArgument;
120 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
121 if (Var->getDeclContext()->isRecord())
122 Kind = StaticDataMember;
123 } else if (isa<FieldDecl>(ContextDecl)) {
124 Kind = DataMember;
Douglas Gregorf54486a2012-04-04 17:40:10 +0000125 }
126 }
127
Richard Smithadb1d4c2012-07-22 23:45:10 +0000128 // Itanium ABI [5.1.7]:
129 // In the following contexts [...] the one-definition rule requires closure
130 // types in different translation units to "correspond":
131 bool IsInNonspecializedTemplate =
132 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
133 unsigned ManglingNumber;
134 switch (Kind) {
135 case Normal:
136 // -- the bodies of non-exported nonspecialized template functions
137 // -- the bodies of inline functions
138 if ((IsInNonspecializedTemplate &&
139 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
140 isInInlineFunction(CurContext))
141 ManglingNumber = Context.getLambdaManglingNumber(Method);
142 else
143 ManglingNumber = 0;
144
145 // There is no special context for this lambda.
146 ContextDecl = 0;
147 break;
148
149 case StaticDataMember:
150 // -- the initializers of nonspecialized static members of template classes
151 if (!IsInNonspecializedTemplate) {
152 ManglingNumber = 0;
153 ContextDecl = 0;
154 break;
155 }
156 // Fall through to assign a mangling number.
157
158 case DataMember:
159 // -- the in-class initializers of class members
160 case DefaultArgument:
161 // -- default arguments appearing in class definitions
162 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
163 .getManglingNumber(Method);
164 break;
165 }
166
167 Class->setLambdaMangling(ManglingNumber, ContextDecl);
168
Douglas Gregordfca6f52012-02-13 22:00:16 +0000169 return Method;
170}
171
172LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
173 SourceRange IntroducerRange,
174 LambdaCaptureDefault CaptureDefault,
175 bool ExplicitParams,
176 bool ExplicitResultType,
177 bool Mutable) {
178 PushLambdaScope(CallOperator->getParent(), CallOperator);
179 LambdaScopeInfo *LSI = getCurLambda();
180 if (CaptureDefault == LCD_ByCopy)
181 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
182 else if (CaptureDefault == LCD_ByRef)
183 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
184 LSI->IntroducerRange = IntroducerRange;
185 LSI->ExplicitParams = ExplicitParams;
186 LSI->Mutable = Mutable;
187
188 if (ExplicitResultType) {
189 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000190
191 if (!LSI->ReturnType->isDependentType() &&
192 !LSI->ReturnType->isVoidType()) {
193 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
194 diag::err_lambda_incomplete_result)) {
195 // Do nothing.
196 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
197 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
198 << LSI->ReturnType;
199 }
200 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000201 } else {
202 LSI->HasImplicitReturnType = true;
203 }
204
205 return LSI;
206}
207
208void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
209 LSI->finishedExplicitCaptures();
210}
211
Douglas Gregorc6889e72012-02-14 22:28:59 +0000212void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000213 // Introduce our parameters into the function scope
214 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
215 p < NumParams; ++p) {
216 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000217
218 // If this has an identifier, add it to the scope stack.
219 if (CurScope && Param->getIdentifier()) {
220 CheckShadow(CurScope, Param);
221
222 PushOnScopeChains(Param, CurScope);
223 }
224 }
225}
226
Jordan Rose7dd900e2012-07-02 21:19:23 +0000227static bool checkReturnValueType(const ASTContext &Ctx, const Expr *E,
228 QualType &DeducedType,
229 QualType &AlternateType) {
230 // Handle ReturnStmts with no expressions.
231 if (!E) {
232 if (AlternateType.isNull())
233 AlternateType = Ctx.VoidTy;
234
235 return Ctx.hasSameType(DeducedType, Ctx.VoidTy);
236 }
237
238 QualType StrictType = E->getType();
239 QualType LooseType = StrictType;
240
241 // In C, enum constants have the type of their underlying integer type,
242 // not the enum. When inferring block return types, we should allow
243 // the enum type if an enum constant is used, unless the enum is
244 // anonymous (in which case there can be no variables of its type).
245 if (!Ctx.getLangOpts().CPlusPlus) {
246 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
247 if (DRE) {
248 const Decl *D = DRE->getDecl();
249 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
250 const EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
251 if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl())
252 LooseType = Ctx.getTypeDeclType(Enum);
253 }
254 }
255 }
256
257 // Special case for the first return statement we find.
258 // The return type has already been tentatively set, but we might still
259 // have an alternate type we should prefer.
260 if (AlternateType.isNull())
261 AlternateType = LooseType;
262
263 if (Ctx.hasSameType(DeducedType, StrictType)) {
264 // FIXME: The loose type is different when there are constants from two
265 // different enums. We could consider warning here.
266 if (AlternateType != Ctx.DependentTy)
267 if (!Ctx.hasSameType(AlternateType, LooseType))
268 AlternateType = Ctx.VoidTy;
269 return true;
270 }
271
272 if (Ctx.hasSameType(DeducedType, LooseType)) {
273 // Use DependentTy to signal that we're using an alternate type and may
274 // need to add casts somewhere.
275 AlternateType = Ctx.DependentTy;
276 return true;
277 }
278
279 if (Ctx.hasSameType(AlternateType, StrictType) ||
280 Ctx.hasSameType(AlternateType, LooseType)) {
281 DeducedType = AlternateType;
282 // Use DependentTy to signal that we're using an alternate type and may
283 // need to add casts somewhere.
284 AlternateType = Ctx.DependentTy;
285 return true;
286 }
287
288 return false;
289}
290
291void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
292 assert(CSI.HasImplicitReturnType);
293
294 // First case: no return statements, implicit void return type.
295 ASTContext &Ctx = getASTContext();
296 if (CSI.Returns.empty()) {
297 // It's possible there were simply no /valid/ return statements.
298 // In this case, the first one we found may have at least given us a type.
299 if (CSI.ReturnType.isNull())
300 CSI.ReturnType = Ctx.VoidTy;
301 return;
302 }
303
304 // Second case: at least one return statement has dependent type.
305 // Delay type checking until instantiation.
306 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
307 if (CSI.ReturnType->isDependentType())
308 return;
309
310 // Third case: only one return statement. Don't bother doing extra work!
311 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
312 E = CSI.Returns.end();
313 if (I+1 == E)
314 return;
315
316 // General case: many return statements.
317 // Check that they all have compatible return types.
318 // For now, that means "identical", with an exception for enum constants.
319 // (In C, enum constants have the type of their underlying integer type,
320 // not the type of the enum. C++ uses the type of the enum.)
321 QualType AlternateType;
322
323 // We require the return types to strictly match here.
324 for (; I != E; ++I) {
325 const ReturnStmt *RS = *I;
326 const Expr *RetE = RS->getRetValue();
327 if (!checkReturnValueType(Ctx, RetE, CSI.ReturnType, AlternateType)) {
328 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
329 Diag(RS->getLocStart(),
330 diag::err_typecheck_missing_return_type_incompatible)
331 << (RetE ? RetE->getType() : Ctx.VoidTy) << CSI.ReturnType
332 << isa<LambdaScopeInfo>(CSI);
333 // Don't bother fixing up the return statements in the block if some of
334 // them are unfixable anyway.
335 AlternateType = Ctx.VoidTy;
336 // Continue iterating so that we keep emitting diagnostics.
337 }
338 }
339
340 // If our return statements turned out to be compatible, but we needed to
341 // pick a different return type, go through and fix the ones that need it.
342 if (AlternateType == Ctx.DependentTy) {
343 for (SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
344 E = CSI.Returns.end();
345 I != E; ++I) {
346 ReturnStmt *RS = *I;
347 Expr *RetE = RS->getRetValue();
348 if (RetE->getType() == CSI.ReturnType)
349 continue;
350
351 // Right now we only support integral fixup casts.
352 assert(CSI.ReturnType->isIntegralOrUnscopedEnumerationType());
353 assert(RetE->getType()->isIntegralOrUnscopedEnumerationType());
354 ExprResult Casted = ImpCastExprToType(RetE, CSI.ReturnType,
355 CK_IntegralCast);
356 assert(Casted.isUsable());
357 RS->setRetValue(Casted.take());
358 }
359 }
360}
361
Douglas Gregordfca6f52012-02-13 22:00:16 +0000362void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
363 Declarator &ParamInfo,
364 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000365 // Determine if we're within a context where we know that the lambda will
366 // be dependent, because there are template parameters in scope.
367 bool KnownDependent = false;
368 if (Scope *TmplScope = CurScope->getTemplateParamParent())
369 if (!TmplScope->decl_empty())
370 KnownDependent = true;
371
372 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000373
374 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000375 TypeSourceInfo *MethodTyInfo;
376 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000377 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000378 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000379 SourceLocation EndLoc;
Richard Smith3bc22262012-08-30 13:13:20 +0000380 llvm::SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000381 if (ParamInfo.getNumTypeObjects() == 0) {
382 // C++11 [expr.prim.lambda]p4:
383 // If a lambda-expression does not include a lambda-declarator, it is as
384 // if the lambda-declarator were ().
385 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000386 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000387 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000388 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
389 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000390 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
391 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000392 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000393 EndLoc = Intro.Range.getEnd();
394 } else {
395 assert(ParamInfo.isFunctionDeclarator() &&
396 "lambda-declarator is a function");
397 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
398
399 // C++11 [expr.prim.lambda]p5:
400 // This function call operator is declared const (9.3.1) if and only if
401 // the lambda-expression's parameter-declaration-clause is not followed
402 // by mutable. It is neither virtual nor declared volatile. [...]
403 if (!FTI.hasMutableQualifier())
404 FTI.TypeQuals |= DeclSpec::TQ_const;
405
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000406 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000407 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000408 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000409
410 ExplicitResultType
411 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
412 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000413
414 Params.reserve(FTI.NumArgs);
415 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
416 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000417
418 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000419 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
420 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000421 }
422
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000423 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000424 MethodTyInfo, EndLoc, Params);
425
426 if (ExplicitParams)
427 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000428
Douglas Gregor503384f2012-02-09 00:47:04 +0000429 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000430 ProcessDeclAttributes(CurScope, Method, ParamInfo);
431
Douglas Gregor503384f2012-02-09 00:47:04 +0000432 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000433 PushDeclContext(CurScope, Method);
434
435 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000436 LambdaScopeInfo *LSI
437 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
438 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000439 !Method->isConst());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000440
441 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000442 SourceLocation PrevCaptureLoc
443 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000444 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
445 C = Intro.Captures.begin(),
446 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000447 C != E;
448 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000449 if (C->Kind == LCK_This) {
450 // C++11 [expr.prim.lambda]p8:
451 // An identifier or this shall not appear more than once in a
452 // lambda-capture.
453 if (LSI->isCXXThisCaptured()) {
454 Diag(C->Loc, diag::err_capture_more_than_once)
455 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000456 << SourceRange(LSI->getCXXThisCapture().getLocation())
457 << FixItHint::CreateRemoval(
458 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000459 continue;
460 }
461
462 // C++11 [expr.prim.lambda]p8:
463 // If a lambda-capture includes a capture-default that is =, the
464 // lambda-capture shall not contain this [...].
465 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000466 Diag(C->Loc, diag::err_this_capture_with_copy_default)
467 << FixItHint::CreateRemoval(
468 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000469 continue;
470 }
471
472 // C++11 [expr.prim.lambda]p12:
473 // If this is captured by a local lambda expression, its nearest
474 // enclosing function shall be a non-static member function.
475 QualType ThisCaptureType = getCurrentThisType();
476 if (ThisCaptureType.isNull()) {
477 Diag(C->Loc, diag::err_this_capture) << true;
478 continue;
479 }
480
481 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
482 continue;
483 }
484
485 assert(C->Id && "missing identifier for capture");
486
487 // C++11 [expr.prim.lambda]p8:
488 // If a lambda-capture includes a capture-default that is &, the
489 // identifiers in the lambda-capture shall not be preceded by &.
490 // If a lambda-capture includes a capture-default that is =, [...]
491 // each identifier it contains shall be preceded by &.
492 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000493 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
494 << FixItHint::CreateRemoval(
495 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000496 continue;
497 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000498 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
499 << FixItHint::CreateRemoval(
500 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000501 continue;
502 }
503
504 DeclarationNameInfo Name(C->Id, C->Loc);
505 LookupResult R(*this, Name, LookupOrdinaryName);
506 LookupName(R, CurScope);
507 if (R.isAmbiguous())
508 continue;
509 if (R.empty()) {
510 // FIXME: Disable corrections that would add qualification?
511 CXXScopeSpec ScopeSpec;
512 DeclFilterCCC<VarDecl> Validator;
513 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
514 continue;
515 }
516
517 // C++11 [expr.prim.lambda]p10:
518 // The identifiers in a capture-list are looked up using the usual rules
519 // for unqualified name lookup (3.4.1); each such lookup shall find a
520 // variable with automatic storage duration declared in the reaching
521 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000522 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000523 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000524 VarDecl *Var = R.getAsSingle<VarDecl>();
525 if (!Var) {
526 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
527 continue;
528 }
529
Eli Friedman9cd5b242012-09-18 21:11:30 +0000530 // Ignore invalid decls; they'll just confuse the code later.
531 if (Var->isInvalidDecl())
532 continue;
533
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000534 if (!Var->hasLocalStorage()) {
535 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
536 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
537 continue;
538 }
539
540 // C++11 [expr.prim.lambda]p8:
541 // An identifier or this shall not appear more than once in a
542 // lambda-capture.
543 if (LSI->isCaptured(Var)) {
544 Diag(C->Loc, diag::err_capture_more_than_once)
545 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000546 << SourceRange(LSI->getCapture(Var).getLocation())
547 << FixItHint::CreateRemoval(
548 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000549 continue;
550 }
551
Douglas Gregora7365242012-02-14 19:27:52 +0000552 // C++11 [expr.prim.lambda]p23:
553 // A capture followed by an ellipsis is a pack expansion (14.5.3).
554 SourceLocation EllipsisLoc;
555 if (C->EllipsisLoc.isValid()) {
556 if (Var->isParameterPack()) {
557 EllipsisLoc = C->EllipsisLoc;
558 } else {
559 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
560 << SourceRange(C->Loc);
561
562 // Just ignore the ellipsis.
563 }
564 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000565 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000566 }
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
Richard Smith612409e2012-07-25 03:56:55 +0000574 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
575
Douglas Gregorc6889e72012-02-14 22:28:59 +0000576 // Add lambda parameters into scope.
577 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000578
Douglas Gregordfca6f52012-02-13 22:00:16 +0000579 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000580 // cleanups from the enclosing full-expression.
581 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582}
583
Douglas Gregordfca6f52012-02-13 22:00:16 +0000584void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
585 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000586 // Leave the expression-evaluation context.
587 DiscardCleanupsInEvaluationContext();
588 PopExpressionEvaluationContext();
589
590 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000591 if (!IsInstantiation)
592 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000593
594 // Finalize the lambda.
595 LambdaScopeInfo *LSI = getCurLambda();
596 CXXRecordDecl *Class = LSI->Lambda;
597 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000598 SmallVector<Decl*, 4> Fields;
599 for (RecordDecl::field_iterator i = Class->field_begin(),
600 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000601 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000602 ActOnFields(0, Class->getLocation(), Class, Fields,
603 SourceLocation(), SourceLocation(), 0);
604 CheckCompletedCXXClass(Class);
605
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000606 PopFunctionScopeInfo();
607}
608
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000609/// \brief Add a lambda's conversion to function pointer, as described in
610/// C++11 [expr.prim.lambda]p6.
611static void addFunctionPointerConversion(Sema &S,
612 SourceRange IntroducerRange,
613 CXXRecordDecl *Class,
614 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000615 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000616 const FunctionProtoType *Proto
617 = CallOperator->getType()->getAs<FunctionProtoType>();
618 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000619 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000620 {
621 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
622 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000623 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
624 Proto->arg_type_begin(),
625 Proto->getNumArgs(),
626 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000627 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
628 }
629
630 FunctionProtoType::ExtProtoInfo ExtInfo;
631 ExtInfo.TypeQuals = Qualifiers::Const;
632 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
633
634 SourceLocation Loc = IntroducerRange.getBegin();
635 DeclarationName Name
636 = S.Context.DeclarationNames.getCXXConversionFunctionName(
637 S.Context.getCanonicalType(FunctionPtrTy));
638 DeclarationNameLoc NameLoc;
639 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
640 Loc);
641 CXXConversionDecl *Conversion
642 = CXXConversionDecl::Create(S.Context, Class, Loc,
643 DeclarationNameInfo(Name, Loc, NameLoc),
644 ConvTy,
645 S.Context.getTrivialTypeSourceInfo(ConvTy,
646 Loc),
647 /*isInline=*/false, /*isExplicit=*/false,
648 /*isConstexpr=*/false,
649 CallOperator->getBody()->getLocEnd());
650 Conversion->setAccess(AS_public);
651 Conversion->setImplicit(true);
652 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000653
654 // Add a non-static member function "__invoke" that will be the result of
655 // the conversion.
656 Name = &S.Context.Idents.get("__invoke");
657 CXXMethodDecl *Invoke
658 = CXXMethodDecl::Create(S.Context, Class, Loc,
659 DeclarationNameInfo(Name, Loc), FunctionTy,
660 CallOperator->getTypeSourceInfo(),
661 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
662 /*IsConstexpr=*/false,
663 CallOperator->getBody()->getLocEnd());
664 SmallVector<ParmVarDecl *, 4> InvokeParams;
665 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
666 ParmVarDecl *From = CallOperator->getParamDecl(I);
667 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
668 From->getLocStart(),
669 From->getLocation(),
670 From->getIdentifier(),
671 From->getType(),
672 From->getTypeSourceInfo(),
673 From->getStorageClass(),
674 From->getStorageClassAsWritten(),
675 /*DefaultArg=*/0));
676 }
677 Invoke->setParams(InvokeParams);
678 Invoke->setAccess(AS_private);
679 Invoke->setImplicit(true);
680 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000681}
682
Douglas Gregorc2956e52012-02-15 22:08:38 +0000683/// \brief Add a lambda's conversion to block pointer.
684static void addBlockPointerConversion(Sema &S,
685 SourceRange IntroducerRange,
686 CXXRecordDecl *Class,
687 CXXMethodDecl *CallOperator) {
688 const FunctionProtoType *Proto
689 = CallOperator->getType()->getAs<FunctionProtoType>();
690 QualType BlockPtrTy;
691 {
692 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
693 ExtInfo.TypeQuals = 0;
694 QualType FunctionTy
695 = S.Context.getFunctionType(Proto->getResultType(),
696 Proto->arg_type_begin(),
697 Proto->getNumArgs(),
698 ExtInfo);
699 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
700 }
701
702 FunctionProtoType::ExtProtoInfo ExtInfo;
703 ExtInfo.TypeQuals = Qualifiers::Const;
704 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
705
706 SourceLocation Loc = IntroducerRange.getBegin();
707 DeclarationName Name
708 = S.Context.DeclarationNames.getCXXConversionFunctionName(
709 S.Context.getCanonicalType(BlockPtrTy));
710 DeclarationNameLoc NameLoc;
711 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
712 CXXConversionDecl *Conversion
713 = CXXConversionDecl::Create(S.Context, Class, Loc,
714 DeclarationNameInfo(Name, Loc, NameLoc),
715 ConvTy,
716 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
717 /*isInline=*/false, /*isExplicit=*/false,
718 /*isConstexpr=*/false,
719 CallOperator->getBody()->getLocEnd());
720 Conversion->setAccess(AS_public);
721 Conversion->setImplicit(true);
722 Class->addDecl(Conversion);
723}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000724
Douglas Gregordfca6f52012-02-13 22:00:16 +0000725ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000726 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000727 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000728 // Collect information from the lambda scope.
729 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
730 llvm::SmallVector<Expr *, 4> CaptureInits;
731 LambdaCaptureDefault CaptureDefault;
732 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000733 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000734 SourceRange IntroducerRange;
735 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000736 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000737 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000738 bool ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000739 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
740 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000741 {
742 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000743 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000744 Class = LSI->Lambda;
745 IntroducerRange = LSI->IntroducerRange;
746 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000747 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000748 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000749 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000750 ArrayIndexVars.swap(LSI->ArrayIndexVars);
751 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
752
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000753 // Translate captures.
754 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
755 LambdaScopeInfo::Capture From = LSI->Captures[I];
756 assert(!From.isBlockCapture() && "Cannot capture __block variables");
757 bool IsImplicit = I >= LSI->NumExplicitCaptures;
758
759 // Handle 'this' capture.
760 if (From.isThisCapture()) {
761 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
762 IsImplicit,
763 LCK_This));
764 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
765 getCurrentThisType(),
766 /*isImplicit=*/true));
767 continue;
768 }
769
770 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000771 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
772 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000773 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000774 CaptureInits.push_back(From.getCopyExpr());
775 }
776
777 switch (LSI->ImpCaptureStyle) {
778 case CapturingScopeInfo::ImpCap_None:
779 CaptureDefault = LCD_None;
780 break;
781
782 case CapturingScopeInfo::ImpCap_LambdaByval:
783 CaptureDefault = LCD_ByCopy;
784 break;
785
786 case CapturingScopeInfo::ImpCap_LambdaByref:
787 CaptureDefault = LCD_ByRef;
788 break;
789
790 case CapturingScopeInfo::ImpCap_Block:
791 llvm_unreachable("block capture in lambda");
792 break;
793 }
794
Douglas Gregor54042f12012-02-09 10:18:50 +0000795 // C++11 [expr.prim.lambda]p4:
796 // If a lambda-expression does not include a
797 // trailing-return-type, it is as if the trailing-return-type
798 // denotes the following type:
799 // FIXME: Assumes current resolution to core issue 975.
800 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000801 deduceClosureReturnType(*LSI);
802
Douglas Gregor54042f12012-02-09 10:18:50 +0000803 // - if there are no return statements in the
804 // compound-statement, or all return statements return
805 // either an expression of type void or no expression or
806 // braced-init-list, the type void;
807 if (LSI->ReturnType.isNull()) {
808 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +0000809 }
810
811 // Create a function type with the inferred return type.
812 const FunctionProtoType *Proto
813 = CallOperator->getType()->getAs<FunctionProtoType>();
814 QualType FunctionTy
815 = Context.getFunctionType(LSI->ReturnType,
816 Proto->arg_type_begin(),
817 Proto->getNumArgs(),
818 Proto->getExtProtoInfo());
819 CallOperator->setType(FunctionTy);
820 }
821
Douglas Gregor215e4e12012-02-12 17:34:23 +0000822 // C++ [expr.prim.lambda]p7:
823 // The lambda-expression's compound-statement yields the
824 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000825 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000826 CallOperator->setLexicalDeclContext(Class);
827 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000828 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000829
Douglas Gregorb5559712012-02-10 16:13:20 +0000830 // C++11 [expr.prim.lambda]p6:
831 // The closure type for a lambda-expression with no lambda-capture
832 // has a public non-virtual non-explicit const conversion function
833 // to pointer to function having the same parameter and return
834 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000835 if (Captures.empty() && CaptureDefault == LCD_None)
836 addFunctionPointerConversion(*this, IntroducerRange, Class,
837 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000838
Douglas Gregorc2956e52012-02-15 22:08:38 +0000839 // Objective-C++:
840 // The closure type for a lambda-expression has a public non-virtual
841 // non-explicit const conversion function to a block pointer having the
842 // same parameter and return types as the closure type's function call
843 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000844 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000845 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
846
Douglas Gregorb5559712012-02-10 16:13:20 +0000847 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000848 SmallVector<Decl*, 4> Fields;
849 for (RecordDecl::field_iterator i = Class->field_begin(),
850 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000851 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000852 ActOnFields(0, Class->getLocation(), Class, Fields,
853 SourceLocation(), SourceLocation(), 0);
854 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000855 }
856
Douglas Gregor503384f2012-02-09 00:47:04 +0000857 if (LambdaExprNeedsCleanups)
858 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000859
Douglas Gregore2c59132012-02-09 08:14:43 +0000860 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
861 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000862 ExplicitParams, ExplicitResultType,
863 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +0000864 ArrayIndexStarts, Body->getLocEnd(),
865 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +0000866
867 // C++11 [expr.prim.lambda]p2:
868 // A lambda-expression shall not appear in an unevaluated operand
869 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000870 if (!CurContext->isDependentContext()) {
871 switch (ExprEvalContexts.back().Context) {
872 case Unevaluated:
873 // We don't actually diagnose this case immediately, because we
874 // could be within a context where we might find out later that
875 // the expression is potentially evaluated (e.g., for typeid).
876 ExprEvalContexts.back().Lambdas.push_back(Lambda);
877 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000878
Douglas Gregord5387e82012-02-14 00:00:48 +0000879 case ConstantEvaluated:
880 case PotentiallyEvaluated:
881 case PotentiallyEvaluatedIfUsed:
882 break;
883 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000884 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000885
Douglas Gregor503384f2012-02-09 00:47:04 +0000886 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000887}
Eli Friedman23f02672012-03-01 04:01:32 +0000888
889ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
890 SourceLocation ConvLocation,
891 CXXConversionDecl *Conv,
892 Expr *Src) {
893 // Make sure that the lambda call operator is marked used.
894 CXXRecordDecl *Lambda = Conv->getParent();
895 CXXMethodDecl *CallOperator
896 = cast<CXXMethodDecl>(
897 *Lambda->lookup(
898 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
899 CallOperator->setReferenced();
900 CallOperator->setUsed();
901
902 ExprResult Init = PerformCopyInitialization(
903 InitializedEntity::InitializeBlock(ConvLocation,
904 Src->getType(),
905 /*NRVO=*/false),
906 CurrentLocation, Src);
907 if (!Init.isInvalid())
908 Init = ActOnFinishFullExpr(Init.take());
909
910 if (Init.isInvalid())
911 return ExprError();
912
913 // Create the new block to be returned.
914 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
915
916 // Set the type information.
917 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
918 Block->setIsVariadic(CallOperator->isVariadic());
919 Block->setBlockMissingReturnType(false);
920
921 // Add parameters.
922 SmallVector<ParmVarDecl *, 4> BlockParams;
923 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
924 ParmVarDecl *From = CallOperator->getParamDecl(I);
925 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
926 From->getLocStart(),
927 From->getLocation(),
928 From->getIdentifier(),
929 From->getType(),
930 From->getTypeSourceInfo(),
931 From->getStorageClass(),
932 From->getStorageClassAsWritten(),
933 /*DefaultArg=*/0));
934 }
935 Block->setParams(BlockParams);
936
937 Block->setIsConversionFromLambda(true);
938
939 // Add capture. The capture uses a fake variable, which doesn't correspond
940 // to any actual memory location. However, the initializer copy-initializes
941 // the lambda object.
942 TypeSourceInfo *CapVarTSI =
943 Context.getTrivialTypeSourceInfo(Src->getType());
944 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
945 ConvLocation, 0,
946 Src->getType(), CapVarTSI,
947 SC_None, SC_None);
948 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
949 /*Nested=*/false, /*Copy=*/Init.take());
950 Block->setCaptures(Context, &Capture, &Capture + 1,
951 /*CapturesCXXThis=*/false);
952
953 // Add a fake function body to the block. IR generation is responsible
954 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +0000955 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +0000956
957 // Create the block literal expression.
958 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
959 ExprCleanupObjects.push_back(Block);
960 ExprNeedsCleanups = true;
961
962 return BuildBlock;
963}