blob: 32a385caaa559fe349bd376464e371a55758d112 [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 Smith04fa7a32013-09-28 04:02:39 +0000497VarDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
498 IdentifierInfo *Id, Expr *Init) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000499 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000500 // An init-capture behaves as if it declares and explicitly captures
501 // a variable of the form
502 // "auto init-capture;"
Richard Smith0d8e9642013-05-16 06:20:58 +0000503 QualType DeductType = Context.getAutoDeductType();
504 TypeLocBuilder TLB;
505 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
506 if (ByRef) {
507 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
508 assert(!DeductType.isNull() && "can't build reference to auto");
509 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
510 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000511 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000512
Richard Smith04fa7a32013-09-28 04:02:39 +0000513 // Create a dummy variable representing the init-capture. This is not actually
514 // used as a variable, and only exists as a way to name and refer to the
515 // init-capture.
516 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith39edfeb2013-09-28 04:31:26 +0000517 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Richard Smith04fa7a32013-09-28 04:02:39 +0000518 Loc, Id, TSI->getType(), TSI, SC_Auto);
519 NewVD->setInitCapture(true);
520 NewVD->setReferenced(true);
521 NewVD->markUsed(Context);
Richard Smith0d8e9642013-05-16 06:20:58 +0000522
Richard Smith04fa7a32013-09-28 04:02:39 +0000523 // We do not need to distinguish between direct-list-initialization
524 // and copy-list-initialization here, because we will always deduce
525 // std::initializer_list<T>, and direct- and copy-list-initialization
526 // always behave the same for such a type.
527 // FIXME: We should model whether an '=' was present.
528 bool DirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
529 AddInitializerToDecl(NewVD, Init, DirectInit, /*ContainsAuto*/true);
530 return NewVD;
531}
Richard Smith0d8e9642013-05-16 06:20:58 +0000532
Richard Smith04fa7a32013-09-28 04:02:39 +0000533FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
534 FieldDecl *Field = FieldDecl::Create(
535 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
536 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
537 Field->setImplicit(true);
538 Field->setAccess(AS_private);
539 LSI->Lambda->addDecl(Field);
Richard Smith0d8e9642013-05-16 06:20:58 +0000540
Richard Smith04fa7a32013-09-28 04:02:39 +0000541 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
542 /*isNested*/false, Var->getLocation(), SourceLocation(),
543 Var->getType(), Var->getInit());
544 return Field;
Richard Smith0d8e9642013-05-16 06:20:58 +0000545}
546
Douglas Gregordfca6f52012-02-13 22:00:16 +0000547void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valifad9e132013-09-26 19:54:12 +0000548 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000549 // Determine if we're within a context where we know that the lambda will
550 // be dependent, because there are template parameters in scope.
551 bool KnownDependent = false;
Faisal Valifad9e132013-09-26 19:54:12 +0000552 LambdaScopeInfo *const LSI = getCurLambda();
553 assert(LSI && "LambdaScopeInfo should be on stack!");
554 TemplateParameterList *TemplateParams =
555 getGenericLambdaTemplateParameterList(LSI, *this);
556
557 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
558 // Since we have our own TemplateParams, so check if an outer scope
559 // has template params, only then are we in a dependent scope.
560 if (TemplateParams) {
561 TmplScope = TmplScope->getParent();
562 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
563 }
564 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000565 KnownDependent = true;
Faisal Valifad9e132013-09-26 19:54:12 +0000566 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000567 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000568 TypeSourceInfo *MethodTyInfo;
569 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000570 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000571 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000572 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000573 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000574 if (ParamInfo.getNumTypeObjects() == 0) {
575 // C++11 [expr.prim.lambda]p4:
576 // If a lambda-expression does not include a lambda-declarator, it is as
577 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000578 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
579 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000580 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000581 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000582 // C++1y [expr.prim.lambda]:
583 // The lambda return type is 'auto', which is replaced by the
584 // trailing-return type if provided and/or deduced from 'return'
585 // statements
586 // We don't do this before C++1y, because we don't support deduced return
587 // types there.
588 QualType DefaultTypeForNoTrailingReturn =
589 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
590 : Context.DependentTy;
591 QualType MethodTy =
592 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000593 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
594 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000595 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000596 EndLoc = Intro.Range.getEnd();
597 } else {
598 assert(ParamInfo.isFunctionDeclarator() &&
599 "lambda-declarator is a function");
600 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000601
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000602 // C++11 [expr.prim.lambda]p5:
603 // This function call operator is declared const (9.3.1) if and only if
604 // the lambda-expression's parameter-declaration-clause is not followed
605 // by mutable. It is neither virtual nor declared volatile. [...]
606 if (!FTI.hasMutableQualifier())
607 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000608
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000609 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000611 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000612
613 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000614
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000615 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
616 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
617 // Empty arg list, don't push any params.
618 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
619 } else {
620 Params.reserve(FTI.NumArgs);
621 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
622 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
623 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000624
625 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000626 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
627 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000628 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000629
630 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
631 KnownDependent);
632
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000633 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000634 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000635 if (ExplicitParams)
636 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000637
Bill Wendlingad017fa2012-12-20 19:22:21 +0000638 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000639 ProcessDeclAttributes(CurScope, Method, ParamInfo);
640
Douglas Gregor503384f2012-02-09 00:47:04 +0000641 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000642 PushDeclContext(CurScope, Method);
643
Faisal Valifad9e132013-09-26 19:54:12 +0000644 // Build the lambda scope.
645 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000646 Intro.Range,
647 Intro.Default, Intro.DefaultLoc,
648 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000649 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000650 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000651
652 // Distinct capture names, for diagnostics.
653 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
654
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000655 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000656 SourceLocation PrevCaptureLoc
657 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000658 for (SmallVectorImpl<LambdaCapture>::const_iterator
659 C = Intro.Captures.begin(),
660 E = Intro.Captures.end();
661 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000662 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000663 if (C->Kind == LCK_This) {
664 // C++11 [expr.prim.lambda]p8:
665 // An identifier or this shall not appear more than once in a
666 // lambda-capture.
667 if (LSI->isCXXThisCaptured()) {
668 Diag(C->Loc, diag::err_capture_more_than_once)
669 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000670 << SourceRange(LSI->getCXXThisCapture().getLocation())
671 << FixItHint::CreateRemoval(
672 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000673 continue;
674 }
675
676 // C++11 [expr.prim.lambda]p8:
677 // If a lambda-capture includes a capture-default that is =, the
678 // lambda-capture shall not contain this [...].
679 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000680 Diag(C->Loc, diag::err_this_capture_with_copy_default)
681 << FixItHint::CreateRemoval(
682 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000683 continue;
684 }
685
686 // C++11 [expr.prim.lambda]p12:
687 // If this is captured by a local lambda expression, its nearest
688 // enclosing function shall be a non-static member function.
689 QualType ThisCaptureType = getCurrentThisType();
690 if (ThisCaptureType.isNull()) {
691 Diag(C->Loc, diag::err_this_capture) << true;
692 continue;
693 }
694
695 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
696 continue;
697 }
698
Richard Smith0d8e9642013-05-16 06:20:58 +0000699 assert(C->Id && "missing identifier for capture");
700
Richard Smith0a664b82013-05-09 21:36:41 +0000701 if (C->Init.isInvalid())
702 continue;
Richard Smith0d8e9642013-05-16 06:20:58 +0000703
Richard Smith04fa7a32013-09-28 04:02:39 +0000704 VarDecl *Var;
705 if (C->Init.isUsable()) {
Richard Smith9beaf202013-09-28 05:38:27 +0000706 Diag(C->Loc, getLangOpts().CPlusPlus1y
707 ? diag::warn_cxx11_compat_init_capture
708 : diag::ext_init_capture);
709
Richard Smith0d8e9642013-05-16 06:20:58 +0000710 if (C->Init.get()->containsUnexpandedParameterPack())
711 ContainsUnexpandedParameterPack = true;
712
Richard Smith04fa7a32013-09-28 04:02:39 +0000713 Var = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
714 C->Id, C->Init.take());
Richard Smith0d8e9642013-05-16 06:20:58 +0000715 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000716 // An init-capture behaves as if it declares and explicitly
717 // captures a variable [...] whose declarative region is the
718 // lambda-expression's compound-statement
719 if (Var)
720 PushOnScopeChains(Var, CurScope, false);
721 } else {
722 // C++11 [expr.prim.lambda]p8:
723 // If a lambda-capture includes a capture-default that is &, the
724 // identifiers in the lambda-capture shall not be preceded by &.
725 // If a lambda-capture includes a capture-default that is =, [...]
726 // each identifier it contains shall be preceded by &.
727 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
728 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
729 << FixItHint::CreateRemoval(
730 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000731 continue;
Richard Smith04fa7a32013-09-28 04:02:39 +0000732 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
733 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
734 << FixItHint::CreateRemoval(
735 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
736 continue;
737 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000738
Richard Smith04fa7a32013-09-28 04:02:39 +0000739 // C++11 [expr.prim.lambda]p10:
740 // The identifiers in a capture-list are looked up using the usual
741 // rules for unqualified name lookup (3.4.1)
742 DeclarationNameInfo Name(C->Id, C->Loc);
743 LookupResult R(*this, Name, LookupOrdinaryName);
744 LookupName(R, CurScope);
745 if (R.isAmbiguous())
746 continue;
747 if (R.empty()) {
748 // FIXME: Disable corrections that would add qualification?
749 CXXScopeSpec ScopeSpec;
750 DeclFilterCCC<VarDecl> Validator;
751 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
752 continue;
753 }
754
755 Var = R.getAsSingle<VarDecl>();
756 }
Richard Smith0d8e9642013-05-16 06:20:58 +0000757
758 // C++11 [expr.prim.lambda]p8:
759 // An identifier or this shall not appear more than once in a
760 // lambda-capture.
761 if (!CaptureNames.insert(C->Id)) {
762 if (Var && LSI->isCaptured(Var)) {
763 Diag(C->Loc, diag::err_capture_more_than_once)
764 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
765 << FixItHint::CreateRemoval(
766 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
767 } else
Richard Smith04fa7a32013-09-28 04:02:39 +0000768 // Previous capture captured something different (one or both was
769 // an init-cpature): no fixit.
Richard Smith0d8e9642013-05-16 06:20:58 +0000770 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
771 continue;
772 }
773
774 // C++11 [expr.prim.lambda]p10:
775 // [...] each such lookup shall find a variable with automatic storage
776 // duration declared in the reaching scope of the local lambda expression.
777 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000778 if (!Var) {
779 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
780 continue;
781 }
782
Eli Friedman9cd5b242012-09-18 21:11:30 +0000783 // Ignore invalid decls; they'll just confuse the code later.
784 if (Var->isInvalidDecl())
785 continue;
786
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000787 if (!Var->hasLocalStorage()) {
788 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
789 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
790 continue;
791 }
792
Douglas Gregora7365242012-02-14 19:27:52 +0000793 // C++11 [expr.prim.lambda]p23:
794 // A capture followed by an ellipsis is a pack expansion (14.5.3).
795 SourceLocation EllipsisLoc;
796 if (C->EllipsisLoc.isValid()) {
797 if (Var->isParameterPack()) {
798 EllipsisLoc = C->EllipsisLoc;
799 } else {
800 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
801 << SourceRange(C->Loc);
802
803 // Just ignore the ellipsis.
804 }
805 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000806 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000807 }
Richard Smith04fa7a32013-09-28 04:02:39 +0000808
809 if (C->Init.isUsable()) {
810 buildInitCaptureField(LSI, Var);
811 } else {
812 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
813 TryCapture_ExplicitByVal;
814 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
815 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000816 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000817 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000818
Richard Smith612409e2012-07-25 03:56:55 +0000819 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
820
Douglas Gregorc6889e72012-02-14 22:28:59 +0000821 // Add lambda parameters into scope.
822 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000823
Douglas Gregordfca6f52012-02-13 22:00:16 +0000824 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000825 // cleanups from the enclosing full-expression.
826 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000827}
828
Douglas Gregordfca6f52012-02-13 22:00:16 +0000829void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
830 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000831 // Leave the expression-evaluation context.
832 DiscardCleanupsInEvaluationContext();
833 PopExpressionEvaluationContext();
834
835 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000836 if (!IsInstantiation)
837 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000838
839 // Finalize the lambda.
840 LambdaScopeInfo *LSI = getCurLambda();
841 CXXRecordDecl *Class = LSI->Lambda;
842 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000843 SmallVector<Decl*, 4> Fields;
844 for (RecordDecl::field_iterator i = Class->field_begin(),
845 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000846 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000847 ActOnFields(0, Class->getLocation(), Class, Fields,
848 SourceLocation(), SourceLocation(), 0);
849 CheckCompletedCXXClass(Class);
850
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000851 PopFunctionScopeInfo();
852}
853
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000854/// \brief Add a lambda's conversion to function pointer, as described in
855/// C++11 [expr.prim.lambda]p6.
856static void addFunctionPointerConversion(Sema &S,
857 SourceRange IntroducerRange,
858 CXXRecordDecl *Class,
859 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000860 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000861 const FunctionProtoType *Proto
862 = CallOperator->getType()->getAs<FunctionProtoType>();
863 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000864 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000865 {
866 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000867 CallingConv CC = S.Context.getDefaultCallingConvention(
868 Proto->isVariadic(), /*IsCXXMethod=*/false);
869 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000870 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000871 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
872 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000873 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
874 }
Reid Kleckneref072032013-08-27 23:08:25 +0000875
876 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
877 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000878 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000879 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
880
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000881 SourceLocation Loc = IntroducerRange.getBegin();
882 DeclarationName Name
883 = S.Context.DeclarationNames.getCXXConversionFunctionName(
884 S.Context.getCanonicalType(FunctionPtrTy));
885 DeclarationNameLoc NameLoc;
886 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
887 Loc);
888 CXXConversionDecl *Conversion
889 = CXXConversionDecl::Create(S.Context, Class, Loc,
890 DeclarationNameInfo(Name, Loc, NameLoc),
891 ConvTy,
892 S.Context.getTrivialTypeSourceInfo(ConvTy,
893 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000894 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000895 /*isConstexpr=*/false,
896 CallOperator->getBody()->getLocEnd());
897 Conversion->setAccess(AS_public);
898 Conversion->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +0000899
900 if (Class->isGenericLambda()) {
901 // Create a template version of the conversion operator, using the template
902 // parameter list of the function call operator.
903 FunctionTemplateDecl *TemplateCallOperator =
904 CallOperator->getDescribedFunctionTemplate();
905 FunctionTemplateDecl *ConversionTemplate =
906 FunctionTemplateDecl::Create(S.Context, Class,
907 Loc, Name,
908 TemplateCallOperator->getTemplateParameters(),
909 Conversion);
910 ConversionTemplate->setAccess(AS_public);
911 ConversionTemplate->setImplicit(true);
912 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
913 Class->addDecl(ConversionTemplate);
914 } else
915 Class->addDecl(Conversion);
Faisal Valifad9e132013-09-26 19:54:12 +0000916 // Add a non-static member function that will be the result of
917 // the conversion with a certain unique ID.
918 Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
Faisal Valid6992ab2013-09-29 08:45:24 +0000919 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
920 // we should get a prebuilt TrivialTypeSourceInfo from Context
921 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
922 // then rewire the parameters accordingly, by hoisting up the InvokeParams
923 // loop below and then use its Params to set Invoke->setParams(...) below.
924 // This would avoid the 'const' qualifier of the calloperator from
925 // contaminating the type of the invoker, which is currently adjusted
926 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000927 CXXMethodDecl *Invoke
928 = CXXMethodDecl::Create(S.Context, Class, Loc,
929 DeclarationNameInfo(Name, Loc), FunctionTy,
930 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000931 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000932 /*IsConstexpr=*/false,
933 CallOperator->getBody()->getLocEnd());
934 SmallVector<ParmVarDecl *, 4> InvokeParams;
935 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
936 ParmVarDecl *From = CallOperator->getParamDecl(I);
937 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
938 From->getLocStart(),
939 From->getLocation(),
940 From->getIdentifier(),
941 From->getType(),
942 From->getTypeSourceInfo(),
943 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000944 /*DefaultArg=*/0));
945 }
946 Invoke->setParams(InvokeParams);
947 Invoke->setAccess(AS_private);
948 Invoke->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +0000949 if (Class->isGenericLambda()) {
950 FunctionTemplateDecl *TemplateCallOperator =
951 CallOperator->getDescribedFunctionTemplate();
952 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
953 S.Context, Class, Loc, Name,
954 TemplateCallOperator->getTemplateParameters(),
955 Invoke);
956 StaticInvokerTemplate->setAccess(AS_private);
957 StaticInvokerTemplate->setImplicit(true);
958 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
959 Class->addDecl(StaticInvokerTemplate);
960 } else
961 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000962}
963
Douglas Gregorc2956e52012-02-15 22:08:38 +0000964/// \brief Add a lambda's conversion to block pointer.
965static void addBlockPointerConversion(Sema &S,
966 SourceRange IntroducerRange,
967 CXXRecordDecl *Class,
968 CXXMethodDecl *CallOperator) {
969 const FunctionProtoType *Proto
970 = CallOperator->getType()->getAs<FunctionProtoType>();
971 QualType BlockPtrTy;
972 {
973 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
974 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000975 QualType FunctionTy = S.Context.getFunctionType(
976 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000977 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
978 }
Reid Kleckneref072032013-08-27 23:08:25 +0000979
980 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
981 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000982 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000983 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000984
985 SourceLocation Loc = IntroducerRange.getBegin();
986 DeclarationName Name
987 = S.Context.DeclarationNames.getCXXConversionFunctionName(
988 S.Context.getCanonicalType(BlockPtrTy));
989 DeclarationNameLoc NameLoc;
990 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
991 CXXConversionDecl *Conversion
992 = CXXConversionDecl::Create(S.Context, Class, Loc,
993 DeclarationNameInfo(Name, Loc, NameLoc),
994 ConvTy,
995 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000996 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000997 /*isConstexpr=*/false,
998 CallOperator->getBody()->getLocEnd());
999 Conversion->setAccess(AS_public);
1000 Conversion->setImplicit(true);
1001 Class->addDecl(Conversion);
1002}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001003
Douglas Gregordfca6f52012-02-13 22:00:16 +00001004ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001005 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001006 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001007 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001008 SmallVector<LambdaExpr::Capture, 4> Captures;
1009 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001010 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001011 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001012 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001013 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001014 SourceRange IntroducerRange;
1015 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001016 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001017 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001018 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001019 SmallVector<VarDecl *, 4> ArrayIndexVars;
1020 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001021 {
1022 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001023 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001024 Class = LSI->Lambda;
1025 IntroducerRange = LSI->IntroducerRange;
1026 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001027 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001028 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001029 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001030 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1031 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1032
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001033 // Translate captures.
1034 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1035 LambdaScopeInfo::Capture From = LSI->Captures[I];
1036 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1037 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1038
1039 // Handle 'this' capture.
1040 if (From.isThisCapture()) {
1041 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1042 IsImplicit,
1043 LCK_This));
1044 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1045 getCurrentThisType(),
1046 /*isImplicit=*/true));
1047 continue;
1048 }
1049
1050 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001051 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1052 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001053 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001054 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001055 }
1056
1057 switch (LSI->ImpCaptureStyle) {
1058 case CapturingScopeInfo::ImpCap_None:
1059 CaptureDefault = LCD_None;
1060 break;
1061
1062 case CapturingScopeInfo::ImpCap_LambdaByval:
1063 CaptureDefault = LCD_ByCopy;
1064 break;
1065
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001066 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001067 case CapturingScopeInfo::ImpCap_LambdaByref:
1068 CaptureDefault = LCD_ByRef;
1069 break;
1070
1071 case CapturingScopeInfo::ImpCap_Block:
1072 llvm_unreachable("block capture in lambda");
1073 break;
1074 }
James Dennettf68af642013-08-09 23:08:25 +00001075 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001076
Douglas Gregor54042f12012-02-09 10:18:50 +00001077 // C++11 [expr.prim.lambda]p4:
1078 // If a lambda-expression does not include a
1079 // trailing-return-type, it is as if the trailing-return-type
1080 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001081 //
1082 // Skip for C++1y return type deduction semantics which uses
1083 // different machinery.
1084 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001085 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001086 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001087 deduceClosureReturnType(*LSI);
1088
Douglas Gregor54042f12012-02-09 10:18:50 +00001089 // - if there are no return statements in the
1090 // compound-statement, or all return statements return
1091 // either an expression of type void or no expression or
1092 // braced-init-list, the type void;
1093 if (LSI->ReturnType.isNull()) {
1094 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001095 }
1096
1097 // Create a function type with the inferred return type.
1098 const FunctionProtoType *Proto
1099 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001100 QualType FunctionTy = Context.getFunctionType(
1101 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001102 CallOperator->setType(FunctionTy);
1103 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001104 // C++ [expr.prim.lambda]p7:
1105 // The lambda-expression's compound-statement yields the
1106 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001107 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001108 CallOperator->setLexicalDeclContext(Class);
Faisal Valifad9e132013-09-26 19:54:12 +00001109 Decl *TemplateOrNonTemplateCallOperatorDecl =
1110 CallOperator->getDescribedFunctionTemplate()
1111 ? CallOperator->getDescribedFunctionTemplate()
1112 : cast<Decl>(CallOperator);
1113
1114 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1115 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1116
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001117 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001118
Douglas Gregorb5559712012-02-10 16:13:20 +00001119 // C++11 [expr.prim.lambda]p6:
1120 // The closure type for a lambda-expression with no lambda-capture
1121 // has a public non-virtual non-explicit const conversion function
1122 // to pointer to function having the same parameter and return
1123 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001124 if (Captures.empty() && CaptureDefault == LCD_None)
1125 addFunctionPointerConversion(*this, IntroducerRange, Class,
1126 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001127
Douglas Gregorc2956e52012-02-15 22:08:38 +00001128 // Objective-C++:
1129 // The closure type for a lambda-expression has a public non-virtual
1130 // non-explicit const conversion function to a block pointer having the
1131 // same parameter and return types as the closure type's function call
1132 // operator.
Faisal Valid6992ab2013-09-29 08:45:24 +00001133 // FIXME: Fix generic lambda to block conversions.
1134 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1135 !Class->isGenericLambda())
Douglas Gregorc2956e52012-02-15 22:08:38 +00001136 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1137
Douglas Gregorb5559712012-02-10 16:13:20 +00001138 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001139 SmallVector<Decl*, 4> Fields;
1140 for (RecordDecl::field_iterator i = Class->field_begin(),
1141 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001142 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001143 ActOnFields(0, Class->getLocation(), Class, Fields,
1144 SourceLocation(), SourceLocation(), 0);
1145 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001146 }
1147
Douglas Gregor503384f2012-02-09 00:47:04 +00001148 if (LambdaExprNeedsCleanups)
1149 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001150
Douglas Gregore2c59132012-02-09 08:14:43 +00001151 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001152 CaptureDefault, CaptureDefaultLoc,
1153 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001154 ExplicitParams, ExplicitResultType,
1155 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001156 ArrayIndexStarts, Body->getLocEnd(),
1157 ContainsUnexpandedParameterPack);
Faisal Valifad9e132013-09-26 19:54:12 +00001158 Class->setLambdaExpr(Lambda);
Douglas Gregore2c59132012-02-09 08:14:43 +00001159 // C++11 [expr.prim.lambda]p2:
1160 // A lambda-expression shall not appear in an unevaluated operand
1161 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001162 if (!CurContext->isDependentContext()) {
1163 switch (ExprEvalContexts.back().Context) {
1164 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001165 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001166 // We don't actually diagnose this case immediately, because we
1167 // could be within a context where we might find out later that
1168 // the expression is potentially evaluated (e.g., for typeid).
1169 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1170 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001171
Douglas Gregord5387e82012-02-14 00:00:48 +00001172 case ConstantEvaluated:
1173 case PotentiallyEvaluated:
1174 case PotentiallyEvaluatedIfUsed:
1175 break;
1176 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001177 }
Faisal Valifad9e132013-09-26 19:54:12 +00001178 // TODO: Implement capturing.
1179 if (Lambda->isGenericLambda()) {
Faisal Valid6992ab2013-09-29 08:45:24 +00001180 if (!Captures.empty() || Lambda->getCaptureDefault() != LCD_None) {
Faisal Valifad9e132013-09-26 19:54:12 +00001181 Diag(Lambda->getIntroducerRange().getBegin(),
1182 diag::err_glambda_not_fully_implemented)
1183 << " capturing not implemented yet";
1184 return ExprError();
1185 }
1186 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001187 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001188}
Eli Friedman23f02672012-03-01 04:01:32 +00001189
1190ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1191 SourceLocation ConvLocation,
1192 CXXConversionDecl *Conv,
1193 Expr *Src) {
1194 // Make sure that the lambda call operator is marked used.
1195 CXXRecordDecl *Lambda = Conv->getParent();
1196 CXXMethodDecl *CallOperator
1197 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001198 Lambda->lookup(
1199 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001200 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001201 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001202
1203 ExprResult Init = PerformCopyInitialization(
1204 InitializedEntity::InitializeBlock(ConvLocation,
1205 Src->getType(),
1206 /*NRVO=*/false),
1207 CurrentLocation, Src);
1208 if (!Init.isInvalid())
1209 Init = ActOnFinishFullExpr(Init.take());
1210
1211 if (Init.isInvalid())
1212 return ExprError();
1213
1214 // Create the new block to be returned.
1215 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1216
1217 // Set the type information.
1218 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1219 Block->setIsVariadic(CallOperator->isVariadic());
1220 Block->setBlockMissingReturnType(false);
1221
1222 // Add parameters.
1223 SmallVector<ParmVarDecl *, 4> BlockParams;
1224 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1225 ParmVarDecl *From = CallOperator->getParamDecl(I);
1226 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1227 From->getLocStart(),
1228 From->getLocation(),
1229 From->getIdentifier(),
1230 From->getType(),
1231 From->getTypeSourceInfo(),
1232 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001233 /*DefaultArg=*/0));
1234 }
1235 Block->setParams(BlockParams);
1236
1237 Block->setIsConversionFromLambda(true);
1238
1239 // Add capture. The capture uses a fake variable, which doesn't correspond
1240 // to any actual memory location. However, the initializer copy-initializes
1241 // the lambda object.
1242 TypeSourceInfo *CapVarTSI =
1243 Context.getTrivialTypeSourceInfo(Src->getType());
1244 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1245 ConvLocation, 0,
1246 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001247 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001248 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1249 /*Nested=*/false, /*Copy=*/Init.take());
1250 Block->setCaptures(Context, &Capture, &Capture + 1,
1251 /*CapturesCXXThis=*/false);
1252
1253 // Add a fake function body to the block. IR generation is responsible
1254 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001255 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001256
1257 // Create the block literal expression.
1258 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1259 ExprCleanupObjects.push_back(Block);
1260 ExprNeedsCleanups = true;
1261
1262 return BuildBlock;
1263}