blob: 3a796ad902573c85344b173e5294428532643a94 [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 ().
Reid Kleckneref072032013-08-27 23:08:25 +0000542 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
543 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000544 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000545 EPI.TypeQuals |= DeclSpec::TQ_const;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000546 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000547 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000548 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
549 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000550 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000551 EndLoc = Intro.Range.getEnd();
552 } else {
553 assert(ParamInfo.isFunctionDeclarator() &&
554 "lambda-declarator is a function");
555 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
556
557 // C++11 [expr.prim.lambda]p5:
558 // This function call operator is declared const (9.3.1) if and only if
559 // the lambda-expression's parameter-declaration-clause is not followed
560 // by mutable. It is neither virtual nor declared volatile. [...]
561 if (!FTI.hasMutableQualifier())
562 FTI.TypeQuals |= DeclSpec::TQ_const;
563
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000564 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000565 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000566 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000567
Manuel Klimek152b4e42013-08-22 12:12:24 +0000568 ExplicitResultType
569 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
570 != Context.DependentTy;
571
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000572 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
573 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
574 // Empty arg list, don't push any params.
575 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
576 } else {
577 Params.reserve(FTI.NumArgs);
578 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
579 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
580 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000581
582 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000583 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
584 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000585 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000586
587 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
588 KnownDependent);
589
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000590 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000591 MethodTyInfo, EndLoc, Params);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000592
Douglas Gregorc6889e72012-02-14 22:28:59 +0000593 if (ExplicitParams)
594 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000595
Bill Wendlingad017fa2012-12-20 19:22:21 +0000596 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000597 ProcessDeclAttributes(CurScope, Method, ParamInfo);
598
Douglas Gregor503384f2012-02-09 00:47:04 +0000599 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000600 PushDeclContext(CurScope, Method);
601
Manuel Klimek152b4e42013-08-22 12:12:24 +0000602 // Introduce the lambda scope.
603 LambdaScopeInfo *LSI
604 = enterLambdaScope(Method,
James Dennettf68af642013-08-09 23:08:25 +0000605 Intro.Range,
606 Intro.Default, Intro.DefaultLoc,
607 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000608 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000609 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000610
611 // Distinct capture names, for diagnostics.
612 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
613
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000614 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000615 SourceLocation PrevCaptureLoc
616 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000617 for (SmallVectorImpl<LambdaCapture>::const_iterator
618 C = Intro.Captures.begin(),
619 E = Intro.Captures.end();
620 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000621 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000622 if (C->Kind == LCK_This) {
623 // C++11 [expr.prim.lambda]p8:
624 // An identifier or this shall not appear more than once in a
625 // lambda-capture.
626 if (LSI->isCXXThisCaptured()) {
627 Diag(C->Loc, diag::err_capture_more_than_once)
628 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000629 << SourceRange(LSI->getCXXThisCapture().getLocation())
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]p8:
636 // If a lambda-capture includes a capture-default that is =, the
637 // lambda-capture shall not contain this [...].
638 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000639 Diag(C->Loc, diag::err_this_capture_with_copy_default)
640 << FixItHint::CreateRemoval(
641 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000642 continue;
643 }
644
645 // C++11 [expr.prim.lambda]p12:
646 // If this is captured by a local lambda expression, its nearest
647 // enclosing function shall be a non-static member function.
648 QualType ThisCaptureType = getCurrentThisType();
649 if (ThisCaptureType.isNull()) {
650 Diag(C->Loc, diag::err_this_capture) << true;
651 continue;
652 }
653
654 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
655 continue;
656 }
657
Richard Smith0d8e9642013-05-16 06:20:58 +0000658 assert(C->Id && "missing identifier for capture");
659
Richard Smith0a664b82013-05-09 21:36:41 +0000660 if (C->Init.isInvalid())
661 continue;
662 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000663 // C++11 [expr.prim.lambda]p8:
664 // An identifier or this shall not appear more than once in a
665 // lambda-capture.
666 if (!CaptureNames.insert(C->Id))
667 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
668
669 if (C->Init.get()->containsUnexpandedParameterPack())
670 ContainsUnexpandedParameterPack = true;
671
672 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
673 C->Id, C->Init.take());
674 // C++1y [expr.prim.lambda]p11:
675 // Within the lambda-expression's lambda-declarator and
676 // compound-statement, the identifier in the init-capture
677 // hides any declaration of the same name in scopes enclosing
678 // the lambda-expression.
679 if (NewFD)
680 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000681 continue;
682 }
683
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000684 // C++11 [expr.prim.lambda]p8:
685 // If a lambda-capture includes a capture-default that is &, the
686 // identifiers in the lambda-capture shall not be preceded by &.
687 // If a lambda-capture includes a capture-default that is =, [...]
688 // each identifier it contains shall be preceded by &.
689 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000690 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
691 << FixItHint::CreateRemoval(
692 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000693 continue;
694 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000695 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
696 << FixItHint::CreateRemoval(
697 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000698 continue;
699 }
700
Richard Smith0d8e9642013-05-16 06:20:58 +0000701 // C++11 [expr.prim.lambda]p10:
702 // The identifiers in a capture-list are looked up using the usual
703 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000704 DeclarationNameInfo Name(C->Id, C->Loc);
705 LookupResult R(*this, Name, LookupOrdinaryName);
706 LookupName(R, CurScope);
707 if (R.isAmbiguous())
708 continue;
709 if (R.empty()) {
710 // FIXME: Disable corrections that would add qualification?
711 CXXScopeSpec ScopeSpec;
712 DeclFilterCCC<VarDecl> Validator;
713 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
714 continue;
715 }
716
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000717 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000718
719 // C++11 [expr.prim.lambda]p8:
720 // An identifier or this shall not appear more than once in a
721 // lambda-capture.
722 if (!CaptureNames.insert(C->Id)) {
723 if (Var && LSI->isCaptured(Var)) {
724 Diag(C->Loc, diag::err_capture_more_than_once)
725 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
726 << FixItHint::CreateRemoval(
727 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
728 } else
729 // Previous capture was an init-capture: no fixit.
730 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
731 continue;
732 }
733
734 // C++11 [expr.prim.lambda]p10:
735 // [...] each such lookup shall find a variable with automatic storage
736 // duration declared in the reaching scope of the local lambda expression.
737 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000738 if (!Var) {
739 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
740 continue;
741 }
742
Eli Friedman9cd5b242012-09-18 21:11:30 +0000743 // Ignore invalid decls; they'll just confuse the code later.
744 if (Var->isInvalidDecl())
745 continue;
746
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000747 if (!Var->hasLocalStorage()) {
748 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
749 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
750 continue;
751 }
752
Douglas Gregora7365242012-02-14 19:27:52 +0000753 // C++11 [expr.prim.lambda]p23:
754 // A capture followed by an ellipsis is a pack expansion (14.5.3).
755 SourceLocation EllipsisLoc;
756 if (C->EllipsisLoc.isValid()) {
757 if (Var->isParameterPack()) {
758 EllipsisLoc = C->EllipsisLoc;
759 } else {
760 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
761 << SourceRange(C->Loc);
762
763 // Just ignore the ellipsis.
764 }
765 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000766 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000767 }
768
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000769 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
770 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000771 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000772 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000773 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000774
Richard Smith612409e2012-07-25 03:56:55 +0000775 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
776
Douglas Gregorc6889e72012-02-14 22:28:59 +0000777 // Add lambda parameters into scope.
778 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000779
Douglas Gregordfca6f52012-02-13 22:00:16 +0000780 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000781 // cleanups from the enclosing full-expression.
782 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000783}
784
Douglas Gregordfca6f52012-02-13 22:00:16 +0000785void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
786 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000787 // Leave the expression-evaluation context.
788 DiscardCleanupsInEvaluationContext();
789 PopExpressionEvaluationContext();
790
791 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000792 if (!IsInstantiation)
793 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000794
795 // Finalize the lambda.
796 LambdaScopeInfo *LSI = getCurLambda();
797 CXXRecordDecl *Class = LSI->Lambda;
798 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000799 SmallVector<Decl*, 4> Fields;
800 for (RecordDecl::field_iterator i = Class->field_begin(),
801 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000802 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000803 ActOnFields(0, Class->getLocation(), Class, Fields,
804 SourceLocation(), SourceLocation(), 0);
805 CheckCompletedCXXClass(Class);
806
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000807 PopFunctionScopeInfo();
808}
809
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000810/// \brief Add a lambda's conversion to function pointer, as described in
811/// C++11 [expr.prim.lambda]p6.
812static void addFunctionPointerConversion(Sema &S,
813 SourceRange IntroducerRange,
814 CXXRecordDecl *Class,
815 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000816 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000817 const FunctionProtoType *Proto
818 = CallOperator->getType()->getAs<FunctionProtoType>();
819 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000820 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000821 {
822 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000823 CallingConv CC = S.Context.getDefaultCallingConvention(
824 Proto->isVariadic(), /*IsCXXMethod=*/false);
825 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000826 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000827 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
828 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000829 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
830 }
Reid Kleckneref072032013-08-27 23:08:25 +0000831
832 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
833 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000834 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000835 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
836
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000837 SourceLocation Loc = IntroducerRange.getBegin();
838 DeclarationName Name
839 = S.Context.DeclarationNames.getCXXConversionFunctionName(
840 S.Context.getCanonicalType(FunctionPtrTy));
841 DeclarationNameLoc NameLoc;
842 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
843 Loc);
844 CXXConversionDecl *Conversion
845 = CXXConversionDecl::Create(S.Context, Class, Loc,
846 DeclarationNameInfo(Name, Loc, NameLoc),
847 ConvTy,
848 S.Context.getTrivialTypeSourceInfo(ConvTy,
849 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000850 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000851 /*isConstexpr=*/false,
852 CallOperator->getBody()->getLocEnd());
853 Conversion->setAccess(AS_public);
854 Conversion->setImplicit(true);
855 Class->addDecl(Conversion);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000856
857 // Add a non-static member function "__invoke" that will be the result of
858 // the conversion.
859 Name = &S.Context.Idents.get("__invoke");
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000860 CXXMethodDecl *Invoke
861 = CXXMethodDecl::Create(S.Context, Class, Loc,
862 DeclarationNameInfo(Name, Loc), FunctionTy,
863 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000864 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000865 /*IsConstexpr=*/false,
866 CallOperator->getBody()->getLocEnd());
867 SmallVector<ParmVarDecl *, 4> InvokeParams;
868 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
869 ParmVarDecl *From = CallOperator->getParamDecl(I);
870 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
871 From->getLocStart(),
872 From->getLocation(),
873 From->getIdentifier(),
874 From->getType(),
875 From->getTypeSourceInfo(),
876 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000877 /*DefaultArg=*/0));
878 }
879 Invoke->setParams(InvokeParams);
880 Invoke->setAccess(AS_private);
881 Invoke->setImplicit(true);
882 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000883}
884
Douglas Gregorc2956e52012-02-15 22:08:38 +0000885/// \brief Add a lambda's conversion to block pointer.
886static void addBlockPointerConversion(Sema &S,
887 SourceRange IntroducerRange,
888 CXXRecordDecl *Class,
889 CXXMethodDecl *CallOperator) {
890 const FunctionProtoType *Proto
891 = CallOperator->getType()->getAs<FunctionProtoType>();
892 QualType BlockPtrTy;
893 {
894 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
895 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000896 QualType FunctionTy = S.Context.getFunctionType(
897 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000898 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
899 }
Reid Kleckneref072032013-08-27 23:08:25 +0000900
901 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
902 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000903 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000904 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000905
906 SourceLocation Loc = IntroducerRange.getBegin();
907 DeclarationName Name
908 = S.Context.DeclarationNames.getCXXConversionFunctionName(
909 S.Context.getCanonicalType(BlockPtrTy));
910 DeclarationNameLoc NameLoc;
911 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
912 CXXConversionDecl *Conversion
913 = CXXConversionDecl::Create(S.Context, Class, Loc,
914 DeclarationNameInfo(Name, Loc, NameLoc),
915 ConvTy,
916 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000917 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000918 /*isConstexpr=*/false,
919 CallOperator->getBody()->getLocEnd());
920 Conversion->setAccess(AS_public);
921 Conversion->setImplicit(true);
922 Class->addDecl(Conversion);
923}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000924
Douglas Gregordfca6f52012-02-13 22:00:16 +0000925ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000926 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000927 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000928 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000929 SmallVector<LambdaExpr::Capture, 4> Captures;
930 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000931 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +0000932 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000933 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000934 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000935 SourceRange IntroducerRange;
936 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000937 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000938 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000939 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000940 SmallVector<VarDecl *, 4> ArrayIndexVars;
941 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000942 {
943 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000944 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000945 Class = LSI->Lambda;
946 IntroducerRange = LSI->IntroducerRange;
947 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000948 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000949 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000950 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000951 ArrayIndexVars.swap(LSI->ArrayIndexVars);
952 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
953
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000954 // Translate captures.
955 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
956 LambdaScopeInfo::Capture From = LSI->Captures[I];
957 assert(!From.isBlockCapture() && "Cannot capture __block variables");
958 bool IsImplicit = I >= LSI->NumExplicitCaptures;
959
960 // Handle 'this' capture.
961 if (From.isThisCapture()) {
962 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
963 IsImplicit,
964 LCK_This));
965 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
966 getCurrentThisType(),
967 /*isImplicit=*/true));
968 continue;
969 }
970
Richard Smith0d8e9642013-05-16 06:20:58 +0000971 if (From.isInitCapture()) {
972 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
973 CaptureInits.push_back(From.getInitExpr());
974 continue;
975 }
976
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000977 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000978 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
979 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000980 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000981 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000982 }
983
984 switch (LSI->ImpCaptureStyle) {
985 case CapturingScopeInfo::ImpCap_None:
986 CaptureDefault = LCD_None;
987 break;
988
989 case CapturingScopeInfo::ImpCap_LambdaByval:
990 CaptureDefault = LCD_ByCopy;
991 break;
992
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000993 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000994 case CapturingScopeInfo::ImpCap_LambdaByref:
995 CaptureDefault = LCD_ByRef;
996 break;
997
998 case CapturingScopeInfo::ImpCap_Block:
999 llvm_unreachable("block capture in lambda");
1000 break;
1001 }
James Dennettf68af642013-08-09 23:08:25 +00001002 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001003
Douglas Gregor54042f12012-02-09 10:18:50 +00001004 // C++11 [expr.prim.lambda]p4:
1005 // If a lambda-expression does not include a
1006 // trailing-return-type, it is as if the trailing-return-type
1007 // denotes the following type:
1008 // FIXME: Assumes current resolution to core issue 975.
Manuel Klimek152b4e42013-08-22 12:12:24 +00001009 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001010 deduceClosureReturnType(*LSI);
1011
Douglas Gregor54042f12012-02-09 10:18:50 +00001012 // - if there are no return statements in the
1013 // compound-statement, or all return statements return
1014 // either an expression of type void or no expression or
1015 // braced-init-list, the type void;
1016 if (LSI->ReturnType.isNull()) {
1017 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001018 }
1019
1020 // Create a function type with the inferred return type.
1021 const FunctionProtoType *Proto
1022 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001023 QualType FunctionTy = Context.getFunctionType(
1024 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001025 CallOperator->setType(FunctionTy);
1026 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001027
Douglas Gregor215e4e12012-02-12 17:34:23 +00001028 // C++ [expr.prim.lambda]p7:
1029 // The lambda-expression's compound-statement yields the
1030 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001031 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001032 CallOperator->setLexicalDeclContext(Class);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001033 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001034 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001035
Douglas Gregorb5559712012-02-10 16:13:20 +00001036 // C++11 [expr.prim.lambda]p6:
1037 // The closure type for a lambda-expression with no lambda-capture
1038 // has a public non-virtual non-explicit const conversion function
1039 // to pointer to function having the same parameter and return
1040 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001041 if (Captures.empty() && CaptureDefault == LCD_None)
1042 addFunctionPointerConversion(*this, IntroducerRange, Class,
1043 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001044
Douglas Gregorc2956e52012-02-15 22:08:38 +00001045 // Objective-C++:
1046 // The closure type for a lambda-expression has a public non-virtual
1047 // non-explicit const conversion function to a block pointer having the
1048 // same parameter and return types as the closure type's function call
1049 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001050 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001051 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1052
Douglas Gregorb5559712012-02-10 16:13:20 +00001053 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001054 SmallVector<Decl*, 4> Fields;
1055 for (RecordDecl::field_iterator i = Class->field_begin(),
1056 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001057 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001058 ActOnFields(0, Class->getLocation(), Class, Fields,
1059 SourceLocation(), SourceLocation(), 0);
1060 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001061 }
1062
Douglas Gregor503384f2012-02-09 00:47:04 +00001063 if (LambdaExprNeedsCleanups)
1064 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001065
Douglas Gregore2c59132012-02-09 08:14:43 +00001066 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001067 CaptureDefault, CaptureDefaultLoc,
1068 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001069 ExplicitParams, ExplicitResultType,
1070 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001071 ArrayIndexStarts, Body->getLocEnd(),
1072 ContainsUnexpandedParameterPack);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001073
Douglas Gregore2c59132012-02-09 08:14:43 +00001074 // C++11 [expr.prim.lambda]p2:
1075 // A lambda-expression shall not appear in an unevaluated operand
1076 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001077 if (!CurContext->isDependentContext()) {
1078 switch (ExprEvalContexts.back().Context) {
1079 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001080 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001081 // We don't actually diagnose this case immediately, because we
1082 // could be within a context where we might find out later that
1083 // the expression is potentially evaluated (e.g., for typeid).
1084 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1085 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001086
Douglas Gregord5387e82012-02-14 00:00:48 +00001087 case ConstantEvaluated:
1088 case PotentiallyEvaluated:
1089 case PotentiallyEvaluatedIfUsed:
1090 break;
1091 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001092 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001093
Douglas Gregor503384f2012-02-09 00:47:04 +00001094 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001095}
Eli Friedman23f02672012-03-01 04:01:32 +00001096
1097ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1098 SourceLocation ConvLocation,
1099 CXXConversionDecl *Conv,
1100 Expr *Src) {
1101 // Make sure that the lambda call operator is marked used.
1102 CXXRecordDecl *Lambda = Conv->getParent();
1103 CXXMethodDecl *CallOperator
1104 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001105 Lambda->lookup(
1106 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001107 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001108 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001109
1110 ExprResult Init = PerformCopyInitialization(
1111 InitializedEntity::InitializeBlock(ConvLocation,
1112 Src->getType(),
1113 /*NRVO=*/false),
1114 CurrentLocation, Src);
1115 if (!Init.isInvalid())
1116 Init = ActOnFinishFullExpr(Init.take());
1117
1118 if (Init.isInvalid())
1119 return ExprError();
1120
1121 // Create the new block to be returned.
1122 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1123
1124 // Set the type information.
1125 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1126 Block->setIsVariadic(CallOperator->isVariadic());
1127 Block->setBlockMissingReturnType(false);
1128
1129 // Add parameters.
1130 SmallVector<ParmVarDecl *, 4> BlockParams;
1131 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1132 ParmVarDecl *From = CallOperator->getParamDecl(I);
1133 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1134 From->getLocStart(),
1135 From->getLocation(),
1136 From->getIdentifier(),
1137 From->getType(),
1138 From->getTypeSourceInfo(),
1139 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001140 /*DefaultArg=*/0));
1141 }
1142 Block->setParams(BlockParams);
1143
1144 Block->setIsConversionFromLambda(true);
1145
1146 // Add capture. The capture uses a fake variable, which doesn't correspond
1147 // to any actual memory location. However, the initializer copy-initializes
1148 // the lambda object.
1149 TypeSourceInfo *CapVarTSI =
1150 Context.getTrivialTypeSourceInfo(Src->getType());
1151 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1152 ConvLocation, 0,
1153 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001154 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001155 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1156 /*Nested=*/false, /*Copy=*/Init.take());
1157 Block->setCaptures(Context, &Capture, &Capture + 1,
1158 /*CapturesCXXThis=*/false);
1159
1160 // Add a fake function body to the block. IR generation is responsible
1161 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001162 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001163
1164 // Create the block literal expression.
1165 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1166 ExprCleanupObjects.push_back(Block);
1167 ExprNeedsCleanups = true;
1168
1169 return BuildBlock;
1170}