blob: 1e6ef9baf70e07cab58eef7d4ea27aae874f2d80 [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 *
56Sema::getCurrentMangleNumberContext(DeclContext *DC,
57 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
180LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
181 SourceRange IntroducerRange,
182 LambdaCaptureDefault CaptureDefault,
183 bool ExplicitParams,
184 bool ExplicitResultType,
185 bool Mutable) {
186 PushLambdaScope(CallOperator->getParent(), CallOperator);
187 LambdaScopeInfo *LSI = getCurLambda();
188 if (CaptureDefault == LCD_ByCopy)
189 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
190 else if (CaptureDefault == LCD_ByRef)
191 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
192 LSI->IntroducerRange = IntroducerRange;
193 LSI->ExplicitParams = ExplicitParams;
194 LSI->Mutable = Mutable;
195
196 if (ExplicitResultType) {
197 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000198
199 if (!LSI->ReturnType->isDependentType() &&
200 !LSI->ReturnType->isVoidType()) {
201 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
202 diag::err_lambda_incomplete_result)) {
203 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000204 }
205 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000206 } else {
207 LSI->HasImplicitReturnType = true;
208 }
209
210 return LSI;
211}
212
213void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
214 LSI->finishedExplicitCaptures();
215}
216
Douglas Gregorc6889e72012-02-14 22:28:59 +0000217void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000218 // Introduce our parameters into the function scope
219 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
220 p < NumParams; ++p) {
221 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000222
223 // If this has an identifier, add it to the scope stack.
224 if (CurScope && Param->getIdentifier()) {
225 CheckShadow(CurScope, Param);
226
227 PushOnScopeChains(Param, CurScope);
228 }
229 }
230}
231
John McCall41d01642013-03-09 00:54:31 +0000232/// If this expression is an enumerator-like expression of some type
233/// T, return the type T; otherwise, return null.
234///
235/// Pointer comparisons on the result here should always work because
236/// it's derived from either the parent of an EnumConstantDecl
237/// (i.e. the definition) or the declaration returned by
238/// EnumType::getDecl() (i.e. the definition).
239static EnumDecl *findEnumForBlockReturn(Expr *E) {
240 // An expression is an enumerator-like expression of type T if,
241 // ignoring parens and parens-like expressions:
242 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000243
John McCall41d01642013-03-09 00:54:31 +0000244 // - it is an enumerator whose enum type is T or
245 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
246 if (EnumConstantDecl *D
247 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
248 return cast<EnumDecl>(D->getDeclContext());
249 }
250 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000251 }
252
John McCall41d01642013-03-09 00:54:31 +0000253 // - it is a comma expression whose RHS is an enumerator-like
254 // expression of type T or
255 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
256 if (BO->getOpcode() == BO_Comma)
257 return findEnumForBlockReturn(BO->getRHS());
258 return 0;
259 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000260
John McCall41d01642013-03-09 00:54:31 +0000261 // - it is a statement-expression whose value expression is an
262 // enumerator-like expression of type T or
263 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
264 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
265 return findEnumForBlockReturn(last);
266 return 0;
267 }
268
269 // - it is a ternary conditional operator (not the GNU ?:
270 // extension) whose second and third operands are
271 // enumerator-like expressions of type T or
272 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
273 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
274 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
275 return ED;
276 return 0;
277 }
278
279 // (implicitly:)
280 // - it is an implicit integral conversion applied to an
281 // enumerator-like expression of type T or
282 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000283 // We can sometimes see integral conversions in valid
284 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000285 if (ICE->getCastKind() == CK_IntegralCast)
286 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000287
288 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000289 }
290
291 // - it is an expression of that formal enum type.
292 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
293 return ET->getDecl();
294 }
295
296 // Otherwise, nope.
297 return 0;
298}
299
300/// Attempt to find a type T for which the returned expression of the
301/// given statement is an enumerator-like expression of that type.
302static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
303 if (Expr *retValue = ret->getRetValue())
304 return findEnumForBlockReturn(retValue);
305 return 0;
306}
307
308/// Attempt to find a common type T for which all of the returned
309/// expressions in a block are enumerator-like expressions of that
310/// type.
311static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
312 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
313
314 // Try to find one for the first return.
315 EnumDecl *ED = findEnumForBlockReturn(*i);
316 if (!ED) return 0;
317
318 // Check that the rest of the returns have the same enum.
319 for (++i; i != e; ++i) {
320 if (findEnumForBlockReturn(*i) != ED)
321 return 0;
322 }
323
324 // Never infer an anonymous enum type.
325 if (!ED->hasNameForLinkage()) return 0;
326
327 return ED;
328}
329
330/// Adjust the given return statements so that they formally return
331/// the given type. It should require, at most, an IntegralCast.
332static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
333 QualType returnType) {
334 for (ArrayRef<ReturnStmt*>::iterator
335 i = returns.begin(), e = returns.end(); i != e; ++i) {
336 ReturnStmt *ret = *i;
337 Expr *retValue = ret->getRetValue();
338 if (S.Context.hasSameType(retValue->getType(), returnType))
339 continue;
340
341 // Right now we only support integral fixup casts.
342 assert(returnType->isIntegralOrUnscopedEnumerationType());
343 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
344
345 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
346
347 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
348 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
349 E, /*base path*/ 0, VK_RValue);
350 if (cleanups) {
351 cleanups->setSubExpr(E);
352 } else {
353 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000354 }
355 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000356}
357
358void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
359 assert(CSI.HasImplicitReturnType);
360
John McCall41d01642013-03-09 00:54:31 +0000361 // C++ Core Issue #975, proposed resolution:
362 // If a lambda-expression does not include a trailing-return-type,
363 // it is as if the trailing-return-type denotes the following type:
364 // - if there are no return statements in the compound-statement,
365 // or all return statements return either an expression of type
366 // void or no expression or braced-init-list, the type void;
367 // - otherwise, if all return statements return an expression
368 // and the types of the returned expressions after
369 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
370 // array-to-pointer conversion (4.2 [conv.array]), and
371 // function-to-pointer conversion (4.3 [conv.func]) are the
372 // same, that common type;
373 // - otherwise, the program is ill-formed.
374 //
375 // In addition, in blocks in non-C++ modes, if all of the return
376 // statements are enumerator-like expressions of some type T, where
377 // T has a name for linkage, then we infer the return type of the
378 // block to be that type.
379
Jordan Rose7dd900e2012-07-02 21:19:23 +0000380 // First case: no return statements, implicit void return type.
381 ASTContext &Ctx = getASTContext();
382 if (CSI.Returns.empty()) {
383 // It's possible there were simply no /valid/ return statements.
384 // In this case, the first one we found may have at least given us a type.
385 if (CSI.ReturnType.isNull())
386 CSI.ReturnType = Ctx.VoidTy;
387 return;
388 }
389
390 // Second case: at least one return statement has dependent type.
391 // Delay type checking until instantiation.
392 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
393 if (CSI.ReturnType->isDependentType())
394 return;
395
John McCall41d01642013-03-09 00:54:31 +0000396 // Try to apply the enum-fuzz rule.
397 if (!getLangOpts().CPlusPlus) {
398 assert(isa<BlockScopeInfo>(CSI));
399 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
400 if (ED) {
401 CSI.ReturnType = Context.getTypeDeclType(ED);
402 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
403 return;
404 }
405 }
406
Jordan Rose7dd900e2012-07-02 21:19:23 +0000407 // Third case: only one return statement. Don't bother doing extra work!
408 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
409 E = CSI.Returns.end();
410 if (I+1 == E)
411 return;
412
413 // General case: many return statements.
414 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000415
416 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000417 // Note that we've already done the required promotions as part of
418 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000419 for (; I != E; ++I) {
420 const ReturnStmt *RS = *I;
421 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000422
John McCall41d01642013-03-09 00:54:31 +0000423 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
424 if (Context.hasSameType(ReturnType, CSI.ReturnType))
425 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000426
John McCall41d01642013-03-09 00:54:31 +0000427 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
428 // TODO: It's possible that the *first* return is the divergent one.
429 Diag(RS->getLocStart(),
430 diag::err_typecheck_missing_return_type_incompatible)
431 << ReturnType << CSI.ReturnType
432 << isa<LambdaScopeInfo>(CSI);
433 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000434 }
435}
436
Richard Smith0d8e9642013-05-16 06:20:58 +0000437FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
438 IdentifierInfo *Id, Expr *InitExpr) {
439 LambdaScopeInfo *LSI = getCurLambda();
440
441 // C++1y [expr.prim.lambda]p11:
442 // The type of [the] member corresponds to the type of a hypothetical
443 // variable declaration of the form "auto init-capture;"
444 QualType DeductType = Context.getAutoDeductType();
445 TypeLocBuilder TLB;
446 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
447 if (ByRef) {
448 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
449 assert(!DeductType.isNull() && "can't build reference to auto");
450 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
451 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000452 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000453
454 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
455 Expr *Init = InitExpr;
456 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
457 if (Parens->getNumExprs() == 1) {
458 Init = Parens->getExpr(0);
459 InitKind = InitializationKind::CreateDirect(
460 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
461 } else {
462 // C++1y [dcl.spec.auto]p3:
463 // In an initializer of the form ( expression-list ), the
464 // expression-list shall be a single assignment-expression.
465 if (Parens->getNumExprs() == 0)
466 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
467 << Id;
468 else if (Parens->getNumExprs() > 1)
469 Diag(Parens->getExpr(1)->getLocStart(),
470 diag::err_init_capture_multiple_expressions)
471 << Id;
472 return 0;
473 }
474 } else if (isa<InitListExpr>(Init))
475 // We do not need to distinguish between direct-list-initialization
476 // and copy-list-initialization here, because we will always deduce
477 // std::initializer_list<T>, and direct- and copy-list-initialization
478 // always behave the same for such a type.
479 // FIXME: We should model whether an '=' was present.
480 InitKind = InitializationKind::CreateDirectList(Loc);
481 else
482 InitKind = InitializationKind::CreateCopy(Loc, Loc);
483 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000484 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000485 if (isa<InitListExpr>(Init))
486 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
487 << Id << Init->getSourceRange();
488 else
489 Diag(Loc, diag::err_init_capture_deduction_failure)
490 << Id << Init->getType() << Init->getSourceRange();
491 }
492 if (DeducedType.isNull())
493 return 0;
494
495 // [...] a non-static data member named by the identifier is declared in
496 // the closure type. This member is not a bit-field and not mutable.
497 // Core issue: the member is (probably...) public.
498 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000499 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000500 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
501 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
502 LSI->Lambda->addDecl(NewFD);
503
504 if (CurContext->isDependentContext()) {
505 LSI->addInitCapture(NewFD, InitExpr);
506 } else {
507 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
508 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
509 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
510 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
511 if (!InitResult.isInvalid())
512 LSI->addInitCapture(NewFD, InitResult.take());
513 }
514 }
515
516 return NewFD;
517}
518
Douglas Gregordfca6f52012-02-13 22:00:16 +0000519void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
520 Declarator &ParamInfo,
521 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000522 // Determine if we're within a context where we know that the lambda will
523 // be dependent, because there are template parameters in scope.
524 bool KnownDependent = false;
525 if (Scope *TmplScope = CurScope->getTemplateParamParent())
526 if (!TmplScope->decl_empty())
527 KnownDependent = true;
528
Douglas Gregordfca6f52012-02-13 22:00:16 +0000529 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000530 TypeSourceInfo *MethodTyInfo;
531 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000532 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000533 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000534 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000535 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000536 if (ParamInfo.getNumTypeObjects() == 0) {
537 // C++11 [expr.prim.lambda]p4:
538 // If a lambda-expression does not include a lambda-declarator, it is as
539 // if the lambda-declarator were ().
540 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000541 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000542 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000543 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000544 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000545 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
546 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000547 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000548 EndLoc = Intro.Range.getEnd();
549 } else {
550 assert(ParamInfo.isFunctionDeclarator() &&
551 "lambda-declarator is a function");
552 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
553
554 // C++11 [expr.prim.lambda]p5:
555 // This function call operator is declared const (9.3.1) if and only if
556 // the lambda-expression's parameter-declaration-clause is not followed
557 // by mutable. It is neither virtual nor declared volatile. [...]
558 if (!FTI.hasMutableQualifier())
559 FTI.TypeQuals |= DeclSpec::TQ_const;
560
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000561 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000562 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000563 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000564
565 ExplicitResultType
566 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
567 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000568
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000569 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
570 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
571 // Empty arg list, don't push any params.
572 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
573 } else {
574 Params.reserve(FTI.NumArgs);
575 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
576 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
577 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000578
579 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000580 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
581 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000583
584 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
585 KnownDependent);
586
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000587 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000588 MethodTyInfo, EndLoc, Params);
589
590 if (ExplicitParams)
591 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000592
Bill Wendlingad017fa2012-12-20 19:22:21 +0000593 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000594 ProcessDeclAttributes(CurScope, Method, ParamInfo);
595
Douglas Gregor503384f2012-02-09 00:47:04 +0000596 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000597 PushDeclContext(CurScope, Method);
598
599 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000600 LambdaScopeInfo *LSI
601 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
602 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000603 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000604
605 // Distinct capture names, for diagnostics.
606 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
607
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000608 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000609 SourceLocation PrevCaptureLoc
610 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000611 for (SmallVectorImpl<LambdaCapture>::const_iterator
612 C = Intro.Captures.begin(),
613 E = Intro.Captures.end();
614 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000615 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000616 if (C->Kind == LCK_This) {
617 // C++11 [expr.prim.lambda]p8:
618 // An identifier or this shall not appear more than once in a
619 // lambda-capture.
620 if (LSI->isCXXThisCaptured()) {
621 Diag(C->Loc, diag::err_capture_more_than_once)
622 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000623 << SourceRange(LSI->getCXXThisCapture().getLocation())
624 << FixItHint::CreateRemoval(
625 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000626 continue;
627 }
628
629 // C++11 [expr.prim.lambda]p8:
630 // If a lambda-capture includes a capture-default that is =, the
631 // lambda-capture shall not contain this [...].
632 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000633 Diag(C->Loc, diag::err_this_capture_with_copy_default)
634 << FixItHint::CreateRemoval(
635 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000636 continue;
637 }
638
639 // C++11 [expr.prim.lambda]p12:
640 // If this is captured by a local lambda expression, its nearest
641 // enclosing function shall be a non-static member function.
642 QualType ThisCaptureType = getCurrentThisType();
643 if (ThisCaptureType.isNull()) {
644 Diag(C->Loc, diag::err_this_capture) << true;
645 continue;
646 }
647
648 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
649 continue;
650 }
651
Richard Smith0d8e9642013-05-16 06:20:58 +0000652 assert(C->Id && "missing identifier for capture");
653
Richard Smith0a664b82013-05-09 21:36:41 +0000654 if (C->Init.isInvalid())
655 continue;
656 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000657 // C++11 [expr.prim.lambda]p8:
658 // An identifier or this shall not appear more than once in a
659 // lambda-capture.
660 if (!CaptureNames.insert(C->Id))
661 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
662
663 if (C->Init.get()->containsUnexpandedParameterPack())
664 ContainsUnexpandedParameterPack = true;
665
666 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
667 C->Id, C->Init.take());
668 // C++1y [expr.prim.lambda]p11:
669 // Within the lambda-expression's lambda-declarator and
670 // compound-statement, the identifier in the init-capture
671 // hides any declaration of the same name in scopes enclosing
672 // the lambda-expression.
673 if (NewFD)
674 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000675 continue;
676 }
677
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000678 // C++11 [expr.prim.lambda]p8:
679 // If a lambda-capture includes a capture-default that is &, the
680 // identifiers in the lambda-capture shall not be preceded by &.
681 // If a lambda-capture includes a capture-default that is =, [...]
682 // each identifier it contains shall be preceded by &.
683 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000684 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
685 << FixItHint::CreateRemoval(
686 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000687 continue;
688 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000689 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
690 << FixItHint::CreateRemoval(
691 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000692 continue;
693 }
694
Richard Smith0d8e9642013-05-16 06:20:58 +0000695 // C++11 [expr.prim.lambda]p10:
696 // The identifiers in a capture-list are looked up using the usual
697 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000698 DeclarationNameInfo Name(C->Id, C->Loc);
699 LookupResult R(*this, Name, LookupOrdinaryName);
700 LookupName(R, CurScope);
701 if (R.isAmbiguous())
702 continue;
703 if (R.empty()) {
704 // FIXME: Disable corrections that would add qualification?
705 CXXScopeSpec ScopeSpec;
706 DeclFilterCCC<VarDecl> Validator;
707 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
708 continue;
709 }
710
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000711 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000712
713 // C++11 [expr.prim.lambda]p8:
714 // An identifier or this shall not appear more than once in a
715 // lambda-capture.
716 if (!CaptureNames.insert(C->Id)) {
717 if (Var && LSI->isCaptured(Var)) {
718 Diag(C->Loc, diag::err_capture_more_than_once)
719 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
720 << FixItHint::CreateRemoval(
721 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
722 } else
723 // Previous capture was an init-capture: no fixit.
724 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
725 continue;
726 }
727
728 // C++11 [expr.prim.lambda]p10:
729 // [...] each such lookup shall find a variable with automatic storage
730 // duration declared in the reaching scope of the local lambda expression.
731 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000732 if (!Var) {
733 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
734 continue;
735 }
736
Eli Friedman9cd5b242012-09-18 21:11:30 +0000737 // Ignore invalid decls; they'll just confuse the code later.
738 if (Var->isInvalidDecl())
739 continue;
740
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000741 if (!Var->hasLocalStorage()) {
742 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
743 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
744 continue;
745 }
746
Douglas Gregora7365242012-02-14 19:27:52 +0000747 // C++11 [expr.prim.lambda]p23:
748 // A capture followed by an ellipsis is a pack expansion (14.5.3).
749 SourceLocation EllipsisLoc;
750 if (C->EllipsisLoc.isValid()) {
751 if (Var->isParameterPack()) {
752 EllipsisLoc = C->EllipsisLoc;
753 } else {
754 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
755 << SourceRange(C->Loc);
756
757 // Just ignore the ellipsis.
758 }
759 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000760 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000761 }
762
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000763 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
764 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000765 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000766 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000767 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000768
Richard Smith612409e2012-07-25 03:56:55 +0000769 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
770
Douglas Gregorc6889e72012-02-14 22:28:59 +0000771 // Add lambda parameters into scope.
772 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000773
Douglas Gregordfca6f52012-02-13 22:00:16 +0000774 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000775 // cleanups from the enclosing full-expression.
776 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000777}
778
Douglas Gregordfca6f52012-02-13 22:00:16 +0000779void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
780 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000781 // Leave the expression-evaluation context.
782 DiscardCleanupsInEvaluationContext();
783 PopExpressionEvaluationContext();
784
785 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000786 if (!IsInstantiation)
787 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000788
789 // Finalize the lambda.
790 LambdaScopeInfo *LSI = getCurLambda();
791 CXXRecordDecl *Class = LSI->Lambda;
792 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000793 SmallVector<Decl*, 4> Fields;
794 for (RecordDecl::field_iterator i = Class->field_begin(),
795 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000796 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000797 ActOnFields(0, Class->getLocation(), Class, Fields,
798 SourceLocation(), SourceLocation(), 0);
799 CheckCompletedCXXClass(Class);
800
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000801 PopFunctionScopeInfo();
802}
803
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000804/// \brief Add a lambda's conversion to function pointer, as described in
805/// C++11 [expr.prim.lambda]p6.
806static void addFunctionPointerConversion(Sema &S,
807 SourceRange IntroducerRange,
808 CXXRecordDecl *Class,
809 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000810 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000811 const FunctionProtoType *Proto
812 = CallOperator->getType()->getAs<FunctionProtoType>();
813 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000814 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000815 {
816 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
817 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000818 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
819 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000820 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
821 }
822
823 FunctionProtoType::ExtProtoInfo ExtInfo;
824 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000825 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000826 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000827
828 SourceLocation Loc = IntroducerRange.getBegin();
829 DeclarationName Name
830 = S.Context.DeclarationNames.getCXXConversionFunctionName(
831 S.Context.getCanonicalType(FunctionPtrTy));
832 DeclarationNameLoc NameLoc;
833 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
834 Loc);
835 CXXConversionDecl *Conversion
836 = CXXConversionDecl::Create(S.Context, Class, Loc,
837 DeclarationNameInfo(Name, Loc, NameLoc),
838 ConvTy,
839 S.Context.getTrivialTypeSourceInfo(ConvTy,
840 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000841 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000842 /*isConstexpr=*/false,
843 CallOperator->getBody()->getLocEnd());
844 Conversion->setAccess(AS_public);
845 Conversion->setImplicit(true);
846 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000847
848 // Add a non-static member function "__invoke" that will be the result of
849 // the conversion.
850 Name = &S.Context.Idents.get("__invoke");
851 CXXMethodDecl *Invoke
852 = CXXMethodDecl::Create(S.Context, Class, Loc,
853 DeclarationNameInfo(Name, Loc), FunctionTy,
854 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000855 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000856 /*IsConstexpr=*/false,
857 CallOperator->getBody()->getLocEnd());
858 SmallVector<ParmVarDecl *, 4> InvokeParams;
859 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
860 ParmVarDecl *From = CallOperator->getParamDecl(I);
861 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
862 From->getLocStart(),
863 From->getLocation(),
864 From->getIdentifier(),
865 From->getType(),
866 From->getTypeSourceInfo(),
867 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000868 /*DefaultArg=*/0));
869 }
870 Invoke->setParams(InvokeParams);
871 Invoke->setAccess(AS_private);
872 Invoke->setImplicit(true);
873 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000874}
875
Douglas Gregorc2956e52012-02-15 22:08:38 +0000876/// \brief Add a lambda's conversion to block pointer.
877static void addBlockPointerConversion(Sema &S,
878 SourceRange IntroducerRange,
879 CXXRecordDecl *Class,
880 CXXMethodDecl *CallOperator) {
881 const FunctionProtoType *Proto
882 = CallOperator->getType()->getAs<FunctionProtoType>();
883 QualType BlockPtrTy;
884 {
885 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
886 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000887 QualType FunctionTy = S.Context.getFunctionType(
888 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000889 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
890 }
891
892 FunctionProtoType::ExtProtoInfo ExtInfo;
893 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000894 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000895
896 SourceLocation Loc = IntroducerRange.getBegin();
897 DeclarationName Name
898 = S.Context.DeclarationNames.getCXXConversionFunctionName(
899 S.Context.getCanonicalType(BlockPtrTy));
900 DeclarationNameLoc NameLoc;
901 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
902 CXXConversionDecl *Conversion
903 = CXXConversionDecl::Create(S.Context, Class, Loc,
904 DeclarationNameInfo(Name, Loc, NameLoc),
905 ConvTy,
906 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000907 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000908 /*isConstexpr=*/false,
909 CallOperator->getBody()->getLocEnd());
910 Conversion->setAccess(AS_public);
911 Conversion->setImplicit(true);
912 Class->addDecl(Conversion);
913}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000914
Douglas Gregordfca6f52012-02-13 22:00:16 +0000915ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000916 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000917 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000918 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000919 SmallVector<LambdaExpr::Capture, 4> Captures;
920 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000921 LambdaCaptureDefault CaptureDefault;
922 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000923 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000924 SourceRange IntroducerRange;
925 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000926 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000927 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000928 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000929 SmallVector<VarDecl *, 4> ArrayIndexVars;
930 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000931 {
932 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000933 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000934 Class = LSI->Lambda;
935 IntroducerRange = LSI->IntroducerRange;
936 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000937 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000938 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000939 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000940 ArrayIndexVars.swap(LSI->ArrayIndexVars);
941 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
942
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000943 // Translate captures.
944 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
945 LambdaScopeInfo::Capture From = LSI->Captures[I];
946 assert(!From.isBlockCapture() && "Cannot capture __block variables");
947 bool IsImplicit = I >= LSI->NumExplicitCaptures;
948
949 // Handle 'this' capture.
950 if (From.isThisCapture()) {
951 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
952 IsImplicit,
953 LCK_This));
954 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
955 getCurrentThisType(),
956 /*isImplicit=*/true));
957 continue;
958 }
959
Richard Smith0d8e9642013-05-16 06:20:58 +0000960 if (From.isInitCapture()) {
961 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
962 CaptureInits.push_back(From.getInitExpr());
963 continue;
964 }
965
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000966 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000967 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
968 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000969 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000970 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000971 }
972
973 switch (LSI->ImpCaptureStyle) {
974 case CapturingScopeInfo::ImpCap_None:
975 CaptureDefault = LCD_None;
976 break;
977
978 case CapturingScopeInfo::ImpCap_LambdaByval:
979 CaptureDefault = LCD_ByCopy;
980 break;
981
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000982 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000983 case CapturingScopeInfo::ImpCap_LambdaByref:
984 CaptureDefault = LCD_ByRef;
985 break;
986
987 case CapturingScopeInfo::ImpCap_Block:
988 llvm_unreachable("block capture in lambda");
989 break;
990 }
991
Douglas Gregor54042f12012-02-09 10:18:50 +0000992 // C++11 [expr.prim.lambda]p4:
993 // If a lambda-expression does not include a
994 // trailing-return-type, it is as if the trailing-return-type
995 // denotes the following type:
996 // FIXME: Assumes current resolution to core issue 975.
997 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000998 deduceClosureReturnType(*LSI);
999
Douglas Gregor54042f12012-02-09 10:18:50 +00001000 // - if there are no return statements in the
1001 // compound-statement, or all return statements return
1002 // either an expression of type void or no expression or
1003 // braced-init-list, the type void;
1004 if (LSI->ReturnType.isNull()) {
1005 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001006 }
1007
1008 // Create a function type with the inferred return type.
1009 const FunctionProtoType *Proto
1010 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001011 QualType FunctionTy = Context.getFunctionType(
1012 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001013 CallOperator->setType(FunctionTy);
1014 }
1015
Douglas Gregor215e4e12012-02-12 17:34:23 +00001016 // C++ [expr.prim.lambda]p7:
1017 // The lambda-expression's compound-statement yields the
1018 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001019 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001020 CallOperator->setLexicalDeclContext(Class);
1021 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001022 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001023
Douglas Gregorb5559712012-02-10 16:13:20 +00001024 // C++11 [expr.prim.lambda]p6:
1025 // The closure type for a lambda-expression with no lambda-capture
1026 // has a public non-virtual non-explicit const conversion function
1027 // to pointer to function having the same parameter and return
1028 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001029 if (Captures.empty() && CaptureDefault == LCD_None)
1030 addFunctionPointerConversion(*this, IntroducerRange, Class,
1031 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001032
Douglas Gregorc2956e52012-02-15 22:08:38 +00001033 // Objective-C++:
1034 // The closure type for a lambda-expression has a public non-virtual
1035 // non-explicit const conversion function to a block pointer having the
1036 // same parameter and return types as the closure type's function call
1037 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001038 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001039 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1040
Douglas Gregorb5559712012-02-10 16:13:20 +00001041 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001042 SmallVector<Decl*, 4> Fields;
1043 for (RecordDecl::field_iterator i = Class->field_begin(),
1044 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001045 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001046 ActOnFields(0, Class->getLocation(), Class, Fields,
1047 SourceLocation(), SourceLocation(), 0);
1048 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001049 }
1050
Douglas Gregor503384f2012-02-09 00:47:04 +00001051 if (LambdaExprNeedsCleanups)
1052 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001053
Douglas Gregore2c59132012-02-09 08:14:43 +00001054 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1055 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001056 ExplicitParams, ExplicitResultType,
1057 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001058 ArrayIndexStarts, Body->getLocEnd(),
1059 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +00001060
1061 // C++11 [expr.prim.lambda]p2:
1062 // A lambda-expression shall not appear in an unevaluated operand
1063 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001064 if (!CurContext->isDependentContext()) {
1065 switch (ExprEvalContexts.back().Context) {
1066 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001067 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001068 // We don't actually diagnose this case immediately, because we
1069 // could be within a context where we might find out later that
1070 // the expression is potentially evaluated (e.g., for typeid).
1071 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1072 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001073
Douglas Gregord5387e82012-02-14 00:00:48 +00001074 case ConstantEvaluated:
1075 case PotentiallyEvaluated:
1076 case PotentiallyEvaluatedIfUsed:
1077 break;
1078 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001079 }
Douglas Gregord5387e82012-02-14 00:00:48 +00001080
Douglas Gregor503384f2012-02-09 00:47:04 +00001081 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001082}
Eli Friedman23f02672012-03-01 04:01:32 +00001083
1084ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1085 SourceLocation ConvLocation,
1086 CXXConversionDecl *Conv,
1087 Expr *Src) {
1088 // Make sure that the lambda call operator is marked used.
1089 CXXRecordDecl *Lambda = Conv->getParent();
1090 CXXMethodDecl *CallOperator
1091 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001092 Lambda->lookup(
1093 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001094 CallOperator->setReferenced();
1095 CallOperator->setUsed();
1096
1097 ExprResult Init = PerformCopyInitialization(
1098 InitializedEntity::InitializeBlock(ConvLocation,
1099 Src->getType(),
1100 /*NRVO=*/false),
1101 CurrentLocation, Src);
1102 if (!Init.isInvalid())
1103 Init = ActOnFinishFullExpr(Init.take());
1104
1105 if (Init.isInvalid())
1106 return ExprError();
1107
1108 // Create the new block to be returned.
1109 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1110
1111 // Set the type information.
1112 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1113 Block->setIsVariadic(CallOperator->isVariadic());
1114 Block->setBlockMissingReturnType(false);
1115
1116 // Add parameters.
1117 SmallVector<ParmVarDecl *, 4> BlockParams;
1118 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1119 ParmVarDecl *From = CallOperator->getParamDecl(I);
1120 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1121 From->getLocStart(),
1122 From->getLocation(),
1123 From->getIdentifier(),
1124 From->getType(),
1125 From->getTypeSourceInfo(),
1126 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001127 /*DefaultArg=*/0));
1128 }
1129 Block->setParams(BlockParams);
1130
1131 Block->setIsConversionFromLambda(true);
1132
1133 // Add capture. The capture uses a fake variable, which doesn't correspond
1134 // to any actual memory location. However, the initializer copy-initializes
1135 // the lambda object.
1136 TypeSourceInfo *CapVarTSI =
1137 Context.getTrivialTypeSourceInfo(Src->getType());
1138 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1139 ConvLocation, 0,
1140 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001141 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001142 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1143 /*Nested=*/false, /*Copy=*/Init.take());
1144 Block->setCaptures(Context, &Capture, &Capture + 1,
1145 /*CapturesCXXThis=*/false);
1146
1147 // Add a fake function body to the block. IR generation is responsible
1148 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001149 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001150
1151 // Create the block literal expression.
1152 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1153 ExprCleanupObjects.push_back(Block);
1154 ExprNeedsCleanups = true;
1155
1156 return BuildBlock;
1157}