blob: 569bfdfce22173527933f1699d950bd2d2f24729 [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"
Richard Smith0d8e9642013-05-16 06:20:58 +000023#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000024using namespace clang;
25using namespace sema;
26
Douglas Gregorf4b7de12012-02-21 19:11:17 +000027CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000028 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000029 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000030 DeclContext *DC = CurContext;
31 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
32 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000033
Douglas Gregore2a7ad02012-02-08 21:18:48 +000034 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000035 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000036 IntroducerRange.getBegin(),
37 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000038 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000039
40 return Class;
41}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000042
Douglas Gregorf54486a2012-04-04 17:40:10 +000043/// \brief Determine whether the given context is or is enclosed in an inline
44/// function.
45static bool isInInlineFunction(const DeclContext *DC) {
46 while (!DC->isFileContext()) {
47 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
48 if (FD->isInlined())
49 return true;
50
51 DC = DC->getLexicalParent();
52 }
53
54 return false;
55}
56
Eli Friedman07369dd2013-07-01 20:22:57 +000057MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000058Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000059 Decl *&ManglingContextDecl) {
60 // Compute the context for allocating mangling numbers in the current
61 // expression, if the ABI requires them.
62 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
63
64 enum ContextKind {
65 Normal,
66 DefaultArgument,
67 DataMember,
68 StaticDataMember
69 } Kind = Normal;
70
71 // Default arguments of member function parameters that appear in a class
72 // definition, as well as the initializers of data members, receive special
73 // treatment. Identify them.
74 if (ManglingContextDecl) {
75 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
76 if (const DeclContext *LexicalDC
77 = Param->getDeclContext()->getLexicalParent())
78 if (LexicalDC->isRecord())
79 Kind = DefaultArgument;
80 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
81 if (Var->getDeclContext()->isRecord())
82 Kind = StaticDataMember;
83 } else if (isa<FieldDecl>(ManglingContextDecl)) {
84 Kind = DataMember;
85 }
86 }
87
88 // Itanium ABI [5.1.7]:
89 // In the following contexts [...] the one-definition rule requires closure
90 // types in different translation units to "correspond":
91 bool IsInNonspecializedTemplate =
92 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
93 switch (Kind) {
94 case Normal:
95 // -- the bodies of non-exported nonspecialized template functions
96 // -- the bodies of inline functions
97 if ((IsInNonspecializedTemplate &&
98 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
99 isInInlineFunction(CurContext)) {
100 ManglingContextDecl = 0;
101 return &Context.getManglingNumberContext(DC);
102 }
103
104 ManglingContextDecl = 0;
105 return 0;
106
107 case StaticDataMember:
108 // -- the initializers of nonspecialized static members of template classes
109 if (!IsInNonspecializedTemplate) {
110 ManglingContextDecl = 0;
111 return 0;
112 }
113 // Fall through to get the current context.
114
115 case DataMember:
116 // -- the in-class initializers of class members
117 case DefaultArgument:
118 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000119 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000120 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000121
122 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000123}
124
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000125MangleNumberingContext &
126Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
127 ASTContext &Ctx) {
128 assert(ManglingContextDecl && "Need to have a context declaration");
129 if (!MangleNumbering)
130 MangleNumbering = Ctx.createMangleNumberingContext();
131 return *MangleNumbering;
132}
133
Faisal Valifad9e132013-09-26 19:54:12 +0000134static inline TemplateParameterList *
135getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
136 if (LSI->GLTemplateParameterList)
137 return LSI->GLTemplateParameterList;
138 else if (LSI->AutoTemplateParams.size()) {
139 SourceRange IntroRange = LSI->IntroducerRange;
140 SourceLocation LAngleLoc = IntroRange.getBegin();
141 SourceLocation RAngleLoc = IntroRange.getEnd();
142 LSI->GLTemplateParameterList =
143 TemplateParameterList::Create(SemaRef.Context,
144 /* Template kw loc */ SourceLocation(),
145 LAngleLoc,
146 (NamedDecl**)LSI->AutoTemplateParams.data(),
147 LSI->AutoTemplateParams.size(), RAngleLoc);
148 }
149 return LSI->GLTemplateParameterList;
150}
151
152
Douglas Gregordfca6f52012-02-13 22:00:16 +0000153CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith41d09582013-09-25 05:02:54 +0000154 SourceRange IntroducerRange,
155 TypeSourceInfo *MethodTypeInfo,
156 SourceLocation EndLoc,
157 ArrayRef<ParmVarDecl *> Params) {
158 QualType MethodType = MethodTypeInfo->getType();
Faisal Valifad9e132013-09-26 19:54:12 +0000159 TemplateParameterList *TemplateParams =
160 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
161 // If a lambda appears in a dependent context or is a generic lambda (has
162 // template parameters) and has an 'auto' return type, deduce it to a
163 // dependent type.
164 if (Class->isDependentContext() || TemplateParams) {
Richard Smith41d09582013-09-25 05:02:54 +0000165 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
166 QualType Result = FPT->getResultType();
167 if (Result->isUndeducedType()) {
168 Result = SubstAutoType(Result, Context.DependentTy);
169 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
170 FPT->getExtProtoInfo());
171 }
172 }
173
Douglas Gregordfca6f52012-02-13 22:00:16 +0000174 // C++11 [expr.prim.lambda]p5:
175 // The closure type for a lambda-expression has a public inline function
176 // call operator (13.5.4) whose parameters and return type are described by
177 // the lambda-expression's parameter-declaration-clause and
178 // trailing-return-type respectively.
179 DeclarationName MethodName
180 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
181 DeclarationNameLoc MethodNameLoc;
182 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
183 = IntroducerRange.getBegin().getRawEncoding();
184 MethodNameLoc.CXXOperatorName.EndOpNameLoc
185 = IntroducerRange.getEnd().getRawEncoding();
186 CXXMethodDecl *Method
187 = CXXMethodDecl::Create(Context, Class, EndLoc,
188 DeclarationNameInfo(MethodName,
189 IntroducerRange.getBegin(),
190 MethodNameLoc),
Richard Smith41d09582013-09-25 05:02:54 +0000191 MethodType, MethodTypeInfo,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000192 SC_None,
193 /*isInline=*/true,
194 /*isConstExpr=*/false,
195 EndLoc);
196 Method->setAccess(AS_public);
197
198 // Temporarily set the lexical declaration context to the current
199 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000200 Method->setLexicalDeclContext(CurContext);
Faisal Valifad9e132013-09-26 19:54:12 +0000201 // Create a function template if we have a template parameter list
202 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
203 FunctionTemplateDecl::Create(Context, Class,
204 Method->getLocation(), MethodName,
205 TemplateParams,
206 Method) : 0;
207 if (TemplateMethod) {
208 TemplateMethod->setLexicalDeclContext(CurContext);
209 TemplateMethod->setAccess(AS_public);
210 Method->setDescribedFunctionTemplate(TemplateMethod);
211 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000212
Douglas Gregorc6889e72012-02-14 22:28:59 +0000213 // Add parameters.
214 if (!Params.empty()) {
215 Method->setParams(Params);
216 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
217 const_cast<ParmVarDecl **>(Params.end()),
218 /*CheckParameterNames=*/false);
219
220 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
221 PEnd = Method->param_end();
222 P != PEnd; ++P)
223 (*P)->setOwningFunction(Method);
224 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000225
Eli Friedman07369dd2013-07-01 20:22:57 +0000226 Decl *ManglingContextDecl;
227 if (MangleNumberingContext *MCtx =
228 getCurrentMangleNumberContext(Class->getDeclContext(),
229 ManglingContextDecl)) {
230 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
231 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000232 }
233
Douglas Gregordfca6f52012-02-13 22:00:16 +0000234 return Method;
235}
236
Faisal Valifad9e132013-09-26 19:54:12 +0000237void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
238 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000239 SourceRange IntroducerRange,
240 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000241 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000242 bool ExplicitParams,
243 bool ExplicitResultType,
244 bool Mutable) {
Faisal Valifad9e132013-09-26 19:54:12 +0000245 LSI->CallOperator = CallOperator;
246 LSI->Lambda = CallOperator->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000247 if (CaptureDefault == LCD_ByCopy)
248 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
249 else if (CaptureDefault == LCD_ByRef)
250 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000251 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000252 LSI->IntroducerRange = IntroducerRange;
253 LSI->ExplicitParams = ExplicitParams;
254 LSI->Mutable = Mutable;
255
256 if (ExplicitResultType) {
257 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000258
259 if (!LSI->ReturnType->isDependentType() &&
260 !LSI->ReturnType->isVoidType()) {
261 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
262 diag::err_lambda_incomplete_result)) {
263 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000264 }
265 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000266 } else {
267 LSI->HasImplicitReturnType = true;
268 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000269}
270
271void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
272 LSI->finishedExplicitCaptures();
273}
274
Douglas Gregorc6889e72012-02-14 22:28:59 +0000275void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000276 // Introduce our parameters into the function scope
277 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
278 p < NumParams; ++p) {
279 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000280
281 // If this has an identifier, add it to the scope stack.
282 if (CurScope && Param->getIdentifier()) {
283 CheckShadow(CurScope, Param);
284
285 PushOnScopeChains(Param, CurScope);
286 }
287 }
288}
289
John McCall41d01642013-03-09 00:54:31 +0000290/// If this expression is an enumerator-like expression of some type
291/// T, return the type T; otherwise, return null.
292///
293/// Pointer comparisons on the result here should always work because
294/// it's derived from either the parent of an EnumConstantDecl
295/// (i.e. the definition) or the declaration returned by
296/// EnumType::getDecl() (i.e. the definition).
297static EnumDecl *findEnumForBlockReturn(Expr *E) {
298 // An expression is an enumerator-like expression of type T if,
299 // ignoring parens and parens-like expressions:
300 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000301
John McCall41d01642013-03-09 00:54:31 +0000302 // - it is an enumerator whose enum type is T or
303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
304 if (EnumConstantDecl *D
305 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
306 return cast<EnumDecl>(D->getDeclContext());
307 }
308 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000309 }
310
John McCall41d01642013-03-09 00:54:31 +0000311 // - it is a comma expression whose RHS is an enumerator-like
312 // expression of type T or
313 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
314 if (BO->getOpcode() == BO_Comma)
315 return findEnumForBlockReturn(BO->getRHS());
316 return 0;
317 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000318
John McCall41d01642013-03-09 00:54:31 +0000319 // - it is a statement-expression whose value expression is an
320 // enumerator-like expression of type T or
321 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
322 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
323 return findEnumForBlockReturn(last);
324 return 0;
325 }
326
327 // - it is a ternary conditional operator (not the GNU ?:
328 // extension) whose second and third operands are
329 // enumerator-like expressions of type T or
330 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
331 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
332 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
333 return ED;
334 return 0;
335 }
336
337 // (implicitly:)
338 // - it is an implicit integral conversion applied to an
339 // enumerator-like expression of type T or
340 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000341 // We can sometimes see integral conversions in valid
342 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000343 if (ICE->getCastKind() == CK_IntegralCast)
344 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000345
346 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000347 }
348
349 // - it is an expression of that formal enum type.
350 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
351 return ET->getDecl();
352 }
353
354 // Otherwise, nope.
355 return 0;
356}
357
358/// Attempt to find a type T for which the returned expression of the
359/// given statement is an enumerator-like expression of that type.
360static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
361 if (Expr *retValue = ret->getRetValue())
362 return findEnumForBlockReturn(retValue);
363 return 0;
364}
365
366/// Attempt to find a common type T for which all of the returned
367/// expressions in a block are enumerator-like expressions of that
368/// type.
369static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
370 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
371
372 // Try to find one for the first return.
373 EnumDecl *ED = findEnumForBlockReturn(*i);
374 if (!ED) return 0;
375
376 // Check that the rest of the returns have the same enum.
377 for (++i; i != e; ++i) {
378 if (findEnumForBlockReturn(*i) != ED)
379 return 0;
380 }
381
382 // Never infer an anonymous enum type.
383 if (!ED->hasNameForLinkage()) return 0;
384
385 return ED;
386}
387
388/// Adjust the given return statements so that they formally return
389/// the given type. It should require, at most, an IntegralCast.
390static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
391 QualType returnType) {
392 for (ArrayRef<ReturnStmt*>::iterator
393 i = returns.begin(), e = returns.end(); i != e; ++i) {
394 ReturnStmt *ret = *i;
395 Expr *retValue = ret->getRetValue();
396 if (S.Context.hasSameType(retValue->getType(), returnType))
397 continue;
398
399 // Right now we only support integral fixup casts.
400 assert(returnType->isIntegralOrUnscopedEnumerationType());
401 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
402
403 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
404
405 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
406 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
407 E, /*base path*/ 0, VK_RValue);
408 if (cleanups) {
409 cleanups->setSubExpr(E);
410 } else {
411 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000412 }
413 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000414}
415
416void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000417 assert(CSI.HasImplicitReturnType);
Faisal Valifad9e132013-09-26 19:54:12 +0000418 // If it was ever a placeholder, it had to been deduced to DependentTy.
419 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000420
John McCall41d01642013-03-09 00:54:31 +0000421 // C++ Core Issue #975, proposed resolution:
422 // If a lambda-expression does not include a trailing-return-type,
423 // it is as if the trailing-return-type denotes the following type:
424 // - if there are no return statements in the compound-statement,
425 // or all return statements return either an expression of type
426 // void or no expression or braced-init-list, the type void;
427 // - otherwise, if all return statements return an expression
428 // and the types of the returned expressions after
429 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
430 // array-to-pointer conversion (4.2 [conv.array]), and
431 // function-to-pointer conversion (4.3 [conv.func]) are the
432 // same, that common type;
433 // - otherwise, the program is ill-formed.
434 //
435 // In addition, in blocks in non-C++ modes, if all of the return
436 // statements are enumerator-like expressions of some type T, where
437 // T has a name for linkage, then we infer the return type of the
438 // block to be that type.
439
Jordan Rose7dd900e2012-07-02 21:19:23 +0000440 // First case: no return statements, implicit void return type.
441 ASTContext &Ctx = getASTContext();
442 if (CSI.Returns.empty()) {
443 // It's possible there were simply no /valid/ return statements.
444 // In this case, the first one we found may have at least given us a type.
445 if (CSI.ReturnType.isNull())
446 CSI.ReturnType = Ctx.VoidTy;
447 return;
448 }
449
450 // Second case: at least one return statement has dependent type.
451 // Delay type checking until instantiation.
452 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000453 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000454 return;
455
John McCall41d01642013-03-09 00:54:31 +0000456 // Try to apply the enum-fuzz rule.
457 if (!getLangOpts().CPlusPlus) {
458 assert(isa<BlockScopeInfo>(CSI));
459 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
460 if (ED) {
461 CSI.ReturnType = Context.getTypeDeclType(ED);
462 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
463 return;
464 }
465 }
466
Jordan Rose7dd900e2012-07-02 21:19:23 +0000467 // Third case: only one return statement. Don't bother doing extra work!
468 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
469 E = CSI.Returns.end();
470 if (I+1 == E)
471 return;
472
473 // General case: many return statements.
474 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000475
476 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000477 // Note that we've already done the required promotions as part of
478 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000479 for (; I != E; ++I) {
480 const ReturnStmt *RS = *I;
481 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000482
John McCall41d01642013-03-09 00:54:31 +0000483 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
484 if (Context.hasSameType(ReturnType, CSI.ReturnType))
485 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000486
John McCall41d01642013-03-09 00:54:31 +0000487 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
488 // TODO: It's possible that the *first* return is the divergent one.
489 Diag(RS->getLocStart(),
490 diag::err_typecheck_missing_return_type_incompatible)
491 << ReturnType << CSI.ReturnType
492 << isa<LambdaScopeInfo>(CSI);
493 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000494 }
495}
496
Richard Smith0d8e9642013-05-16 06:20:58 +0000497FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
498 IdentifierInfo *Id, Expr *InitExpr) {
499 LambdaScopeInfo *LSI = getCurLambda();
500
501 // C++1y [expr.prim.lambda]p11:
502 // The type of [the] member corresponds to the type of a hypothetical
503 // variable declaration of the form "auto init-capture;"
504 QualType DeductType = Context.getAutoDeductType();
505 TypeLocBuilder TLB;
506 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
507 if (ByRef) {
508 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
509 assert(!DeductType.isNull() && "can't build reference to auto");
510 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
511 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000512 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000513
514 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
515 Expr *Init = InitExpr;
516 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
517 if (Parens->getNumExprs() == 1) {
518 Init = Parens->getExpr(0);
519 InitKind = InitializationKind::CreateDirect(
520 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
521 } else {
522 // C++1y [dcl.spec.auto]p3:
523 // In an initializer of the form ( expression-list ), the
524 // expression-list shall be a single assignment-expression.
525 if (Parens->getNumExprs() == 0)
526 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
527 << Id;
528 else if (Parens->getNumExprs() > 1)
529 Diag(Parens->getExpr(1)->getLocStart(),
530 diag::err_init_capture_multiple_expressions)
531 << Id;
532 return 0;
533 }
534 } else if (isa<InitListExpr>(Init))
535 // We do not need to distinguish between direct-list-initialization
536 // and copy-list-initialization here, because we will always deduce
537 // std::initializer_list<T>, and direct- and copy-list-initialization
538 // always behave the same for such a type.
539 // FIXME: We should model whether an '=' was present.
540 InitKind = InitializationKind::CreateDirectList(Loc);
541 else
542 InitKind = InitializationKind::CreateCopy(Loc, Loc);
543 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000544 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000545 if (isa<InitListExpr>(Init))
546 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
547 << Id << Init->getSourceRange();
548 else
549 Diag(Loc, diag::err_init_capture_deduction_failure)
550 << Id << Init->getType() << Init->getSourceRange();
551 }
552 if (DeducedType.isNull())
553 return 0;
554
555 // [...] a non-static data member named by the identifier is declared in
556 // the closure type. This member is not a bit-field and not mutable.
557 // Core issue: the member is (probably...) public.
558 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000559 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000560 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
561 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
562 LSI->Lambda->addDecl(NewFD);
563
564 if (CurContext->isDependentContext()) {
565 LSI->addInitCapture(NewFD, InitExpr);
566 } else {
567 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
568 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
569 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
570 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
571 if (!InitResult.isInvalid())
572 LSI->addInitCapture(NewFD, InitResult.take());
573 }
574 }
575
576 return NewFD;
577}
578
Douglas Gregordfca6f52012-02-13 22:00:16 +0000579void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valifad9e132013-09-26 19:54:12 +0000580 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000581 // Determine if we're within a context where we know that the lambda will
582 // be dependent, because there are template parameters in scope.
583 bool KnownDependent = false;
Faisal Valifad9e132013-09-26 19:54:12 +0000584 LambdaScopeInfo *const LSI = getCurLambda();
585 assert(LSI && "LambdaScopeInfo should be on stack!");
586 TemplateParameterList *TemplateParams =
587 getGenericLambdaTemplateParameterList(LSI, *this);
588
589 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
590 // Since we have our own TemplateParams, so check if an outer scope
591 // has template params, only then are we in a dependent scope.
592 if (TemplateParams) {
593 TmplScope = TmplScope->getParent();
594 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
595 }
596 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000597 KnownDependent = true;
Faisal Valifad9e132013-09-26 19:54:12 +0000598 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000599 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000600 TypeSourceInfo *MethodTyInfo;
601 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000602 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000603 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000604 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000605 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000606 if (ParamInfo.getNumTypeObjects() == 0) {
607 // C++11 [expr.prim.lambda]p4:
608 // If a lambda-expression does not include a lambda-declarator, it is as
609 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000610 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
611 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000612 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000613 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000614 // C++1y [expr.prim.lambda]:
615 // The lambda return type is 'auto', which is replaced by the
616 // trailing-return type if provided and/or deduced from 'return'
617 // statements
618 // We don't do this before C++1y, because we don't support deduced return
619 // types there.
620 QualType DefaultTypeForNoTrailingReturn =
621 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
622 : Context.DependentTy;
623 QualType MethodTy =
624 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000625 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
626 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000627 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000628 EndLoc = Intro.Range.getEnd();
629 } else {
630 assert(ParamInfo.isFunctionDeclarator() &&
631 "lambda-declarator is a function");
632 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000633
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000634 // C++11 [expr.prim.lambda]p5:
635 // This function call operator is declared const (9.3.1) if and only if
636 // the lambda-expression's parameter-declaration-clause is not followed
637 // by mutable. It is neither virtual nor declared volatile. [...]
638 if (!FTI.hasMutableQualifier())
639 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000640
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000641 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000642 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000643 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000644
645 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000646
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000647 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
648 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
649 // Empty arg list, don't push any params.
650 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
651 } else {
652 Params.reserve(FTI.NumArgs);
653 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
654 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
655 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000656
657 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000658 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
659 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000660 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000661
662 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
663 KnownDependent);
664
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000665 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000666 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000667 if (ExplicitParams)
668 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000669
Bill Wendlingad017fa2012-12-20 19:22:21 +0000670 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000671 ProcessDeclAttributes(CurScope, Method, ParamInfo);
672
Douglas Gregor503384f2012-02-09 00:47:04 +0000673 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000674 PushDeclContext(CurScope, Method);
675
Faisal Valifad9e132013-09-26 19:54:12 +0000676 // Build the lambda scope.
677 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000678 Intro.Range,
679 Intro.Default, Intro.DefaultLoc,
680 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000681 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000682 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000683
684 // Distinct capture names, for diagnostics.
685 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
686
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000687 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000688 SourceLocation PrevCaptureLoc
689 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000690 for (SmallVectorImpl<LambdaCapture>::const_iterator
691 C = Intro.Captures.begin(),
692 E = Intro.Captures.end();
693 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000694 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000695 if (C->Kind == LCK_This) {
696 // C++11 [expr.prim.lambda]p8:
697 // An identifier or this shall not appear more than once in a
698 // lambda-capture.
699 if (LSI->isCXXThisCaptured()) {
700 Diag(C->Loc, diag::err_capture_more_than_once)
701 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000702 << SourceRange(LSI->getCXXThisCapture().getLocation())
703 << FixItHint::CreateRemoval(
704 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000705 continue;
706 }
707
708 // C++11 [expr.prim.lambda]p8:
709 // If a lambda-capture includes a capture-default that is =, the
710 // lambda-capture shall not contain this [...].
711 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000712 Diag(C->Loc, diag::err_this_capture_with_copy_default)
713 << FixItHint::CreateRemoval(
714 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000715 continue;
716 }
717
718 // C++11 [expr.prim.lambda]p12:
719 // If this is captured by a local lambda expression, its nearest
720 // enclosing function shall be a non-static member function.
721 QualType ThisCaptureType = getCurrentThisType();
722 if (ThisCaptureType.isNull()) {
723 Diag(C->Loc, diag::err_this_capture) << true;
724 continue;
725 }
726
727 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
728 continue;
729 }
730
Richard Smith0d8e9642013-05-16 06:20:58 +0000731 assert(C->Id && "missing identifier for capture");
732
Richard Smith0a664b82013-05-09 21:36:41 +0000733 if (C->Init.isInvalid())
734 continue;
735 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000736 // C++11 [expr.prim.lambda]p8:
737 // An identifier or this shall not appear more than once in a
738 // lambda-capture.
739 if (!CaptureNames.insert(C->Id))
740 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
741
742 if (C->Init.get()->containsUnexpandedParameterPack())
743 ContainsUnexpandedParameterPack = true;
744
745 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
746 C->Id, C->Init.take());
747 // C++1y [expr.prim.lambda]p11:
748 // Within the lambda-expression's lambda-declarator and
749 // compound-statement, the identifier in the init-capture
750 // hides any declaration of the same name in scopes enclosing
751 // the lambda-expression.
752 if (NewFD)
753 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000754 continue;
755 }
756
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000757 // C++11 [expr.prim.lambda]p8:
758 // If a lambda-capture includes a capture-default that is &, the
759 // identifiers in the lambda-capture shall not be preceded by &.
760 // If a lambda-capture includes a capture-default that is =, [...]
761 // each identifier it contains shall be preceded by &.
762 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000763 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
764 << FixItHint::CreateRemoval(
765 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000766 continue;
767 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000768 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
769 << FixItHint::CreateRemoval(
770 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000771 continue;
772 }
773
Richard Smith0d8e9642013-05-16 06:20:58 +0000774 // C++11 [expr.prim.lambda]p10:
775 // The identifiers in a capture-list are looked up using the usual
776 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000777 DeclarationNameInfo Name(C->Id, C->Loc);
778 LookupResult R(*this, Name, LookupOrdinaryName);
779 LookupName(R, CurScope);
780 if (R.isAmbiguous())
781 continue;
782 if (R.empty()) {
783 // FIXME: Disable corrections that would add qualification?
784 CXXScopeSpec ScopeSpec;
785 DeclFilterCCC<VarDecl> Validator;
786 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
787 continue;
788 }
789
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000790 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000791
792 // C++11 [expr.prim.lambda]p8:
793 // An identifier or this shall not appear more than once in a
794 // lambda-capture.
795 if (!CaptureNames.insert(C->Id)) {
796 if (Var && LSI->isCaptured(Var)) {
797 Diag(C->Loc, diag::err_capture_more_than_once)
798 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
799 << FixItHint::CreateRemoval(
800 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
801 } else
802 // Previous capture was an init-capture: no fixit.
803 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
804 continue;
805 }
806
807 // C++11 [expr.prim.lambda]p10:
808 // [...] each such lookup shall find a variable with automatic storage
809 // duration declared in the reaching scope of the local lambda expression.
810 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000811 if (!Var) {
812 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
813 continue;
814 }
815
Eli Friedman9cd5b242012-09-18 21:11:30 +0000816 // Ignore invalid decls; they'll just confuse the code later.
817 if (Var->isInvalidDecl())
818 continue;
819
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000820 if (!Var->hasLocalStorage()) {
821 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
822 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
823 continue;
824 }
825
Douglas Gregora7365242012-02-14 19:27:52 +0000826 // C++11 [expr.prim.lambda]p23:
827 // A capture followed by an ellipsis is a pack expansion (14.5.3).
828 SourceLocation EllipsisLoc;
829 if (C->EllipsisLoc.isValid()) {
830 if (Var->isParameterPack()) {
831 EllipsisLoc = C->EllipsisLoc;
832 } else {
833 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
834 << SourceRange(C->Loc);
835
836 // Just ignore the ellipsis.
837 }
838 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000839 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000840 }
841
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000842 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
843 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000844 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000845 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000846 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000847
Richard Smith612409e2012-07-25 03:56:55 +0000848 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
849
Douglas Gregorc6889e72012-02-14 22:28:59 +0000850 // Add lambda parameters into scope.
851 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000852
Douglas Gregordfca6f52012-02-13 22:00:16 +0000853 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000854 // cleanups from the enclosing full-expression.
855 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000856}
857
Douglas Gregordfca6f52012-02-13 22:00:16 +0000858void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
859 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000860 // Leave the expression-evaluation context.
861 DiscardCleanupsInEvaluationContext();
862 PopExpressionEvaluationContext();
863
864 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000865 if (!IsInstantiation)
866 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000867
868 // Finalize the lambda.
869 LambdaScopeInfo *LSI = getCurLambda();
870 CXXRecordDecl *Class = LSI->Lambda;
871 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000872 SmallVector<Decl*, 4> Fields;
873 for (RecordDecl::field_iterator i = Class->field_begin(),
874 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000875 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000876 ActOnFields(0, Class->getLocation(), Class, Fields,
877 SourceLocation(), SourceLocation(), 0);
878 CheckCompletedCXXClass(Class);
879
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000880 PopFunctionScopeInfo();
881}
882
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000883/// \brief Add a lambda's conversion to function pointer, as described in
884/// C++11 [expr.prim.lambda]p6.
885static void addFunctionPointerConversion(Sema &S,
886 SourceRange IntroducerRange,
887 CXXRecordDecl *Class,
888 CXXMethodDecl *CallOperator) {
Faisal Valifad9e132013-09-26 19:54:12 +0000889 // FIXME: The conversion operator needs to be fixed for generic lambdas.
890 if (Class->isGenericLambda()) return;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000891 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000892 const FunctionProtoType *Proto
893 = CallOperator->getType()->getAs<FunctionProtoType>();
894 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000895 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000896 {
897 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000898 CallingConv CC = S.Context.getDefaultCallingConvention(
899 Proto->isVariadic(), /*IsCXXMethod=*/false);
900 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000901 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000902 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
903 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000904 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
905 }
Reid Kleckneref072032013-08-27 23:08:25 +0000906
907 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
908 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000909 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000910 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
911
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000912 SourceLocation Loc = IntroducerRange.getBegin();
913 DeclarationName Name
914 = S.Context.DeclarationNames.getCXXConversionFunctionName(
915 S.Context.getCanonicalType(FunctionPtrTy));
916 DeclarationNameLoc NameLoc;
917 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
918 Loc);
919 CXXConversionDecl *Conversion
920 = CXXConversionDecl::Create(S.Context, Class, Loc,
921 DeclarationNameInfo(Name, Loc, NameLoc),
922 ConvTy,
923 S.Context.getTrivialTypeSourceInfo(ConvTy,
924 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000925 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000926 /*isConstexpr=*/false,
927 CallOperator->getBody()->getLocEnd());
928 Conversion->setAccess(AS_public);
929 Conversion->setImplicit(true);
930 Class->addDecl(Conversion);
Faisal Valifad9e132013-09-26 19:54:12 +0000931 // Add a non-static member function that will be the result of
932 // the conversion with a certain unique ID.
933 Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000934 CXXMethodDecl *Invoke
935 = CXXMethodDecl::Create(S.Context, Class, Loc,
936 DeclarationNameInfo(Name, Loc), FunctionTy,
937 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000938 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000939 /*IsConstexpr=*/false,
940 CallOperator->getBody()->getLocEnd());
941 SmallVector<ParmVarDecl *, 4> InvokeParams;
942 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
943 ParmVarDecl *From = CallOperator->getParamDecl(I);
944 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
945 From->getLocStart(),
946 From->getLocation(),
947 From->getIdentifier(),
948 From->getType(),
949 From->getTypeSourceInfo(),
950 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000951 /*DefaultArg=*/0));
952 }
953 Invoke->setParams(InvokeParams);
954 Invoke->setAccess(AS_private);
955 Invoke->setImplicit(true);
956 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000957}
958
Douglas Gregorc2956e52012-02-15 22:08:38 +0000959/// \brief Add a lambda's conversion to block pointer.
960static void addBlockPointerConversion(Sema &S,
961 SourceRange IntroducerRange,
962 CXXRecordDecl *Class,
963 CXXMethodDecl *CallOperator) {
964 const FunctionProtoType *Proto
965 = CallOperator->getType()->getAs<FunctionProtoType>();
966 QualType BlockPtrTy;
967 {
968 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
969 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000970 QualType FunctionTy = S.Context.getFunctionType(
971 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000972 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
973 }
Reid Kleckneref072032013-08-27 23:08:25 +0000974
975 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
976 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000977 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000978 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000979
980 SourceLocation Loc = IntroducerRange.getBegin();
981 DeclarationName Name
982 = S.Context.DeclarationNames.getCXXConversionFunctionName(
983 S.Context.getCanonicalType(BlockPtrTy));
984 DeclarationNameLoc NameLoc;
985 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
986 CXXConversionDecl *Conversion
987 = CXXConversionDecl::Create(S.Context, Class, Loc,
988 DeclarationNameInfo(Name, Loc, NameLoc),
989 ConvTy,
990 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000991 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000992 /*isConstexpr=*/false,
993 CallOperator->getBody()->getLocEnd());
994 Conversion->setAccess(AS_public);
995 Conversion->setImplicit(true);
996 Class->addDecl(Conversion);
997}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000998
Douglas Gregordfca6f52012-02-13 22:00:16 +0000999ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001000 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001001 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001002 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001003 SmallVector<LambdaExpr::Capture, 4> Captures;
1004 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001005 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001006 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001007 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001008 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001009 SourceRange IntroducerRange;
1010 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001011 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001012 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001013 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001014 SmallVector<VarDecl *, 4> ArrayIndexVars;
1015 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001016 {
1017 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001018 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001019 Class = LSI->Lambda;
1020 IntroducerRange = LSI->IntroducerRange;
1021 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001022 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001023 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001024 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001025 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1026 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1027
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001028 // Translate captures.
1029 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1030 LambdaScopeInfo::Capture From = LSI->Captures[I];
1031 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1032 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1033
1034 // Handle 'this' capture.
1035 if (From.isThisCapture()) {
1036 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1037 IsImplicit,
1038 LCK_This));
1039 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1040 getCurrentThisType(),
1041 /*isImplicit=*/true));
1042 continue;
1043 }
1044
Richard Smith0d8e9642013-05-16 06:20:58 +00001045 if (From.isInitCapture()) {
1046 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
1047 CaptureInits.push_back(From.getInitExpr());
1048 continue;
1049 }
1050
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001051 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001052 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1053 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001054 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001055 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001056 }
1057
1058 switch (LSI->ImpCaptureStyle) {
1059 case CapturingScopeInfo::ImpCap_None:
1060 CaptureDefault = LCD_None;
1061 break;
1062
1063 case CapturingScopeInfo::ImpCap_LambdaByval:
1064 CaptureDefault = LCD_ByCopy;
1065 break;
1066
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001067 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001068 case CapturingScopeInfo::ImpCap_LambdaByref:
1069 CaptureDefault = LCD_ByRef;
1070 break;
1071
1072 case CapturingScopeInfo::ImpCap_Block:
1073 llvm_unreachable("block capture in lambda");
1074 break;
1075 }
James Dennettf68af642013-08-09 23:08:25 +00001076 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001077
Douglas Gregor54042f12012-02-09 10:18:50 +00001078 // C++11 [expr.prim.lambda]p4:
1079 // If a lambda-expression does not include a
1080 // trailing-return-type, it is as if the trailing-return-type
1081 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001082 //
1083 // Skip for C++1y return type deduction semantics which uses
1084 // different machinery.
1085 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001086 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001087 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001088 deduceClosureReturnType(*LSI);
1089
Douglas Gregor54042f12012-02-09 10:18:50 +00001090 // - if there are no return statements in the
1091 // compound-statement, or all return statements return
1092 // either an expression of type void or no expression or
1093 // braced-init-list, the type void;
1094 if (LSI->ReturnType.isNull()) {
1095 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001096 }
1097
1098 // Create a function type with the inferred return type.
1099 const FunctionProtoType *Proto
1100 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001101 QualType FunctionTy = Context.getFunctionType(
1102 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001103 CallOperator->setType(FunctionTy);
1104 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001105 // C++ [expr.prim.lambda]p7:
1106 // The lambda-expression's compound-statement yields the
1107 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001108 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001109 CallOperator->setLexicalDeclContext(Class);
Faisal Valifad9e132013-09-26 19:54:12 +00001110 Decl *TemplateOrNonTemplateCallOperatorDecl =
1111 CallOperator->getDescribedFunctionTemplate()
1112 ? CallOperator->getDescribedFunctionTemplate()
1113 : cast<Decl>(CallOperator);
1114
1115 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1116 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1117
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001118 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001119
Douglas Gregorb5559712012-02-10 16:13:20 +00001120 // C++11 [expr.prim.lambda]p6:
1121 // The closure type for a lambda-expression with no lambda-capture
1122 // has a public non-virtual non-explicit const conversion function
1123 // to pointer to function having the same parameter and return
1124 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001125 if (Captures.empty() && CaptureDefault == LCD_None)
1126 addFunctionPointerConversion(*this, IntroducerRange, Class,
1127 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001128
Douglas Gregorc2956e52012-02-15 22:08:38 +00001129 // Objective-C++:
1130 // The closure type for a lambda-expression has a public non-virtual
1131 // non-explicit const conversion function to a block pointer having the
1132 // same parameter and return types as the closure type's function call
1133 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001134 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001135 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1136
Douglas Gregorb5559712012-02-10 16:13:20 +00001137 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001138 SmallVector<Decl*, 4> Fields;
1139 for (RecordDecl::field_iterator i = Class->field_begin(),
1140 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001141 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001142 ActOnFields(0, Class->getLocation(), Class, Fields,
1143 SourceLocation(), SourceLocation(), 0);
1144 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001145 }
1146
Douglas Gregor503384f2012-02-09 00:47:04 +00001147 if (LambdaExprNeedsCleanups)
1148 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001149
Douglas Gregore2c59132012-02-09 08:14:43 +00001150 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001151 CaptureDefault, CaptureDefaultLoc,
1152 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001153 ExplicitParams, ExplicitResultType,
1154 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001155 ArrayIndexStarts, Body->getLocEnd(),
1156 ContainsUnexpandedParameterPack);
Faisal Valifad9e132013-09-26 19:54:12 +00001157 Class->setLambdaExpr(Lambda);
Douglas Gregore2c59132012-02-09 08:14:43 +00001158 // C++11 [expr.prim.lambda]p2:
1159 // A lambda-expression shall not appear in an unevaluated operand
1160 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001161 if (!CurContext->isDependentContext()) {
1162 switch (ExprEvalContexts.back().Context) {
1163 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001164 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001165 // We don't actually diagnose this case immediately, because we
1166 // could be within a context where we might find out later that
1167 // the expression is potentially evaluated (e.g., for typeid).
1168 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1169 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001170
Douglas Gregord5387e82012-02-14 00:00:48 +00001171 case ConstantEvaluated:
1172 case PotentiallyEvaluated:
1173 case PotentiallyEvaluatedIfUsed:
1174 break;
1175 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001176 }
Faisal Valifad9e132013-09-26 19:54:12 +00001177 // TODO: Implement capturing.
1178 if (Lambda->isGenericLambda()) {
1179 if (Lambda->getCaptureDefault() != LCD_None) {
1180 Diag(Lambda->getIntroducerRange().getBegin(),
1181 diag::err_glambda_not_fully_implemented)
1182 << " capturing not implemented yet";
1183 return ExprError();
1184 }
1185 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001186 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001187}
Eli Friedman23f02672012-03-01 04:01:32 +00001188
1189ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1190 SourceLocation ConvLocation,
1191 CXXConversionDecl *Conv,
1192 Expr *Src) {
1193 // Make sure that the lambda call operator is marked used.
1194 CXXRecordDecl *Lambda = Conv->getParent();
1195 CXXMethodDecl *CallOperator
1196 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001197 Lambda->lookup(
1198 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001199 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001200 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001201
1202 ExprResult Init = PerformCopyInitialization(
1203 InitializedEntity::InitializeBlock(ConvLocation,
1204 Src->getType(),
1205 /*NRVO=*/false),
1206 CurrentLocation, Src);
1207 if (!Init.isInvalid())
1208 Init = ActOnFinishFullExpr(Init.take());
1209
1210 if (Init.isInvalid())
1211 return ExprError();
1212
1213 // Create the new block to be returned.
1214 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1215
1216 // Set the type information.
1217 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1218 Block->setIsVariadic(CallOperator->isVariadic());
1219 Block->setBlockMissingReturnType(false);
1220
1221 // Add parameters.
1222 SmallVector<ParmVarDecl *, 4> BlockParams;
1223 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1224 ParmVarDecl *From = CallOperator->getParamDecl(I);
1225 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1226 From->getLocStart(),
1227 From->getLocation(),
1228 From->getIdentifier(),
1229 From->getType(),
1230 From->getTypeSourceInfo(),
1231 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001232 /*DefaultArg=*/0));
1233 }
1234 Block->setParams(BlockParams);
1235
1236 Block->setIsConversionFromLambda(true);
1237
1238 // Add capture. The capture uses a fake variable, which doesn't correspond
1239 // to any actual memory location. However, the initializer copy-initializes
1240 // the lambda object.
1241 TypeSourceInfo *CapVarTSI =
1242 Context.getTrivialTypeSourceInfo(Src->getType());
1243 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1244 ConvLocation, 0,
1245 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001246 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001247 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1248 /*Nested=*/false, /*Copy=*/Init.take());
1249 Block->setCaptures(Context, &Capture, &Capture + 1,
1250 /*CapturesCXXThis=*/false);
1251
1252 // Add a fake function body to the block. IR generation is responsible
1253 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001254 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001255
1256 // Create the block literal expression.
1257 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1258 ExprCleanupObjects.push_back(Block);
1259 ExprNeedsCleanups = true;
1260
1261 return BuildBlock;
1262}