blob: ae3a938333f828bf6de595bb4d5843ff78d2585c [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
Eli Friedman07369dd2013-07-01 20:22:57 +000055MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000056Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000057 Decl *&ManglingContextDecl) {
58 // Compute the context for allocating mangling numbers in the current
59 // expression, if the ABI requires them.
60 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
61
62 enum ContextKind {
63 Normal,
64 DefaultArgument,
65 DataMember,
66 StaticDataMember
67 } Kind = Normal;
68
69 // Default arguments of member function parameters that appear in a class
70 // definition, as well as the initializers of data members, receive special
71 // treatment. Identify them.
72 if (ManglingContextDecl) {
73 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
74 if (const DeclContext *LexicalDC
75 = Param->getDeclContext()->getLexicalParent())
76 if (LexicalDC->isRecord())
77 Kind = DefaultArgument;
78 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
79 if (Var->getDeclContext()->isRecord())
80 Kind = StaticDataMember;
81 } else if (isa<FieldDecl>(ManglingContextDecl)) {
82 Kind = DataMember;
83 }
84 }
85
86 // Itanium ABI [5.1.7]:
87 // In the following contexts [...] the one-definition rule requires closure
88 // types in different translation units to "correspond":
89 bool IsInNonspecializedTemplate =
90 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
91 switch (Kind) {
92 case Normal:
93 // -- the bodies of non-exported nonspecialized template functions
94 // -- the bodies of inline functions
95 if ((IsInNonspecializedTemplate &&
96 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
97 isInInlineFunction(CurContext)) {
98 ManglingContextDecl = 0;
99 return &Context.getManglingNumberContext(DC);
100 }
101
102 ManglingContextDecl = 0;
103 return 0;
104
105 case StaticDataMember:
106 // -- the initializers of nonspecialized static members of template classes
107 if (!IsInNonspecializedTemplate) {
108 ManglingContextDecl = 0;
109 return 0;
110 }
111 // Fall through to get the current context.
112
113 case DataMember:
114 // -- the in-class initializers of class members
115 case DefaultArgument:
116 // -- default arguments appearing in class definitions
117 return &ExprEvalContexts.back().getMangleNumberingContext();
118 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000119
120 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000121}
122
Douglas Gregordfca6f52012-02-13 22:00:16 +0000123CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000124 SourceRange IntroducerRange,
125 TypeSourceInfo *MethodType,
126 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000127 ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000128 // C++11 [expr.prim.lambda]p5:
129 // The closure type for a lambda-expression has a public inline function
130 // call operator (13.5.4) whose parameters and return type are described by
131 // the lambda-expression's parameter-declaration-clause and
132 // trailing-return-type respectively.
133 DeclarationName MethodName
134 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
135 DeclarationNameLoc MethodNameLoc;
136 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
137 = IntroducerRange.getBegin().getRawEncoding();
138 MethodNameLoc.CXXOperatorName.EndOpNameLoc
139 = IntroducerRange.getEnd().getRawEncoding();
140 CXXMethodDecl *Method
141 = CXXMethodDecl::Create(Context, Class, EndLoc,
142 DeclarationNameInfo(MethodName,
143 IntroducerRange.getBegin(),
144 MethodNameLoc),
145 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000146 SC_None,
147 /*isInline=*/true,
148 /*isConstExpr=*/false,
149 EndLoc);
150 Method->setAccess(AS_public);
151
152 // Temporarily set the lexical declaration context to the current
153 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000154 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000155
Douglas Gregorc6889e72012-02-14 22:28:59 +0000156 // Add parameters.
157 if (!Params.empty()) {
158 Method->setParams(Params);
159 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
160 const_cast<ParmVarDecl **>(Params.end()),
161 /*CheckParameterNames=*/false);
162
163 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
164 PEnd = Method->param_end();
165 P != PEnd; ++P)
166 (*P)->setOwningFunction(Method);
167 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000168
Eli Friedman07369dd2013-07-01 20:22:57 +0000169 Decl *ManglingContextDecl;
170 if (MangleNumberingContext *MCtx =
171 getCurrentMangleNumberContext(Class->getDeclContext(),
172 ManglingContextDecl)) {
173 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
174 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000175 }
176
Douglas Gregordfca6f52012-02-13 22:00:16 +0000177 return Method;
178}
179
Manuel Klimek152b4e42013-08-22 12:12:24 +0000180LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000181 SourceRange IntroducerRange,
182 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000183 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000184 bool ExplicitParams,
185 bool ExplicitResultType,
186 bool Mutable) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000187 PushLambdaScope(CallOperator->getParent(), CallOperator);
188 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000189 if (CaptureDefault == LCD_ByCopy)
190 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
191 else if (CaptureDefault == LCD_ByRef)
192 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000193 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000194 LSI->IntroducerRange = IntroducerRange;
195 LSI->ExplicitParams = ExplicitParams;
196 LSI->Mutable = Mutable;
197
198 if (ExplicitResultType) {
199 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000200
201 if (!LSI->ReturnType->isDependentType() &&
202 !LSI->ReturnType->isVoidType()) {
203 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
204 diag::err_lambda_incomplete_result)) {
205 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000206 }
207 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000208 } else {
209 LSI->HasImplicitReturnType = true;
210 }
Manuel Klimek152b4e42013-08-22 12:12:24 +0000211
212 return LSI;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000213}
214
215void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
216 LSI->finishedExplicitCaptures();
217}
218
Douglas Gregorc6889e72012-02-14 22:28:59 +0000219void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000220 // Introduce our parameters into the function scope
221 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
222 p < NumParams; ++p) {
223 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000224
225 // If this has an identifier, add it to the scope stack.
226 if (CurScope && Param->getIdentifier()) {
227 CheckShadow(CurScope, Param);
228
229 PushOnScopeChains(Param, CurScope);
230 }
231 }
232}
233
John McCall41d01642013-03-09 00:54:31 +0000234/// If this expression is an enumerator-like expression of some type
235/// T, return the type T; otherwise, return null.
236///
237/// Pointer comparisons on the result here should always work because
238/// it's derived from either the parent of an EnumConstantDecl
239/// (i.e. the definition) or the declaration returned by
240/// EnumType::getDecl() (i.e. the definition).
241static EnumDecl *findEnumForBlockReturn(Expr *E) {
242 // An expression is an enumerator-like expression of type T if,
243 // ignoring parens and parens-like expressions:
244 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000245
John McCall41d01642013-03-09 00:54:31 +0000246 // - it is an enumerator whose enum type is T or
247 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
248 if (EnumConstantDecl *D
249 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
250 return cast<EnumDecl>(D->getDeclContext());
251 }
252 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000253 }
254
John McCall41d01642013-03-09 00:54:31 +0000255 // - it is a comma expression whose RHS is an enumerator-like
256 // expression of type T or
257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
258 if (BO->getOpcode() == BO_Comma)
259 return findEnumForBlockReturn(BO->getRHS());
260 return 0;
261 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000262
John McCall41d01642013-03-09 00:54:31 +0000263 // - it is a statement-expression whose value expression is an
264 // enumerator-like expression of type T or
265 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
266 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
267 return findEnumForBlockReturn(last);
268 return 0;
269 }
270
271 // - it is a ternary conditional operator (not the GNU ?:
272 // extension) whose second and third operands are
273 // enumerator-like expressions of type T or
274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
275 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
276 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
277 return ED;
278 return 0;
279 }
280
281 // (implicitly:)
282 // - it is an implicit integral conversion applied to an
283 // enumerator-like expression of type T or
284 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000285 // We can sometimes see integral conversions in valid
286 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000287 if (ICE->getCastKind() == CK_IntegralCast)
288 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000289
290 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000291 }
292
293 // - it is an expression of that formal enum type.
294 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
295 return ET->getDecl();
296 }
297
298 // Otherwise, nope.
299 return 0;
300}
301
302/// Attempt to find a type T for which the returned expression of the
303/// given statement is an enumerator-like expression of that type.
304static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
305 if (Expr *retValue = ret->getRetValue())
306 return findEnumForBlockReturn(retValue);
307 return 0;
308}
309
310/// Attempt to find a common type T for which all of the returned
311/// expressions in a block are enumerator-like expressions of that
312/// type.
313static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
314 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
315
316 // Try to find one for the first return.
317 EnumDecl *ED = findEnumForBlockReturn(*i);
318 if (!ED) return 0;
319
320 // Check that the rest of the returns have the same enum.
321 for (++i; i != e; ++i) {
322 if (findEnumForBlockReturn(*i) != ED)
323 return 0;
324 }
325
326 // Never infer an anonymous enum type.
327 if (!ED->hasNameForLinkage()) return 0;
328
329 return ED;
330}
331
332/// Adjust the given return statements so that they formally return
333/// the given type. It should require, at most, an IntegralCast.
334static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
335 QualType returnType) {
336 for (ArrayRef<ReturnStmt*>::iterator
337 i = returns.begin(), e = returns.end(); i != e; ++i) {
338 ReturnStmt *ret = *i;
339 Expr *retValue = ret->getRetValue();
340 if (S.Context.hasSameType(retValue->getType(), returnType))
341 continue;
342
343 // Right now we only support integral fixup casts.
344 assert(returnType->isIntegralOrUnscopedEnumerationType());
345 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
346
347 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
348
349 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
350 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
351 E, /*base path*/ 0, VK_RValue);
352 if (cleanups) {
353 cleanups->setSubExpr(E);
354 } else {
355 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000356 }
357 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000358}
359
360void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000361 assert(CSI.HasImplicitReturnType);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000362
John McCall41d01642013-03-09 00:54:31 +0000363 // C++ Core Issue #975, proposed resolution:
364 // If a lambda-expression does not include a trailing-return-type,
365 // it is as if the trailing-return-type denotes the following type:
366 // - if there are no return statements in the compound-statement,
367 // or all return statements return either an expression of type
368 // void or no expression or braced-init-list, the type void;
369 // - otherwise, if all return statements return an expression
370 // and the types of the returned expressions after
371 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
372 // array-to-pointer conversion (4.2 [conv.array]), and
373 // function-to-pointer conversion (4.3 [conv.func]) are the
374 // same, that common type;
375 // - otherwise, the program is ill-formed.
376 //
377 // In addition, in blocks in non-C++ modes, if all of the return
378 // statements are enumerator-like expressions of some type T, where
379 // T has a name for linkage, then we infer the return type of the
380 // block to be that type.
381
Jordan Rose7dd900e2012-07-02 21:19:23 +0000382 // First case: no return statements, implicit void return type.
383 ASTContext &Ctx = getASTContext();
384 if (CSI.Returns.empty()) {
385 // It's possible there were simply no /valid/ return statements.
386 // In this case, the first one we found may have at least given us a type.
387 if (CSI.ReturnType.isNull())
388 CSI.ReturnType = Ctx.VoidTy;
389 return;
390 }
391
392 // Second case: at least one return statement has dependent type.
393 // Delay type checking until instantiation.
394 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000395 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000396 return;
397
John McCall41d01642013-03-09 00:54:31 +0000398 // Try to apply the enum-fuzz rule.
399 if (!getLangOpts().CPlusPlus) {
400 assert(isa<BlockScopeInfo>(CSI));
401 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
402 if (ED) {
403 CSI.ReturnType = Context.getTypeDeclType(ED);
404 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
405 return;
406 }
407 }
408
Jordan Rose7dd900e2012-07-02 21:19:23 +0000409 // Third case: only one return statement. Don't bother doing extra work!
410 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
411 E = CSI.Returns.end();
412 if (I+1 == E)
413 return;
414
415 // General case: many return statements.
416 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000417
418 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000419 // Note that we've already done the required promotions as part of
420 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000421 for (; I != E; ++I) {
422 const ReturnStmt *RS = *I;
423 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000424
John McCall41d01642013-03-09 00:54:31 +0000425 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
426 if (Context.hasSameType(ReturnType, CSI.ReturnType))
427 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000428
John McCall41d01642013-03-09 00:54:31 +0000429 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
430 // TODO: It's possible that the *first* return is the divergent one.
431 Diag(RS->getLocStart(),
432 diag::err_typecheck_missing_return_type_incompatible)
433 << ReturnType << CSI.ReturnType
434 << isa<LambdaScopeInfo>(CSI);
435 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000436 }
437}
438
Richard Smith0d8e9642013-05-16 06:20:58 +0000439FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
440 IdentifierInfo *Id, Expr *InitExpr) {
441 LambdaScopeInfo *LSI = getCurLambda();
442
443 // C++1y [expr.prim.lambda]p11:
444 // The type of [the] member corresponds to the type of a hypothetical
445 // variable declaration of the form "auto init-capture;"
446 QualType DeductType = Context.getAutoDeductType();
447 TypeLocBuilder TLB;
448 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
449 if (ByRef) {
450 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
451 assert(!DeductType.isNull() && "can't build reference to auto");
452 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
453 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000454 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000455
456 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
457 Expr *Init = InitExpr;
458 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
459 if (Parens->getNumExprs() == 1) {
460 Init = Parens->getExpr(0);
461 InitKind = InitializationKind::CreateDirect(
462 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
463 } else {
464 // C++1y [dcl.spec.auto]p3:
465 // In an initializer of the form ( expression-list ), the
466 // expression-list shall be a single assignment-expression.
467 if (Parens->getNumExprs() == 0)
468 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
469 << Id;
470 else if (Parens->getNumExprs() > 1)
471 Diag(Parens->getExpr(1)->getLocStart(),
472 diag::err_init_capture_multiple_expressions)
473 << Id;
474 return 0;
475 }
476 } else if (isa<InitListExpr>(Init))
477 // We do not need to distinguish between direct-list-initialization
478 // and copy-list-initialization here, because we will always deduce
479 // std::initializer_list<T>, and direct- and copy-list-initialization
480 // always behave the same for such a type.
481 // FIXME: We should model whether an '=' was present.
482 InitKind = InitializationKind::CreateDirectList(Loc);
483 else
484 InitKind = InitializationKind::CreateCopy(Loc, Loc);
485 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000486 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000487 if (isa<InitListExpr>(Init))
488 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
489 << Id << Init->getSourceRange();
490 else
491 Diag(Loc, diag::err_init_capture_deduction_failure)
492 << Id << Init->getType() << Init->getSourceRange();
493 }
494 if (DeducedType.isNull())
495 return 0;
496
497 // [...] a non-static data member named by the identifier is declared in
498 // the closure type. This member is not a bit-field and not mutable.
499 // Core issue: the member is (probably...) public.
500 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000501 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000502 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
503 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
504 LSI->Lambda->addDecl(NewFD);
505
506 if (CurContext->isDependentContext()) {
507 LSI->addInitCapture(NewFD, InitExpr);
508 } else {
509 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
510 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
511 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
512 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
513 if (!InitResult.isInvalid())
514 LSI->addInitCapture(NewFD, InitResult.take());
515 }
516 }
517
518 return NewFD;
519}
520
Douglas Gregordfca6f52012-02-13 22:00:16 +0000521void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Manuel Klimek152b4e42013-08-22 12:12:24 +0000522 Declarator &ParamInfo,
523 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000524 // Determine if we're within a context where we know that the lambda will
525 // be dependent, because there are template parameters in scope.
526 bool KnownDependent = false;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000527 if (Scope *TmplScope = CurScope->getTemplateParamParent())
528 if (!TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000529 KnownDependent = true;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000530
Douglas Gregordfca6f52012-02-13 22:00:16 +0000531 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000532 TypeSourceInfo *MethodTyInfo;
533 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000534 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000535 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000536 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000537 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000538 if (ParamInfo.getNumTypeObjects() == 0) {
539 // C++11 [expr.prim.lambda]p4:
540 // If a lambda-expression does not include a lambda-declarator, it is as
541 // if the lambda-declarator were ().
542 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000543 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000544 EPI.TypeQuals |= DeclSpec::TQ_const;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000545 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000546 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000547 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
548 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000549 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000550 EndLoc = Intro.Range.getEnd();
551 } else {
552 assert(ParamInfo.isFunctionDeclarator() &&
553 "lambda-declarator is a function");
554 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
555
556 // C++11 [expr.prim.lambda]p5:
557 // This function call operator is declared const (9.3.1) if and only if
558 // the lambda-expression's parameter-declaration-clause is not followed
559 // by mutable. It is neither virtual nor declared volatile. [...]
560 if (!FTI.hasMutableQualifier())
561 FTI.TypeQuals |= DeclSpec::TQ_const;
562
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000563 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000564 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000565 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000566
Manuel Klimek152b4e42013-08-22 12:12:24 +0000567 ExplicitResultType
568 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
569 != Context.DependentTy;
570
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000571 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
572 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
573 // Empty arg list, don't push any params.
574 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
575 } else {
576 Params.reserve(FTI.NumArgs);
577 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
578 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
579 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000580
581 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000582 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
583 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000584 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000585
586 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
587 KnownDependent);
588
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000589 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000590 MethodTyInfo, EndLoc, Params);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000591
Douglas Gregorc6889e72012-02-14 22:28:59 +0000592 if (ExplicitParams)
593 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000594
Bill Wendlingad017fa2012-12-20 19:22:21 +0000595 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000596 ProcessDeclAttributes(CurScope, Method, ParamInfo);
597
Douglas Gregor503384f2012-02-09 00:47:04 +0000598 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000599 PushDeclContext(CurScope, Method);
600
Manuel Klimek152b4e42013-08-22 12:12:24 +0000601 // Introduce the lambda scope.
602 LambdaScopeInfo *LSI
603 = enterLambdaScope(Method,
James Dennettf68af642013-08-09 23:08:25 +0000604 Intro.Range,
605 Intro.Default, Intro.DefaultLoc,
606 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000607 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000608 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000609
610 // Distinct capture names, for diagnostics.
611 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
612
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000613 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000614 SourceLocation PrevCaptureLoc
615 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000616 for (SmallVectorImpl<LambdaCapture>::const_iterator
617 C = Intro.Captures.begin(),
618 E = Intro.Captures.end();
619 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000620 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000621 if (C->Kind == LCK_This) {
622 // C++11 [expr.prim.lambda]p8:
623 // An identifier or this shall not appear more than once in a
624 // lambda-capture.
625 if (LSI->isCXXThisCaptured()) {
626 Diag(C->Loc, diag::err_capture_more_than_once)
627 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000628 << SourceRange(LSI->getCXXThisCapture().getLocation())
629 << FixItHint::CreateRemoval(
630 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000631 continue;
632 }
633
634 // C++11 [expr.prim.lambda]p8:
635 // If a lambda-capture includes a capture-default that is =, the
636 // lambda-capture shall not contain this [...].
637 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000638 Diag(C->Loc, diag::err_this_capture_with_copy_default)
639 << FixItHint::CreateRemoval(
640 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000641 continue;
642 }
643
644 // C++11 [expr.prim.lambda]p12:
645 // If this is captured by a local lambda expression, its nearest
646 // enclosing function shall be a non-static member function.
647 QualType ThisCaptureType = getCurrentThisType();
648 if (ThisCaptureType.isNull()) {
649 Diag(C->Loc, diag::err_this_capture) << true;
650 continue;
651 }
652
653 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
654 continue;
655 }
656
Richard Smith0d8e9642013-05-16 06:20:58 +0000657 assert(C->Id && "missing identifier for capture");
658
Richard Smith0a664b82013-05-09 21:36:41 +0000659 if (C->Init.isInvalid())
660 continue;
661 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000662 // C++11 [expr.prim.lambda]p8:
663 // An identifier or this shall not appear more than once in a
664 // lambda-capture.
665 if (!CaptureNames.insert(C->Id))
666 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
667
668 if (C->Init.get()->containsUnexpandedParameterPack())
669 ContainsUnexpandedParameterPack = true;
670
671 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
672 C->Id, C->Init.take());
673 // C++1y [expr.prim.lambda]p11:
674 // Within the lambda-expression's lambda-declarator and
675 // compound-statement, the identifier in the init-capture
676 // hides any declaration of the same name in scopes enclosing
677 // the lambda-expression.
678 if (NewFD)
679 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000680 continue;
681 }
682
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000683 // C++11 [expr.prim.lambda]p8:
684 // If a lambda-capture includes a capture-default that is &, the
685 // identifiers in the lambda-capture shall not be preceded by &.
686 // If a lambda-capture includes a capture-default that is =, [...]
687 // each identifier it contains shall be preceded by &.
688 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000689 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
690 << FixItHint::CreateRemoval(
691 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000692 continue;
693 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000694 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
695 << FixItHint::CreateRemoval(
696 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000697 continue;
698 }
699
Richard Smith0d8e9642013-05-16 06:20:58 +0000700 // C++11 [expr.prim.lambda]p10:
701 // The identifiers in a capture-list are looked up using the usual
702 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000703 DeclarationNameInfo Name(C->Id, C->Loc);
704 LookupResult R(*this, Name, LookupOrdinaryName);
705 LookupName(R, CurScope);
706 if (R.isAmbiguous())
707 continue;
708 if (R.empty()) {
709 // FIXME: Disable corrections that would add qualification?
710 CXXScopeSpec ScopeSpec;
711 DeclFilterCCC<VarDecl> Validator;
712 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
713 continue;
714 }
715
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000716 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000717
718 // C++11 [expr.prim.lambda]p8:
719 // An identifier or this shall not appear more than once in a
720 // lambda-capture.
721 if (!CaptureNames.insert(C->Id)) {
722 if (Var && LSI->isCaptured(Var)) {
723 Diag(C->Loc, diag::err_capture_more_than_once)
724 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
725 << FixItHint::CreateRemoval(
726 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
727 } else
728 // Previous capture was an init-capture: no fixit.
729 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
730 continue;
731 }
732
733 // C++11 [expr.prim.lambda]p10:
734 // [...] each such lookup shall find a variable with automatic storage
735 // duration declared in the reaching scope of the local lambda expression.
736 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000737 if (!Var) {
738 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
739 continue;
740 }
741
Eli Friedman9cd5b242012-09-18 21:11:30 +0000742 // Ignore invalid decls; they'll just confuse the code later.
743 if (Var->isInvalidDecl())
744 continue;
745
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746 if (!Var->hasLocalStorage()) {
747 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
748 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
749 continue;
750 }
751
Douglas Gregora7365242012-02-14 19:27:52 +0000752 // C++11 [expr.prim.lambda]p23:
753 // A capture followed by an ellipsis is a pack expansion (14.5.3).
754 SourceLocation EllipsisLoc;
755 if (C->EllipsisLoc.isValid()) {
756 if (Var->isParameterPack()) {
757 EllipsisLoc = C->EllipsisLoc;
758 } else {
759 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
760 << SourceRange(C->Loc);
761
762 // Just ignore the ellipsis.
763 }
764 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000765 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000766 }
767
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000768 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
769 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000770 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000771 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000772 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773
Richard Smith612409e2012-07-25 03:56:55 +0000774 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
775
Douglas Gregorc6889e72012-02-14 22:28:59 +0000776 // Add lambda parameters into scope.
777 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000778
Douglas Gregordfca6f52012-02-13 22:00:16 +0000779 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000780 // cleanups from the enclosing full-expression.
781 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000782}
783
Douglas Gregordfca6f52012-02-13 22:00:16 +0000784void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
785 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000786 // Leave the expression-evaluation context.
787 DiscardCleanupsInEvaluationContext();
788 PopExpressionEvaluationContext();
789
790 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000791 if (!IsInstantiation)
792 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000793
794 // Finalize the lambda.
795 LambdaScopeInfo *LSI = getCurLambda();
796 CXXRecordDecl *Class = LSI->Lambda;
797 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000798 SmallVector<Decl*, 4> Fields;
799 for (RecordDecl::field_iterator i = Class->field_begin(),
800 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000801 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000802 ActOnFields(0, Class->getLocation(), Class, Fields,
803 SourceLocation(), SourceLocation(), 0);
804 CheckCompletedCXXClass(Class);
805
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000806 PopFunctionScopeInfo();
807}
808
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000809/// \brief Add a lambda's conversion to function pointer, as described in
810/// C++11 [expr.prim.lambda]p6.
811static void addFunctionPointerConversion(Sema &S,
812 SourceRange IntroducerRange,
813 CXXRecordDecl *Class,
814 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000815 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000816 const FunctionProtoType *Proto
817 = CallOperator->getType()->getAs<FunctionProtoType>();
818 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000819 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000820 {
821 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
822 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000823 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
824 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000825 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
826 }
827
828 FunctionProtoType::ExtProtoInfo ExtInfo;
829 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000830 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000831 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000832
833 SourceLocation Loc = IntroducerRange.getBegin();
834 DeclarationName Name
835 = S.Context.DeclarationNames.getCXXConversionFunctionName(
836 S.Context.getCanonicalType(FunctionPtrTy));
837 DeclarationNameLoc NameLoc;
838 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
839 Loc);
840 CXXConversionDecl *Conversion
841 = CXXConversionDecl::Create(S.Context, Class, Loc,
842 DeclarationNameInfo(Name, Loc, NameLoc),
843 ConvTy,
844 S.Context.getTrivialTypeSourceInfo(ConvTy,
845 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000846 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000847 /*isConstexpr=*/false,
848 CallOperator->getBody()->getLocEnd());
849 Conversion->setAccess(AS_public);
850 Conversion->setImplicit(true);
851 Class->addDecl(Conversion);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000852
853 // Add a non-static member function "__invoke" that will be the result of
854 // the conversion.
855 Name = &S.Context.Idents.get("__invoke");
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000856 CXXMethodDecl *Invoke
857 = CXXMethodDecl::Create(S.Context, Class, Loc,
858 DeclarationNameInfo(Name, Loc), FunctionTy,
859 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000860 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000861 /*IsConstexpr=*/false,
862 CallOperator->getBody()->getLocEnd());
863 SmallVector<ParmVarDecl *, 4> InvokeParams;
864 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
865 ParmVarDecl *From = CallOperator->getParamDecl(I);
866 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
867 From->getLocStart(),
868 From->getLocation(),
869 From->getIdentifier(),
870 From->getType(),
871 From->getTypeSourceInfo(),
872 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000873 /*DefaultArg=*/0));
874 }
875 Invoke->setParams(InvokeParams);
876 Invoke->setAccess(AS_private);
877 Invoke->setImplicit(true);
878 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000879}
880
Douglas Gregorc2956e52012-02-15 22:08:38 +0000881/// \brief Add a lambda's conversion to block pointer.
882static void addBlockPointerConversion(Sema &S,
883 SourceRange IntroducerRange,
884 CXXRecordDecl *Class,
885 CXXMethodDecl *CallOperator) {
886 const FunctionProtoType *Proto
887 = CallOperator->getType()->getAs<FunctionProtoType>();
888 QualType BlockPtrTy;
889 {
890 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
891 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000892 QualType FunctionTy = S.Context.getFunctionType(
893 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000894 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
895 }
896
897 FunctionProtoType::ExtProtoInfo ExtInfo;
898 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000899 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000900
901 SourceLocation Loc = IntroducerRange.getBegin();
902 DeclarationName Name
903 = S.Context.DeclarationNames.getCXXConversionFunctionName(
904 S.Context.getCanonicalType(BlockPtrTy));
905 DeclarationNameLoc NameLoc;
906 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
907 CXXConversionDecl *Conversion
908 = CXXConversionDecl::Create(S.Context, Class, Loc,
909 DeclarationNameInfo(Name, Loc, NameLoc),
910 ConvTy,
911 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000912 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000913 /*isConstexpr=*/false,
914 CallOperator->getBody()->getLocEnd());
915 Conversion->setAccess(AS_public);
916 Conversion->setImplicit(true);
917 Class->addDecl(Conversion);
918}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000919
Douglas Gregordfca6f52012-02-13 22:00:16 +0000920ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000921 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000922 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000923 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000924 SmallVector<LambdaExpr::Capture, 4> Captures;
925 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000926 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +0000927 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000928 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000929 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000930 SourceRange IntroducerRange;
931 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000932 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000933 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000934 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000935 SmallVector<VarDecl *, 4> ArrayIndexVars;
936 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000937 {
938 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000939 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000940 Class = LSI->Lambda;
941 IntroducerRange = LSI->IntroducerRange;
942 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000943 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000944 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000945 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000946 ArrayIndexVars.swap(LSI->ArrayIndexVars);
947 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
948
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000949 // Translate captures.
950 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
951 LambdaScopeInfo::Capture From = LSI->Captures[I];
952 assert(!From.isBlockCapture() && "Cannot capture __block variables");
953 bool IsImplicit = I >= LSI->NumExplicitCaptures;
954
955 // Handle 'this' capture.
956 if (From.isThisCapture()) {
957 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
958 IsImplicit,
959 LCK_This));
960 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
961 getCurrentThisType(),
962 /*isImplicit=*/true));
963 continue;
964 }
965
Richard Smith0d8e9642013-05-16 06:20:58 +0000966 if (From.isInitCapture()) {
967 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
968 CaptureInits.push_back(From.getInitExpr());
969 continue;
970 }
971
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000972 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000973 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
974 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000975 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000976 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000977 }
978
979 switch (LSI->ImpCaptureStyle) {
980 case CapturingScopeInfo::ImpCap_None:
981 CaptureDefault = LCD_None;
982 break;
983
984 case CapturingScopeInfo::ImpCap_LambdaByval:
985 CaptureDefault = LCD_ByCopy;
986 break;
987
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000988 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000989 case CapturingScopeInfo::ImpCap_LambdaByref:
990 CaptureDefault = LCD_ByRef;
991 break;
992
993 case CapturingScopeInfo::ImpCap_Block:
994 llvm_unreachable("block capture in lambda");
995 break;
996 }
James Dennettf68af642013-08-09 23:08:25 +0000997 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000998
Douglas Gregor54042f12012-02-09 10:18:50 +0000999 // C++11 [expr.prim.lambda]p4:
1000 // If a lambda-expression does not include a
1001 // trailing-return-type, it is as if the trailing-return-type
1002 // denotes the following type:
1003 // FIXME: Assumes current resolution to core issue 975.
Manuel Klimek152b4e42013-08-22 12:12:24 +00001004 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001005 deduceClosureReturnType(*LSI);
1006
Douglas Gregor54042f12012-02-09 10:18:50 +00001007 // - if there are no return statements in the
1008 // compound-statement, or all return statements return
1009 // either an expression of type void or no expression or
1010 // braced-init-list, the type void;
1011 if (LSI->ReturnType.isNull()) {
1012 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001013 }
1014
1015 // Create a function type with the inferred return type.
1016 const FunctionProtoType *Proto
1017 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001018 QualType FunctionTy = Context.getFunctionType(
1019 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001020 CallOperator->setType(FunctionTy);
1021 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001022
Douglas Gregor215e4e12012-02-12 17:34:23 +00001023 // C++ [expr.prim.lambda]p7:
1024 // The lambda-expression's compound-statement yields the
1025 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001026 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001027 CallOperator->setLexicalDeclContext(Class);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001028 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001029 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001030
Douglas Gregorb5559712012-02-10 16:13:20 +00001031 // C++11 [expr.prim.lambda]p6:
1032 // The closure type for a lambda-expression with no lambda-capture
1033 // has a public non-virtual non-explicit const conversion function
1034 // to pointer to function having the same parameter and return
1035 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001036 if (Captures.empty() && CaptureDefault == LCD_None)
1037 addFunctionPointerConversion(*this, IntroducerRange, Class,
1038 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001039
Douglas Gregorc2956e52012-02-15 22:08:38 +00001040 // Objective-C++:
1041 // The closure type for a lambda-expression has a public non-virtual
1042 // non-explicit const conversion function to a block pointer having the
1043 // same parameter and return types as the closure type's function call
1044 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001045 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001046 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1047
Douglas Gregorb5559712012-02-10 16:13:20 +00001048 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001049 SmallVector<Decl*, 4> Fields;
1050 for (RecordDecl::field_iterator i = Class->field_begin(),
1051 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001052 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001053 ActOnFields(0, Class->getLocation(), Class, Fields,
1054 SourceLocation(), SourceLocation(), 0);
1055 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001056 }
1057
Douglas Gregor503384f2012-02-09 00:47:04 +00001058 if (LambdaExprNeedsCleanups)
1059 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001060
Douglas Gregore2c59132012-02-09 08:14:43 +00001061 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001062 CaptureDefault, CaptureDefaultLoc,
1063 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001064 ExplicitParams, ExplicitResultType,
1065 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001066 ArrayIndexStarts, Body->getLocEnd(),
1067 ContainsUnexpandedParameterPack);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001068
Douglas Gregore2c59132012-02-09 08:14:43 +00001069 // C++11 [expr.prim.lambda]p2:
1070 // A lambda-expression shall not appear in an unevaluated operand
1071 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001072 if (!CurContext->isDependentContext()) {
1073 switch (ExprEvalContexts.back().Context) {
1074 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001075 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001076 // We don't actually diagnose this case immediately, because we
1077 // could be within a context where we might find out later that
1078 // the expression is potentially evaluated (e.g., for typeid).
1079 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1080 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001081
Douglas Gregord5387e82012-02-14 00:00:48 +00001082 case ConstantEvaluated:
1083 case PotentiallyEvaluated:
1084 case PotentiallyEvaluatedIfUsed:
1085 break;
1086 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001087 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001088
Douglas Gregor503384f2012-02-09 00:47:04 +00001089 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001090}
Eli Friedman23f02672012-03-01 04:01:32 +00001091
1092ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1093 SourceLocation ConvLocation,
1094 CXXConversionDecl *Conv,
1095 Expr *Src) {
1096 // Make sure that the lambda call operator is marked used.
1097 CXXRecordDecl *Lambda = Conv->getParent();
1098 CXXMethodDecl *CallOperator
1099 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001100 Lambda->lookup(
1101 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001102 CallOperator->setReferenced();
1103 CallOperator->setUsed();
1104
1105 ExprResult Init = PerformCopyInitialization(
1106 InitializedEntity::InitializeBlock(ConvLocation,
1107 Src->getType(),
1108 /*NRVO=*/false),
1109 CurrentLocation, Src);
1110 if (!Init.isInvalid())
1111 Init = ActOnFinishFullExpr(Init.take());
1112
1113 if (Init.isInvalid())
1114 return ExprError();
1115
1116 // Create the new block to be returned.
1117 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1118
1119 // Set the type information.
1120 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1121 Block->setIsVariadic(CallOperator->isVariadic());
1122 Block->setBlockMissingReturnType(false);
1123
1124 // Add parameters.
1125 SmallVector<ParmVarDecl *, 4> BlockParams;
1126 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1127 ParmVarDecl *From = CallOperator->getParamDecl(I);
1128 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1129 From->getLocStart(),
1130 From->getLocation(),
1131 From->getIdentifier(),
1132 From->getType(),
1133 From->getTypeSourceInfo(),
1134 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001135 /*DefaultArg=*/0));
1136 }
1137 Block->setParams(BlockParams);
1138
1139 Block->setIsConversionFromLambda(true);
1140
1141 // Add capture. The capture uses a fake variable, which doesn't correspond
1142 // to any actual memory location. However, the initializer copy-initializes
1143 // the lambda object.
1144 TypeSourceInfo *CapVarTSI =
1145 Context.getTrivialTypeSourceInfo(Src->getType());
1146 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1147 ConvLocation, 0,
1148 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001149 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001150 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1151 /*Nested=*/false, /*Copy=*/Init.take());
1152 Block->setCaptures(Context, &Capture, &Capture + 1,
1153 /*CapturesCXXThis=*/false);
1154
1155 // Add a fake function body to the block. IR generation is responsible
1156 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001157 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001158
1159 // Create the block literal expression.
1160 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1161 ExprCleanupObjects.push_back(Block);
1162 ExprNeedsCleanups = true;
1163
1164 return BuildBlock;
1165}