blob: 469756cf4d9aa294326f7aed7da1168fa036af36 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/AST/ExprCXX.h"
15#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000018#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000019#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000021#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000022using namespace clang;
23using namespace sema;
24
Douglas Gregorf4b7de12012-02-21 19:11:17 +000025CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000026 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000027 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000028 DeclContext *DC = CurContext;
29 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
30 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000031
Douglas Gregore2a7ad02012-02-08 21:18:48 +000032 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000033 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000034 IntroducerRange.getBegin(),
35 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000036 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000037
38 return Class;
39}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000040
Douglas Gregorf54486a2012-04-04 17:40:10 +000041/// \brief Determine whether the given context is or is enclosed in an inline
42/// function.
43static bool isInInlineFunction(const DeclContext *DC) {
44 while (!DC->isFileContext()) {
45 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
46 if (FD->isInlined())
47 return true;
48
49 DC = DC->getLexicalParent();
50 }
51
52 return false;
53}
54
Douglas Gregordfca6f52012-02-13 22:00:16 +000055CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000056 SourceRange IntroducerRange,
57 TypeSourceInfo *MethodType,
58 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000059 ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000060 // C++11 [expr.prim.lambda]p5:
61 // The closure type for a lambda-expression has a public inline function
62 // call operator (13.5.4) whose parameters and return type are described by
63 // the lambda-expression's parameter-declaration-clause and
64 // trailing-return-type respectively.
65 DeclarationName MethodName
66 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67 DeclarationNameLoc MethodNameLoc;
68 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69 = IntroducerRange.getBegin().getRawEncoding();
70 MethodNameLoc.CXXOperatorName.EndOpNameLoc
71 = IntroducerRange.getEnd().getRawEncoding();
72 CXXMethodDecl *Method
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
76 MethodNameLoc),
77 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +000078 SC_None,
79 /*isInline=*/true,
80 /*isConstExpr=*/false,
81 EndLoc);
82 Method->setAccess(AS_public);
83
84 // Temporarily set the lexical declaration context to the current
85 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000086 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000087
Douglas Gregorc6889e72012-02-14 22:28:59 +000088 // Add parameters.
89 if (!Params.empty()) {
90 Method->setParams(Params);
91 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
92 const_cast<ParmVarDecl **>(Params.end()),
93 /*CheckParameterNames=*/false);
94
95 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
96 PEnd = Method->param_end();
97 P != PEnd; ++P)
98 (*P)->setOwningFunction(Method);
99 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000100
101 // Allocate a mangling number for this lambda expression, if the ABI
102 // requires one.
103 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
104
105 enum ContextKind {
106 Normal,
107 DefaultArgument,
108 DataMember,
109 StaticDataMember
110 } Kind = Normal;
111
112 // Default arguments of member function parameters that appear in a class
113 // definition, as well as the initializers of data members, receive special
114 // treatment. Identify them.
115 if (ContextDecl) {
116 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
117 if (const DeclContext *LexicalDC
118 = Param->getDeclContext()->getLexicalParent())
119 if (LexicalDC->isRecord())
120 Kind = DefaultArgument;
121 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
122 if (Var->getDeclContext()->isRecord())
123 Kind = StaticDataMember;
124 } else if (isa<FieldDecl>(ContextDecl)) {
125 Kind = DataMember;
Douglas Gregorf54486a2012-04-04 17:40:10 +0000126 }
127 }
128
Richard Smithadb1d4c2012-07-22 23:45:10 +0000129 // Itanium ABI [5.1.7]:
130 // In the following contexts [...] the one-definition rule requires closure
131 // types in different translation units to "correspond":
132 bool IsInNonspecializedTemplate =
133 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
134 unsigned ManglingNumber;
135 switch (Kind) {
136 case Normal:
137 // -- the bodies of non-exported nonspecialized template functions
138 // -- the bodies of inline functions
139 if ((IsInNonspecializedTemplate &&
140 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
141 isInInlineFunction(CurContext))
142 ManglingNumber = Context.getLambdaManglingNumber(Method);
143 else
144 ManglingNumber = 0;
145
146 // There is no special context for this lambda.
147 ContextDecl = 0;
148 break;
149
150 case StaticDataMember:
151 // -- the initializers of nonspecialized static members of template classes
152 if (!IsInNonspecializedTemplate) {
153 ManglingNumber = 0;
154 ContextDecl = 0;
155 break;
156 }
157 // Fall through to assign a mangling number.
158
159 case DataMember:
160 // -- the in-class initializers of class members
161 case DefaultArgument:
162 // -- default arguments appearing in class definitions
163 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
164 .getManglingNumber(Method);
165 break;
166 }
167
168 Class->setLambdaMangling(ManglingNumber, ContextDecl);
169
Douglas Gregordfca6f52012-02-13 22:00:16 +0000170 return Method;
171}
172
173LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
174 SourceRange IntroducerRange,
175 LambdaCaptureDefault CaptureDefault,
176 bool ExplicitParams,
177 bool ExplicitResultType,
178 bool Mutable) {
179 PushLambdaScope(CallOperator->getParent(), CallOperator);
180 LambdaScopeInfo *LSI = getCurLambda();
181 if (CaptureDefault == LCD_ByCopy)
182 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
183 else if (CaptureDefault == LCD_ByRef)
184 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
185 LSI->IntroducerRange = IntroducerRange;
186 LSI->ExplicitParams = ExplicitParams;
187 LSI->Mutable = Mutable;
188
189 if (ExplicitResultType) {
190 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000191
192 if (!LSI->ReturnType->isDependentType() &&
193 !LSI->ReturnType->isVoidType()) {
194 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
195 diag::err_lambda_incomplete_result)) {
196 // Do nothing.
197 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
198 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
199 << LSI->ReturnType;
200 }
201 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000202 } else {
203 LSI->HasImplicitReturnType = true;
204 }
205
206 return LSI;
207}
208
209void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
210 LSI->finishedExplicitCaptures();
211}
212
Douglas Gregorc6889e72012-02-14 22:28:59 +0000213void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000214 // Introduce our parameters into the function scope
215 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
216 p < NumParams; ++p) {
217 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000218
219 // If this has an identifier, add it to the scope stack.
220 if (CurScope && Param->getIdentifier()) {
221 CheckShadow(CurScope, Param);
222
223 PushOnScopeChains(Param, CurScope);
224 }
225 }
226}
227
John McCall41d01642013-03-09 00:54:31 +0000228/// If this expression is an enumerator-like expression of some type
229/// T, return the type T; otherwise, return null.
230///
231/// Pointer comparisons on the result here should always work because
232/// it's derived from either the parent of an EnumConstantDecl
233/// (i.e. the definition) or the declaration returned by
234/// EnumType::getDecl() (i.e. the definition).
235static EnumDecl *findEnumForBlockReturn(Expr *E) {
236 // An expression is an enumerator-like expression of type T if,
237 // ignoring parens and parens-like expressions:
238 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000239
John McCall41d01642013-03-09 00:54:31 +0000240 // - it is an enumerator whose enum type is T or
241 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
242 if (EnumConstantDecl *D
243 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
244 return cast<EnumDecl>(D->getDeclContext());
245 }
246 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000247 }
248
John McCall41d01642013-03-09 00:54:31 +0000249 // - it is a comma expression whose RHS is an enumerator-like
250 // expression of type T or
251 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
252 if (BO->getOpcode() == BO_Comma)
253 return findEnumForBlockReturn(BO->getRHS());
254 return 0;
255 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000256
John McCall41d01642013-03-09 00:54:31 +0000257 // - it is a statement-expression whose value expression is an
258 // enumerator-like expression of type T or
259 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
260 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
261 return findEnumForBlockReturn(last);
262 return 0;
263 }
264
265 // - it is a ternary conditional operator (not the GNU ?:
266 // extension) whose second and third operands are
267 // enumerator-like expressions of type T or
268 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
269 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
270 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
271 return ED;
272 return 0;
273 }
274
275 // (implicitly:)
276 // - it is an implicit integral conversion applied to an
277 // enumerator-like expression of type T or
278 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000279 // We can sometimes see integral conversions in valid
280 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000281 if (ICE->getCastKind() == CK_IntegralCast)
282 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000283
284 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000285 }
286
287 // - it is an expression of that formal enum type.
288 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
289 return ET->getDecl();
290 }
291
292 // Otherwise, nope.
293 return 0;
294}
295
296/// Attempt to find a type T for which the returned expression of the
297/// given statement is an enumerator-like expression of that type.
298static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
299 if (Expr *retValue = ret->getRetValue())
300 return findEnumForBlockReturn(retValue);
301 return 0;
302}
303
304/// Attempt to find a common type T for which all of the returned
305/// expressions in a block are enumerator-like expressions of that
306/// type.
307static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
308 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
309
310 // Try to find one for the first return.
311 EnumDecl *ED = findEnumForBlockReturn(*i);
312 if (!ED) return 0;
313
314 // Check that the rest of the returns have the same enum.
315 for (++i; i != e; ++i) {
316 if (findEnumForBlockReturn(*i) != ED)
317 return 0;
318 }
319
320 // Never infer an anonymous enum type.
321 if (!ED->hasNameForLinkage()) return 0;
322
323 return ED;
324}
325
326/// Adjust the given return statements so that they formally return
327/// the given type. It should require, at most, an IntegralCast.
328static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
329 QualType returnType) {
330 for (ArrayRef<ReturnStmt*>::iterator
331 i = returns.begin(), e = returns.end(); i != e; ++i) {
332 ReturnStmt *ret = *i;
333 Expr *retValue = ret->getRetValue();
334 if (S.Context.hasSameType(retValue->getType(), returnType))
335 continue;
336
337 // Right now we only support integral fixup casts.
338 assert(returnType->isIntegralOrUnscopedEnumerationType());
339 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
340
341 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
342
343 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
344 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
345 E, /*base path*/ 0, VK_RValue);
346 if (cleanups) {
347 cleanups->setSubExpr(E);
348 } else {
349 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000350 }
351 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000352}
353
354void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
355 assert(CSI.HasImplicitReturnType);
356
John McCall41d01642013-03-09 00:54:31 +0000357 // C++ Core Issue #975, proposed resolution:
358 // If a lambda-expression does not include a trailing-return-type,
359 // it is as if the trailing-return-type denotes the following type:
360 // - if there are no return statements in the compound-statement,
361 // or all return statements return either an expression of type
362 // void or no expression or braced-init-list, the type void;
363 // - otherwise, if all return statements return an expression
364 // and the types of the returned expressions after
365 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
366 // array-to-pointer conversion (4.2 [conv.array]), and
367 // function-to-pointer conversion (4.3 [conv.func]) are the
368 // same, that common type;
369 // - otherwise, the program is ill-formed.
370 //
371 // In addition, in blocks in non-C++ modes, if all of the return
372 // statements are enumerator-like expressions of some type T, where
373 // T has a name for linkage, then we infer the return type of the
374 // block to be that type.
375
Jordan Rose7dd900e2012-07-02 21:19:23 +0000376 // First case: no return statements, implicit void return type.
377 ASTContext &Ctx = getASTContext();
378 if (CSI.Returns.empty()) {
379 // It's possible there were simply no /valid/ return statements.
380 // In this case, the first one we found may have at least given us a type.
381 if (CSI.ReturnType.isNull())
382 CSI.ReturnType = Ctx.VoidTy;
383 return;
384 }
385
386 // Second case: at least one return statement has dependent type.
387 // Delay type checking until instantiation.
388 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
389 if (CSI.ReturnType->isDependentType())
390 return;
391
John McCall41d01642013-03-09 00:54:31 +0000392 // Try to apply the enum-fuzz rule.
393 if (!getLangOpts().CPlusPlus) {
394 assert(isa<BlockScopeInfo>(CSI));
395 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
396 if (ED) {
397 CSI.ReturnType = Context.getTypeDeclType(ED);
398 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
399 return;
400 }
401 }
402
Jordan Rose7dd900e2012-07-02 21:19:23 +0000403 // Third case: only one return statement. Don't bother doing extra work!
404 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
405 E = CSI.Returns.end();
406 if (I+1 == E)
407 return;
408
409 // General case: many return statements.
410 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000411
412 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000413 // Note that we've already done the required promotions as part of
414 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000415 for (; I != E; ++I) {
416 const ReturnStmt *RS = *I;
417 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000418
John McCall41d01642013-03-09 00:54:31 +0000419 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
420 if (Context.hasSameType(ReturnType, CSI.ReturnType))
421 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000422
John McCall41d01642013-03-09 00:54:31 +0000423 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
424 // TODO: It's possible that the *first* return is the divergent one.
425 Diag(RS->getLocStart(),
426 diag::err_typecheck_missing_return_type_incompatible)
427 << ReturnType << CSI.ReturnType
428 << isa<LambdaScopeInfo>(CSI);
429 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000430 }
431}
432
Richard Smith0d8e9642013-05-16 06:20:58 +0000433FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
434 IdentifierInfo *Id, Expr *InitExpr) {
435 LambdaScopeInfo *LSI = getCurLambda();
436
437 // C++1y [expr.prim.lambda]p11:
438 // The type of [the] member corresponds to the type of a hypothetical
439 // variable declaration of the form "auto init-capture;"
440 QualType DeductType = Context.getAutoDeductType();
441 TypeLocBuilder TLB;
442 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
443 if (ByRef) {
444 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
445 assert(!DeductType.isNull() && "can't build reference to auto");
446 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
447 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000448 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000449
450 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
451 Expr *Init = InitExpr;
452 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
453 if (Parens->getNumExprs() == 1) {
454 Init = Parens->getExpr(0);
455 InitKind = InitializationKind::CreateDirect(
456 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
457 } else {
458 // C++1y [dcl.spec.auto]p3:
459 // In an initializer of the form ( expression-list ), the
460 // expression-list shall be a single assignment-expression.
461 if (Parens->getNumExprs() == 0)
462 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
463 << Id;
464 else if (Parens->getNumExprs() > 1)
465 Diag(Parens->getExpr(1)->getLocStart(),
466 diag::err_init_capture_multiple_expressions)
467 << Id;
468 return 0;
469 }
470 } else if (isa<InitListExpr>(Init))
471 // We do not need to distinguish between direct-list-initialization
472 // and copy-list-initialization here, because we will always deduce
473 // std::initializer_list<T>, and direct- and copy-list-initialization
474 // always behave the same for such a type.
475 // FIXME: We should model whether an '=' was present.
476 InitKind = InitializationKind::CreateDirectList(Loc);
477 else
478 InitKind = InitializationKind::CreateCopy(Loc, Loc);
479 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000480 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000481 if (isa<InitListExpr>(Init))
482 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
483 << Id << Init->getSourceRange();
484 else
485 Diag(Loc, diag::err_init_capture_deduction_failure)
486 << Id << Init->getType() << Init->getSourceRange();
487 }
488 if (DeducedType.isNull())
489 return 0;
490
491 // [...] a non-static data member named by the identifier is declared in
492 // the closure type. This member is not a bit-field and not mutable.
493 // Core issue: the member is (probably...) public.
494 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000495 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000496 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
497 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
498 LSI->Lambda->addDecl(NewFD);
499
500 if (CurContext->isDependentContext()) {
501 LSI->addInitCapture(NewFD, InitExpr);
502 } else {
503 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
504 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
505 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
506 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
507 if (!InitResult.isInvalid())
508 LSI->addInitCapture(NewFD, InitResult.take());
509 }
510 }
511
512 return NewFD;
513}
514
Douglas Gregordfca6f52012-02-13 22:00:16 +0000515void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
516 Declarator &ParamInfo,
517 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000518 // Determine if we're within a context where we know that the lambda will
519 // be dependent, because there are template parameters in scope.
520 bool KnownDependent = false;
521 if (Scope *TmplScope = CurScope->getTemplateParamParent())
522 if (!TmplScope->decl_empty())
523 KnownDependent = true;
524
Douglas Gregordfca6f52012-02-13 22:00:16 +0000525 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000526 TypeSourceInfo *MethodTyInfo;
527 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000528 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000529 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000530 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000531 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000532 if (ParamInfo.getNumTypeObjects() == 0) {
533 // C++11 [expr.prim.lambda]p4:
534 // If a lambda-expression does not include a lambda-declarator, it is as
535 // if the lambda-declarator were ().
536 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000537 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000538 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000539 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000540 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000541 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
542 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000543 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000544 EndLoc = Intro.Range.getEnd();
545 } else {
546 assert(ParamInfo.isFunctionDeclarator() &&
547 "lambda-declarator is a function");
548 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
549
550 // C++11 [expr.prim.lambda]p5:
551 // This function call operator is declared const (9.3.1) if and only if
552 // the lambda-expression's parameter-declaration-clause is not followed
553 // by mutable. It is neither virtual nor declared volatile. [...]
554 if (!FTI.hasMutableQualifier())
555 FTI.TypeQuals |= DeclSpec::TQ_const;
556
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000557 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000558 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000559 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000560
561 ExplicitResultType
562 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
563 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000564
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000565 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
566 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
567 // Empty arg list, don't push any params.
568 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
569 } else {
570 Params.reserve(FTI.NumArgs);
571 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
572 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
573 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000574
575 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000576 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
577 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000578 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000579
580 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
581 KnownDependent);
582
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000583 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000584 MethodTyInfo, EndLoc, Params);
585
586 if (ExplicitParams)
587 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000588
Bill Wendlingad017fa2012-12-20 19:22:21 +0000589 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000590 ProcessDeclAttributes(CurScope, Method, ParamInfo);
591
Douglas Gregor503384f2012-02-09 00:47:04 +0000592 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000593 PushDeclContext(CurScope, Method);
594
595 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000596 LambdaScopeInfo *LSI
597 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
598 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000599 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000600
601 // Distinct capture names, for diagnostics.
602 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
603
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000604 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000605 SourceLocation PrevCaptureLoc
606 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000607 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000608 C = Intro.Captures.begin(),
609 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000610 C != E;
611 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000612 if (C->Kind == LCK_This) {
613 // C++11 [expr.prim.lambda]p8:
614 // An identifier or this shall not appear more than once in a
615 // lambda-capture.
616 if (LSI->isCXXThisCaptured()) {
617 Diag(C->Loc, diag::err_capture_more_than_once)
618 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000619 << SourceRange(LSI->getCXXThisCapture().getLocation())
620 << FixItHint::CreateRemoval(
621 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000622 continue;
623 }
624
625 // C++11 [expr.prim.lambda]p8:
626 // If a lambda-capture includes a capture-default that is =, the
627 // lambda-capture shall not contain this [...].
628 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000629 Diag(C->Loc, diag::err_this_capture_with_copy_default)
630 << FixItHint::CreateRemoval(
631 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000632 continue;
633 }
634
635 // C++11 [expr.prim.lambda]p12:
636 // If this is captured by a local lambda expression, its nearest
637 // enclosing function shall be a non-static member function.
638 QualType ThisCaptureType = getCurrentThisType();
639 if (ThisCaptureType.isNull()) {
640 Diag(C->Loc, diag::err_this_capture) << true;
641 continue;
642 }
643
644 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
645 continue;
646 }
647
Richard Smith0d8e9642013-05-16 06:20:58 +0000648 assert(C->Id && "missing identifier for capture");
649
Richard Smith0a664b82013-05-09 21:36:41 +0000650 if (C->Init.isInvalid())
651 continue;
652 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000653 // C++11 [expr.prim.lambda]p8:
654 // An identifier or this shall not appear more than once in a
655 // lambda-capture.
656 if (!CaptureNames.insert(C->Id))
657 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
658
659 if (C->Init.get()->containsUnexpandedParameterPack())
660 ContainsUnexpandedParameterPack = true;
661
662 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
663 C->Id, C->Init.take());
664 // C++1y [expr.prim.lambda]p11:
665 // Within the lambda-expression's lambda-declarator and
666 // compound-statement, the identifier in the init-capture
667 // hides any declaration of the same name in scopes enclosing
668 // the lambda-expression.
669 if (NewFD)
670 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000671 continue;
672 }
673
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000674 // C++11 [expr.prim.lambda]p8:
675 // If a lambda-capture includes a capture-default that is &, the
676 // identifiers in the lambda-capture shall not be preceded by &.
677 // If a lambda-capture includes a capture-default that is =, [...]
678 // each identifier it contains shall be preceded by &.
679 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000680 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
681 << FixItHint::CreateRemoval(
682 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000683 continue;
684 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000685 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
686 << FixItHint::CreateRemoval(
687 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000688 continue;
689 }
690
Richard Smith0d8e9642013-05-16 06:20:58 +0000691 // C++11 [expr.prim.lambda]p10:
692 // The identifiers in a capture-list are looked up using the usual
693 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000694 DeclarationNameInfo Name(C->Id, C->Loc);
695 LookupResult R(*this, Name, LookupOrdinaryName);
696 LookupName(R, CurScope);
697 if (R.isAmbiguous())
698 continue;
699 if (R.empty()) {
700 // FIXME: Disable corrections that would add qualification?
701 CXXScopeSpec ScopeSpec;
702 DeclFilterCCC<VarDecl> Validator;
703 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
704 continue;
705 }
706
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000707 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000708
709 // C++11 [expr.prim.lambda]p8:
710 // An identifier or this shall not appear more than once in a
711 // lambda-capture.
712 if (!CaptureNames.insert(C->Id)) {
713 if (Var && LSI->isCaptured(Var)) {
714 Diag(C->Loc, diag::err_capture_more_than_once)
715 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
716 << FixItHint::CreateRemoval(
717 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
718 } else
719 // Previous capture was an init-capture: no fixit.
720 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
721 continue;
722 }
723
724 // C++11 [expr.prim.lambda]p10:
725 // [...] each such lookup shall find a variable with automatic storage
726 // duration declared in the reaching scope of the local lambda expression.
727 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000728 if (!Var) {
729 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
730 continue;
731 }
732
Eli Friedman9cd5b242012-09-18 21:11:30 +0000733 // Ignore invalid decls; they'll just confuse the code later.
734 if (Var->isInvalidDecl())
735 continue;
736
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000737 if (!Var->hasLocalStorage()) {
738 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
739 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
740 continue;
741 }
742
Douglas Gregora7365242012-02-14 19:27:52 +0000743 // C++11 [expr.prim.lambda]p23:
744 // A capture followed by an ellipsis is a pack expansion (14.5.3).
745 SourceLocation EllipsisLoc;
746 if (C->EllipsisLoc.isValid()) {
747 if (Var->isParameterPack()) {
748 EllipsisLoc = C->EllipsisLoc;
749 } else {
750 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
751 << SourceRange(C->Loc);
752
753 // Just ignore the ellipsis.
754 }
755 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000756 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000757 }
758
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000759 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
760 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000761 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000762 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000763 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000764
Richard Smith612409e2012-07-25 03:56:55 +0000765 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
766
Douglas Gregorc6889e72012-02-14 22:28:59 +0000767 // Add lambda parameters into scope.
768 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000769
Douglas Gregordfca6f52012-02-13 22:00:16 +0000770 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000771 // cleanups from the enclosing full-expression.
772 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773}
774
Douglas Gregordfca6f52012-02-13 22:00:16 +0000775void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
776 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000777 // Leave the expression-evaluation context.
778 DiscardCleanupsInEvaluationContext();
779 PopExpressionEvaluationContext();
780
781 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000782 if (!IsInstantiation)
783 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000784
785 // Finalize the lambda.
786 LambdaScopeInfo *LSI = getCurLambda();
787 CXXRecordDecl *Class = LSI->Lambda;
788 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000789 SmallVector<Decl*, 4> Fields;
790 for (RecordDecl::field_iterator i = Class->field_begin(),
791 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000792 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000793 ActOnFields(0, Class->getLocation(), Class, Fields,
794 SourceLocation(), SourceLocation(), 0);
795 CheckCompletedCXXClass(Class);
796
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000797 PopFunctionScopeInfo();
798}
799
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000800/// \brief Add a lambda's conversion to function pointer, as described in
801/// C++11 [expr.prim.lambda]p6.
802static void addFunctionPointerConversion(Sema &S,
803 SourceRange IntroducerRange,
804 CXXRecordDecl *Class,
805 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000806 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000807 const FunctionProtoType *Proto
808 = CallOperator->getType()->getAs<FunctionProtoType>();
809 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000810 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000811 {
812 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
813 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000814 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
815 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000816 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
817 }
818
819 FunctionProtoType::ExtProtoInfo ExtInfo;
820 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000821 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000822 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000823
824 SourceLocation Loc = IntroducerRange.getBegin();
825 DeclarationName Name
826 = S.Context.DeclarationNames.getCXXConversionFunctionName(
827 S.Context.getCanonicalType(FunctionPtrTy));
828 DeclarationNameLoc NameLoc;
829 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
830 Loc);
831 CXXConversionDecl *Conversion
832 = CXXConversionDecl::Create(S.Context, Class, Loc,
833 DeclarationNameInfo(Name, Loc, NameLoc),
834 ConvTy,
835 S.Context.getTrivialTypeSourceInfo(ConvTy,
836 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000837 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000838 /*isConstexpr=*/false,
839 CallOperator->getBody()->getLocEnd());
840 Conversion->setAccess(AS_public);
841 Conversion->setImplicit(true);
842 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000843
844 // Add a non-static member function "__invoke" that will be the result of
845 // the conversion.
846 Name = &S.Context.Idents.get("__invoke");
847 CXXMethodDecl *Invoke
848 = CXXMethodDecl::Create(S.Context, Class, Loc,
849 DeclarationNameInfo(Name, Loc), FunctionTy,
850 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000851 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000852 /*IsConstexpr=*/false,
853 CallOperator->getBody()->getLocEnd());
854 SmallVector<ParmVarDecl *, 4> InvokeParams;
855 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
856 ParmVarDecl *From = CallOperator->getParamDecl(I);
857 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
858 From->getLocStart(),
859 From->getLocation(),
860 From->getIdentifier(),
861 From->getType(),
862 From->getTypeSourceInfo(),
863 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000864 /*DefaultArg=*/0));
865 }
866 Invoke->setParams(InvokeParams);
867 Invoke->setAccess(AS_private);
868 Invoke->setImplicit(true);
869 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000870}
871
Douglas Gregorc2956e52012-02-15 22:08:38 +0000872/// \brief Add a lambda's conversion to block pointer.
873static void addBlockPointerConversion(Sema &S,
874 SourceRange IntroducerRange,
875 CXXRecordDecl *Class,
876 CXXMethodDecl *CallOperator) {
877 const FunctionProtoType *Proto
878 = CallOperator->getType()->getAs<FunctionProtoType>();
879 QualType BlockPtrTy;
880 {
881 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
882 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000883 QualType FunctionTy = S.Context.getFunctionType(
884 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000885 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
886 }
887
888 FunctionProtoType::ExtProtoInfo ExtInfo;
889 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000890 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000891
892 SourceLocation Loc = IntroducerRange.getBegin();
893 DeclarationName Name
894 = S.Context.DeclarationNames.getCXXConversionFunctionName(
895 S.Context.getCanonicalType(BlockPtrTy));
896 DeclarationNameLoc NameLoc;
897 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
898 CXXConversionDecl *Conversion
899 = CXXConversionDecl::Create(S.Context, Class, Loc,
900 DeclarationNameInfo(Name, Loc, NameLoc),
901 ConvTy,
902 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
903 /*isInline=*/false, /*isExplicit=*/false,
904 /*isConstexpr=*/false,
905 CallOperator->getBody()->getLocEnd());
906 Conversion->setAccess(AS_public);
907 Conversion->setImplicit(true);
908 Class->addDecl(Conversion);
909}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000910
Douglas Gregordfca6f52012-02-13 22:00:16 +0000911ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000912 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000913 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000914 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000915 SmallVector<LambdaExpr::Capture, 4> Captures;
916 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000917 LambdaCaptureDefault CaptureDefault;
918 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000919 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000920 SourceRange IntroducerRange;
921 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000922 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000923 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000924 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000925 SmallVector<VarDecl *, 4> ArrayIndexVars;
926 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000927 {
928 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000929 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000930 Class = LSI->Lambda;
931 IntroducerRange = LSI->IntroducerRange;
932 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000933 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000934 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000935 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000936 ArrayIndexVars.swap(LSI->ArrayIndexVars);
937 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
938
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000939 // Translate captures.
940 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
941 LambdaScopeInfo::Capture From = LSI->Captures[I];
942 assert(!From.isBlockCapture() && "Cannot capture __block variables");
943 bool IsImplicit = I >= LSI->NumExplicitCaptures;
944
945 // Handle 'this' capture.
946 if (From.isThisCapture()) {
947 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
948 IsImplicit,
949 LCK_This));
950 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
951 getCurrentThisType(),
952 /*isImplicit=*/true));
953 continue;
954 }
955
Richard Smith0d8e9642013-05-16 06:20:58 +0000956 if (From.isInitCapture()) {
957 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
958 CaptureInits.push_back(From.getInitExpr());
959 continue;
960 }
961
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000962 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000963 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
964 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000965 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000966 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000967 }
968
969 switch (LSI->ImpCaptureStyle) {
970 case CapturingScopeInfo::ImpCap_None:
971 CaptureDefault = LCD_None;
972 break;
973
974 case CapturingScopeInfo::ImpCap_LambdaByval:
975 CaptureDefault = LCD_ByCopy;
976 break;
977
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000978 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000979 case CapturingScopeInfo::ImpCap_LambdaByref:
980 CaptureDefault = LCD_ByRef;
981 break;
982
983 case CapturingScopeInfo::ImpCap_Block:
984 llvm_unreachable("block capture in lambda");
985 break;
986 }
987
Douglas Gregor54042f12012-02-09 10:18:50 +0000988 // C++11 [expr.prim.lambda]p4:
989 // If a lambda-expression does not include a
990 // trailing-return-type, it is as if the trailing-return-type
991 // denotes the following type:
992 // FIXME: Assumes current resolution to core issue 975.
993 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000994 deduceClosureReturnType(*LSI);
995
Douglas Gregor54042f12012-02-09 10:18:50 +0000996 // - if there are no return statements in the
997 // compound-statement, or all return statements return
998 // either an expression of type void or no expression or
999 // braced-init-list, the type void;
1000 if (LSI->ReturnType.isNull()) {
1001 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001002 }
1003
1004 // Create a function type with the inferred return type.
1005 const FunctionProtoType *Proto
1006 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001007 QualType FunctionTy = Context.getFunctionType(
1008 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001009 CallOperator->setType(FunctionTy);
1010 }
1011
Douglas Gregor215e4e12012-02-12 17:34:23 +00001012 // C++ [expr.prim.lambda]p7:
1013 // The lambda-expression's compound-statement yields the
1014 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001015 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001016 CallOperator->setLexicalDeclContext(Class);
1017 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001018 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001019
Douglas Gregorb5559712012-02-10 16:13:20 +00001020 // C++11 [expr.prim.lambda]p6:
1021 // The closure type for a lambda-expression with no lambda-capture
1022 // has a public non-virtual non-explicit const conversion function
1023 // to pointer to function having the same parameter and return
1024 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001025 if (Captures.empty() && CaptureDefault == LCD_None)
1026 addFunctionPointerConversion(*this, IntroducerRange, Class,
1027 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001028
Douglas Gregorc2956e52012-02-15 22:08:38 +00001029 // Objective-C++:
1030 // The closure type for a lambda-expression has a public non-virtual
1031 // non-explicit const conversion function to a block pointer having the
1032 // same parameter and return types as the closure type's function call
1033 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001034 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001035 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1036
Douglas Gregorb5559712012-02-10 16:13:20 +00001037 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001038 SmallVector<Decl*, 4> Fields;
1039 for (RecordDecl::field_iterator i = Class->field_begin(),
1040 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001041 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001042 ActOnFields(0, Class->getLocation(), Class, Fields,
1043 SourceLocation(), SourceLocation(), 0);
1044 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001045 }
1046
Douglas Gregor503384f2012-02-09 00:47:04 +00001047 if (LambdaExprNeedsCleanups)
1048 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001049
Douglas Gregore2c59132012-02-09 08:14:43 +00001050 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1051 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001052 ExplicitParams, ExplicitResultType,
1053 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001054 ArrayIndexStarts, Body->getLocEnd(),
1055 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +00001056
1057 // C++11 [expr.prim.lambda]p2:
1058 // A lambda-expression shall not appear in an unevaluated operand
1059 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001060 if (!CurContext->isDependentContext()) {
1061 switch (ExprEvalContexts.back().Context) {
1062 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001063 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001064 // We don't actually diagnose this case immediately, because we
1065 // could be within a context where we might find out later that
1066 // the expression is potentially evaluated (e.g., for typeid).
1067 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1068 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001069
Douglas Gregord5387e82012-02-14 00:00:48 +00001070 case ConstantEvaluated:
1071 case PotentiallyEvaluated:
1072 case PotentiallyEvaluatedIfUsed:
1073 break;
1074 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001075 }
Douglas Gregord5387e82012-02-14 00:00:48 +00001076
Douglas Gregor503384f2012-02-09 00:47:04 +00001077 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001078}
Eli Friedman23f02672012-03-01 04:01:32 +00001079
1080ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1081 SourceLocation ConvLocation,
1082 CXXConversionDecl *Conv,
1083 Expr *Src) {
1084 // Make sure that the lambda call operator is marked used.
1085 CXXRecordDecl *Lambda = Conv->getParent();
1086 CXXMethodDecl *CallOperator
1087 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001088 Lambda->lookup(
1089 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001090 CallOperator->setReferenced();
1091 CallOperator->setUsed();
1092
1093 ExprResult Init = PerformCopyInitialization(
1094 InitializedEntity::InitializeBlock(ConvLocation,
1095 Src->getType(),
1096 /*NRVO=*/false),
1097 CurrentLocation, Src);
1098 if (!Init.isInvalid())
1099 Init = ActOnFinishFullExpr(Init.take());
1100
1101 if (Init.isInvalid())
1102 return ExprError();
1103
1104 // Create the new block to be returned.
1105 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1106
1107 // Set the type information.
1108 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1109 Block->setIsVariadic(CallOperator->isVariadic());
1110 Block->setBlockMissingReturnType(false);
1111
1112 // Add parameters.
1113 SmallVector<ParmVarDecl *, 4> BlockParams;
1114 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1115 ParmVarDecl *From = CallOperator->getParamDecl(I);
1116 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1117 From->getLocStart(),
1118 From->getLocation(),
1119 From->getIdentifier(),
1120 From->getType(),
1121 From->getTypeSourceInfo(),
1122 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001123 /*DefaultArg=*/0));
1124 }
1125 Block->setParams(BlockParams);
1126
1127 Block->setIsConversionFromLambda(true);
1128
1129 // Add capture. The capture uses a fake variable, which doesn't correspond
1130 // to any actual memory location. However, the initializer copy-initializes
1131 // the lambda object.
1132 TypeSourceInfo *CapVarTSI =
1133 Context.getTrivialTypeSourceInfo(Src->getType());
1134 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1135 ConvLocation, 0,
1136 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001137 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001138 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1139 /*Nested=*/false, /*Copy=*/Init.take());
1140 Block->setCaptures(Context, &Capture, &Capture + 1,
1141 /*CapturesCXXThis=*/false);
1142
1143 // Add a fake function body to the block. IR generation is responsible
1144 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001145 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001146
1147 // Create the block literal expression.
1148 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1149 ExprCleanupObjects.push_back(Block);
1150 ExprNeedsCleanups = true;
1151
1152 return BuildBlock;
1153}