blob: 42040084e10eb6f3973105765b65514e8dccdf38 [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"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000016#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/AST/ExprCXX.h"
21using namespace clang;
22using namespace sema;
23
Douglas Gregorf4b7de12012-02-21 19:11:17 +000024CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000026 DeclContext *DC = CurContext;
27 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
28 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000029
Douglas Gregore2a7ad02012-02-08 21:18:48 +000030 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000031 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000032 IntroducerRange.getBegin(),
33 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000034 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000035
36 return Class;
37}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000038
Douglas Gregordfca6f52012-02-13 22:00:16 +000039CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
40 SourceRange IntroducerRange,
41 TypeSourceInfo *MethodType,
Douglas Gregorc6889e72012-02-14 22:28:59 +000042 SourceLocation EndLoc,
43 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000044 // C++11 [expr.prim.lambda]p5:
45 // The closure type for a lambda-expression has a public inline function
46 // call operator (13.5.4) whose parameters and return type are described by
47 // the lambda-expression's parameter-declaration-clause and
48 // trailing-return-type respectively.
49 DeclarationName MethodName
50 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
51 DeclarationNameLoc MethodNameLoc;
52 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
53 = IntroducerRange.getBegin().getRawEncoding();
54 MethodNameLoc.CXXOperatorName.EndOpNameLoc
55 = IntroducerRange.getEnd().getRawEncoding();
56 CXXMethodDecl *Method
57 = CXXMethodDecl::Create(Context, Class, EndLoc,
58 DeclarationNameInfo(MethodName,
59 IntroducerRange.getBegin(),
60 MethodNameLoc),
61 MethodType->getType(), MethodType,
62 /*isStatic=*/false,
63 SC_None,
64 /*isInline=*/true,
65 /*isConstExpr=*/false,
66 EndLoc);
67 Method->setAccess(AS_public);
68
69 // Temporarily set the lexical declaration context to the current
70 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000071 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000072
Douglas Gregorc6889e72012-02-14 22:28:59 +000073 // Add parameters.
74 if (!Params.empty()) {
75 Method->setParams(Params);
76 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
77 const_cast<ParmVarDecl **>(Params.end()),
78 /*CheckParameterNames=*/false);
79
80 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
81 PEnd = Method->param_end();
82 P != PEnd; ++P)
83 (*P)->setOwningFunction(Method);
84 }
85
Douglas Gregordfca6f52012-02-13 22:00:16 +000086 return Method;
87}
88
89LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
90 SourceRange IntroducerRange,
91 LambdaCaptureDefault CaptureDefault,
92 bool ExplicitParams,
93 bool ExplicitResultType,
94 bool Mutable) {
95 PushLambdaScope(CallOperator->getParent(), CallOperator);
96 LambdaScopeInfo *LSI = getCurLambda();
97 if (CaptureDefault == LCD_ByCopy)
98 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
99 else if (CaptureDefault == LCD_ByRef)
100 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
101 LSI->IntroducerRange = IntroducerRange;
102 LSI->ExplicitParams = ExplicitParams;
103 LSI->Mutable = Mutable;
104
105 if (ExplicitResultType) {
106 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000107
108 if (!LSI->ReturnType->isDependentType() &&
109 !LSI->ReturnType->isVoidType()) {
110 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
111 diag::err_lambda_incomplete_result)) {
112 // Do nothing.
113 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
114 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
115 << LSI->ReturnType;
116 }
117 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000118 } else {
119 LSI->HasImplicitReturnType = true;
120 }
121
122 return LSI;
123}
124
125void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
126 LSI->finishedExplicitCaptures();
127}
128
Douglas Gregorc6889e72012-02-14 22:28:59 +0000129void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000130 // Introduce our parameters into the function scope
131 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
132 p < NumParams; ++p) {
133 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000134
135 // If this has an identifier, add it to the scope stack.
136 if (CurScope && Param->getIdentifier()) {
137 CheckShadow(CurScope, Param);
138
139 PushOnScopeChains(Param, CurScope);
140 }
141 }
142}
143
144void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
145 Declarator &ParamInfo,
146 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000147 // Determine if we're within a context where we know that the lambda will
148 // be dependent, because there are template parameters in scope.
149 bool KnownDependent = false;
150 if (Scope *TmplScope = CurScope->getTemplateParamParent())
151 if (!TmplScope->decl_empty())
152 KnownDependent = true;
153
154 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000155
156 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000157 TypeSourceInfo *MethodTyInfo;
158 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000160 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000161 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000162 if (ParamInfo.getNumTypeObjects() == 0) {
163 // C++11 [expr.prim.lambda]p4:
164 // If a lambda-expression does not include a lambda-declarator, it is as
165 // if the lambda-declarator were ().
166 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000167 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000168 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000169 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
170 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000171 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
172 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000173 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000174 EndLoc = Intro.Range.getEnd();
175 } else {
176 assert(ParamInfo.isFunctionDeclarator() &&
177 "lambda-declarator is a function");
178 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
179
180 // C++11 [expr.prim.lambda]p5:
181 // This function call operator is declared const (9.3.1) if and only if
182 // the lambda-expression's parameter-declaration-clause is not followed
183 // by mutable. It is neither virtual nor declared volatile. [...]
184 if (!FTI.hasMutableQualifier())
185 FTI.TypeQuals |= DeclSpec::TQ_const;
186
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000187 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000188 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000189 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000190
191 ExplicitResultType
192 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
193 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000194
195 TypeLoc TL = MethodTyInfo->getTypeLoc();
196 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
197 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
198 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000199 }
200
Douglas Gregordfca6f52012-02-13 22:00:16 +0000201 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000202 MethodTyInfo, EndLoc, Params);
203
204 if (ExplicitParams)
205 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000206
Douglas Gregor503384f2012-02-09 00:47:04 +0000207 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000208 ProcessDeclAttributes(CurScope, Method, ParamInfo);
209
Douglas Gregor503384f2012-02-09 00:47:04 +0000210 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000211 PushDeclContext(CurScope, Method);
212
213 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000214 LambdaScopeInfo *LSI
215 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
216 ExplicitResultType,
217 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000218
219 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000220 SourceLocation PrevCaptureLoc
221 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000222 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
223 C = Intro.Captures.begin(),
224 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000225 C != E;
226 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000227 if (C->Kind == LCK_This) {
228 // C++11 [expr.prim.lambda]p8:
229 // An identifier or this shall not appear more than once in a
230 // lambda-capture.
231 if (LSI->isCXXThisCaptured()) {
232 Diag(C->Loc, diag::err_capture_more_than_once)
233 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000234 << SourceRange(LSI->getCXXThisCapture().getLocation())
235 << FixItHint::CreateRemoval(
236 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000237 continue;
238 }
239
240 // C++11 [expr.prim.lambda]p8:
241 // If a lambda-capture includes a capture-default that is =, the
242 // lambda-capture shall not contain this [...].
243 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000244 Diag(C->Loc, diag::err_this_capture_with_copy_default)
245 << FixItHint::CreateRemoval(
246 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000247 continue;
248 }
249
250 // C++11 [expr.prim.lambda]p12:
251 // If this is captured by a local lambda expression, its nearest
252 // enclosing function shall be a non-static member function.
253 QualType ThisCaptureType = getCurrentThisType();
254 if (ThisCaptureType.isNull()) {
255 Diag(C->Loc, diag::err_this_capture) << true;
256 continue;
257 }
258
259 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
260 continue;
261 }
262
263 assert(C->Id && "missing identifier for capture");
264
265 // C++11 [expr.prim.lambda]p8:
266 // If a lambda-capture includes a capture-default that is &, the
267 // identifiers in the lambda-capture shall not be preceded by &.
268 // If a lambda-capture includes a capture-default that is =, [...]
269 // each identifier it contains shall be preceded by &.
270 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000271 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
272 << FixItHint::CreateRemoval(
273 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000274 continue;
275 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000276 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
277 << FixItHint::CreateRemoval(
278 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000279 continue;
280 }
281
282 DeclarationNameInfo Name(C->Id, C->Loc);
283 LookupResult R(*this, Name, LookupOrdinaryName);
284 LookupName(R, CurScope);
285 if (R.isAmbiguous())
286 continue;
287 if (R.empty()) {
288 // FIXME: Disable corrections that would add qualification?
289 CXXScopeSpec ScopeSpec;
290 DeclFilterCCC<VarDecl> Validator;
291 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
292 continue;
293 }
294
295 // C++11 [expr.prim.lambda]p10:
296 // The identifiers in a capture-list are looked up using the usual rules
297 // for unqualified name lookup (3.4.1); each such lookup shall find a
298 // variable with automatic storage duration declared in the reaching
299 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000300 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000301 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000302 VarDecl *Var = R.getAsSingle<VarDecl>();
303 if (!Var) {
304 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
305 continue;
306 }
307
308 if (!Var->hasLocalStorage()) {
309 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
310 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
311 continue;
312 }
313
314 // C++11 [expr.prim.lambda]p8:
315 // An identifier or this shall not appear more than once in a
316 // lambda-capture.
317 if (LSI->isCaptured(Var)) {
318 Diag(C->Loc, diag::err_capture_more_than_once)
319 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000320 << SourceRange(LSI->getCapture(Var).getLocation())
321 << FixItHint::CreateRemoval(
322 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000323 continue;
324 }
325
Douglas Gregora7365242012-02-14 19:27:52 +0000326 // C++11 [expr.prim.lambda]p23:
327 // A capture followed by an ellipsis is a pack expansion (14.5.3).
328 SourceLocation EllipsisLoc;
329 if (C->EllipsisLoc.isValid()) {
330 if (Var->isParameterPack()) {
331 EllipsisLoc = C->EllipsisLoc;
332 } else {
333 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
334 << SourceRange(C->Loc);
335
336 // Just ignore the ellipsis.
337 }
338 } else if (Var->isParameterPack()) {
339 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
340 continue;
341 }
342
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000343 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
344 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000345 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000346 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000347 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000348
Douglas Gregorc6889e72012-02-14 22:28:59 +0000349 // Add lambda parameters into scope.
350 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000351
Douglas Gregordfca6f52012-02-13 22:00:16 +0000352 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000353 // cleanups from the enclosing full-expression.
354 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000355}
356
Douglas Gregordfca6f52012-02-13 22:00:16 +0000357void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
358 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000359 // Leave the expression-evaluation context.
360 DiscardCleanupsInEvaluationContext();
361 PopExpressionEvaluationContext();
362
363 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000364 if (!IsInstantiation)
365 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000366
367 // Finalize the lambda.
368 LambdaScopeInfo *LSI = getCurLambda();
369 CXXRecordDecl *Class = LSI->Lambda;
370 Class->setInvalidDecl();
371 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
372 ActOnFields(0, Class->getLocation(), Class, Fields,
373 SourceLocation(), SourceLocation(), 0);
374 CheckCompletedCXXClass(Class);
375
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000376 PopFunctionScopeInfo();
377}
378
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000379/// \brief Add a lambda's conversion to function pointer, as described in
380/// C++11 [expr.prim.lambda]p6.
381static void addFunctionPointerConversion(Sema &S,
382 SourceRange IntroducerRange,
383 CXXRecordDecl *Class,
384 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000385 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000386 const FunctionProtoType *Proto
387 = CallOperator->getType()->getAs<FunctionProtoType>();
388 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000389 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000390 {
391 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
392 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000393 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
394 Proto->arg_type_begin(),
395 Proto->getNumArgs(),
396 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000397 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
398 }
399
400 FunctionProtoType::ExtProtoInfo ExtInfo;
401 ExtInfo.TypeQuals = Qualifiers::Const;
402 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
403
404 SourceLocation Loc = IntroducerRange.getBegin();
405 DeclarationName Name
406 = S.Context.DeclarationNames.getCXXConversionFunctionName(
407 S.Context.getCanonicalType(FunctionPtrTy));
408 DeclarationNameLoc NameLoc;
409 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
410 Loc);
411 CXXConversionDecl *Conversion
412 = CXXConversionDecl::Create(S.Context, Class, Loc,
413 DeclarationNameInfo(Name, Loc, NameLoc),
414 ConvTy,
415 S.Context.getTrivialTypeSourceInfo(ConvTy,
416 Loc),
417 /*isInline=*/false, /*isExplicit=*/false,
418 /*isConstexpr=*/false,
419 CallOperator->getBody()->getLocEnd());
420 Conversion->setAccess(AS_public);
421 Conversion->setImplicit(true);
422 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000423
424 // Add a non-static member function "__invoke" that will be the result of
425 // the conversion.
426 Name = &S.Context.Idents.get("__invoke");
427 CXXMethodDecl *Invoke
428 = CXXMethodDecl::Create(S.Context, Class, Loc,
429 DeclarationNameInfo(Name, Loc), FunctionTy,
430 CallOperator->getTypeSourceInfo(),
431 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
432 /*IsConstexpr=*/false,
433 CallOperator->getBody()->getLocEnd());
434 SmallVector<ParmVarDecl *, 4> InvokeParams;
435 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
436 ParmVarDecl *From = CallOperator->getParamDecl(I);
437 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
438 From->getLocStart(),
439 From->getLocation(),
440 From->getIdentifier(),
441 From->getType(),
442 From->getTypeSourceInfo(),
443 From->getStorageClass(),
444 From->getStorageClassAsWritten(),
445 /*DefaultArg=*/0));
446 }
447 Invoke->setParams(InvokeParams);
448 Invoke->setAccess(AS_private);
449 Invoke->setImplicit(true);
450 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000451}
452
Douglas Gregorc2956e52012-02-15 22:08:38 +0000453/// \brief Add a lambda's conversion to block pointer.
454static void addBlockPointerConversion(Sema &S,
455 SourceRange IntroducerRange,
456 CXXRecordDecl *Class,
457 CXXMethodDecl *CallOperator) {
458 const FunctionProtoType *Proto
459 = CallOperator->getType()->getAs<FunctionProtoType>();
460 QualType BlockPtrTy;
461 {
462 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
463 ExtInfo.TypeQuals = 0;
464 QualType FunctionTy
465 = S.Context.getFunctionType(Proto->getResultType(),
466 Proto->arg_type_begin(),
467 Proto->getNumArgs(),
468 ExtInfo);
469 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
470 }
471
472 FunctionProtoType::ExtProtoInfo ExtInfo;
473 ExtInfo.TypeQuals = Qualifiers::Const;
474 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
475
476 SourceLocation Loc = IntroducerRange.getBegin();
477 DeclarationName Name
478 = S.Context.DeclarationNames.getCXXConversionFunctionName(
479 S.Context.getCanonicalType(BlockPtrTy));
480 DeclarationNameLoc NameLoc;
481 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
482 CXXConversionDecl *Conversion
483 = CXXConversionDecl::Create(S.Context, Class, Loc,
484 DeclarationNameInfo(Name, Loc, NameLoc),
485 ConvTy,
486 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
487 /*isInline=*/false, /*isExplicit=*/false,
488 /*isConstexpr=*/false,
489 CallOperator->getBody()->getLocEnd());
490 Conversion->setAccess(AS_public);
491 Conversion->setImplicit(true);
492 Class->addDecl(Conversion);
493}
494
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000495/// \brief Determine whether the given context is or is enclosed in an inline
496/// function.
497static bool isInInlineFunction(const DeclContext *DC) {
498 while (!DC->isFileContext()) {
499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
500 if (FD->isInlined())
501 return true;
502
503 DC = DC->getLexicalParent();
504 }
505
506 return false;
507}
508
Douglas Gregordfca6f52012-02-13 22:00:16 +0000509ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000510 Scope *CurScope,
511 llvm::Optional<unsigned> ManglingNumber,
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000512 Decl *ContextDecl,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000513 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000514 // Leave the expression-evaluation context.
515 DiscardCleanupsInEvaluationContext();
516 PopExpressionEvaluationContext();
517
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000518 // Collect information from the lambda scope.
519 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
520 llvm::SmallVector<Expr *, 4> CaptureInits;
521 LambdaCaptureDefault CaptureDefault;
522 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000523 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000524 SourceRange IntroducerRange;
525 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000526 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000527 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000528 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
529 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000530 {
531 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000532 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000533 Class = LSI->Lambda;
534 IntroducerRange = LSI->IntroducerRange;
535 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000536 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000537 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000538 ArrayIndexVars.swap(LSI->ArrayIndexVars);
539 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
540
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000541 // Translate captures.
542 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
543 LambdaScopeInfo::Capture From = LSI->Captures[I];
544 assert(!From.isBlockCapture() && "Cannot capture __block variables");
545 bool IsImplicit = I >= LSI->NumExplicitCaptures;
546
547 // Handle 'this' capture.
548 if (From.isThisCapture()) {
549 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
550 IsImplicit,
551 LCK_This));
552 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
553 getCurrentThisType(),
554 /*isImplicit=*/true));
555 continue;
556 }
557
558 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000559 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
560 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000561 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000562 CaptureInits.push_back(From.getCopyExpr());
563 }
564
565 switch (LSI->ImpCaptureStyle) {
566 case CapturingScopeInfo::ImpCap_None:
567 CaptureDefault = LCD_None;
568 break;
569
570 case CapturingScopeInfo::ImpCap_LambdaByval:
571 CaptureDefault = LCD_ByCopy;
572 break;
573
574 case CapturingScopeInfo::ImpCap_LambdaByref:
575 CaptureDefault = LCD_ByRef;
576 break;
577
578 case CapturingScopeInfo::ImpCap_Block:
579 llvm_unreachable("block capture in lambda");
580 break;
581 }
582
Douglas Gregor54042f12012-02-09 10:18:50 +0000583 // C++11 [expr.prim.lambda]p4:
584 // If a lambda-expression does not include a
585 // trailing-return-type, it is as if the trailing-return-type
586 // denotes the following type:
587 // FIXME: Assumes current resolution to core issue 975.
588 if (LSI->HasImplicitReturnType) {
589 // - if there are no return statements in the
590 // compound-statement, or all return statements return
591 // either an expression of type void or no expression or
592 // braced-init-list, the type void;
593 if (LSI->ReturnType.isNull()) {
594 LSI->ReturnType = Context.VoidTy;
595 } else {
596 // C++11 [expr.prim.lambda]p4:
597 // - if the compound-statement is of the form
598 //
599 // { attribute-specifier-seq[opt] return expression ; }
600 //
601 // the type of the returned expression after
602 // lvalue-to-rvalue conversion (4.1), array-to-pointer
603 // conver- sion (4.2), and function-to-pointer conversion
604 // (4.3);
605 //
606 // Since we're accepting the resolution to a post-C++11 core
607 // issue with a non-trivial extension, provide a warning (by
608 // default).
609 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
610 if (!(CompoundBody->size() == 1 &&
611 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
612 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
613 Diag(IntroducerRange.getBegin(),
614 diag::ext_lambda_implies_void_return);
615 }
616
617 // Create a function type with the inferred return type.
618 const FunctionProtoType *Proto
619 = CallOperator->getType()->getAs<FunctionProtoType>();
620 QualType FunctionTy
621 = Context.getFunctionType(LSI->ReturnType,
622 Proto->arg_type_begin(),
623 Proto->getNumArgs(),
624 Proto->getExtProtoInfo());
625 CallOperator->setType(FunctionTy);
626 }
627
Douglas Gregor215e4e12012-02-12 17:34:23 +0000628 // C++ [expr.prim.lambda]p7:
629 // The lambda-expression's compound-statement yields the
630 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000631 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000632 CallOperator->setLexicalDeclContext(Class);
633 Class->addDecl(CallOperator);
634
Douglas Gregorb5559712012-02-10 16:13:20 +0000635 // C++11 [expr.prim.lambda]p6:
636 // The closure type for a lambda-expression with no lambda-capture
637 // has a public non-virtual non-explicit const conversion function
638 // to pointer to function having the same parameter and return
639 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000640 if (Captures.empty() && CaptureDefault == LCD_None)
641 addFunctionPointerConversion(*this, IntroducerRange, Class,
642 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000643
Douglas Gregorc2956e52012-02-15 22:08:38 +0000644 // Objective-C++:
645 // The closure type for a lambda-expression has a public non-virtual
646 // non-explicit const conversion function to a block pointer having the
647 // same parameter and return types as the closure type's function call
648 // operator.
649 if (getLangOptions().Blocks)
650 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
651
Douglas Gregorb5559712012-02-10 16:13:20 +0000652 // Finalize the lambda class.
653 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000654 ActOnFields(0, Class->getLocation(), Class, Fields,
655 SourceLocation(), SourceLocation(), 0);
656 CheckCompletedCXXClass(Class);
657
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000658 }
659
Douglas Gregor503384f2012-02-09 00:47:04 +0000660 if (LambdaExprNeedsCleanups)
661 ExprNeedsCleanups = true;
662
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000663 // If we don't already have a mangling number for this lambda expression,
664 // allocate one now.
665 if (!ManglingNumber) {
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000666 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
667
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000668 enum ContextKind {
669 Normal,
Douglas Gregor552e2992012-02-21 02:22:07 +0000670 DefaultArgument,
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000671 DataMember,
Craig Toppera7b07fd2012-02-21 05:39:57 +0000672 StaticDataMember
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000673 } Kind = Normal;
674
675 // Default arguments of member function parameters that appear in a class
Douglas Gregor552e2992012-02-21 02:22:07 +0000676 // definition, as well as the initializers of data members, receive special
677 // treatment. Identify them.
678 if (ContextDecl) {
679 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
680 if (const DeclContext *LexicalDC
681 = Param->getDeclContext()->getLexicalParent())
682 if (LexicalDC->isRecord())
683 Kind = DefaultArgument;
684 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
685 if (Var->getDeclContext()->isRecord())
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000686 Kind = StaticDataMember;
Douglas Gregor552e2992012-02-21 02:22:07 +0000687 } else if (isa<FieldDecl>(ContextDecl)) {
688 Kind = DataMember;
689 }
690 }
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000691
692 switch (Kind) {
693 case Normal:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000694 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
695 ManglingNumber = Context.getLambdaManglingNumber(CallOperator);
696 else
697 ManglingNumber = 0;
698
699 // There is no special context for this lambda.
700 ContextDecl = 0;
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000701 break;
702
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000703 case StaticDataMember:
704 if (!CurContext->isDependentContext()) {
705 ManglingNumber = 0;
706 ContextDecl = 0;
707 break;
708 }
709 // Fall through to assign a mangling number.
710
Douglas Gregor552e2992012-02-21 02:22:07 +0000711 case DataMember:
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000712 case DefaultArgument:
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000713 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
714 .getManglingNumber(CallOperator);
715 break;
716 }
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000717 }
718
Douglas Gregore2c59132012-02-09 08:14:43 +0000719 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
720 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000721 ExplicitParams, ExplicitResultType,
722 CaptureInits, ArrayIndexVars,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000723 ArrayIndexStarts, Body->getLocEnd(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000724 *ManglingNumber, ContextDecl);
Douglas Gregore2c59132012-02-09 08:14:43 +0000725
726 // C++11 [expr.prim.lambda]p2:
727 // A lambda-expression shall not appear in an unevaluated operand
728 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000729 if (!CurContext->isDependentContext()) {
730 switch (ExprEvalContexts.back().Context) {
731 case Unevaluated:
732 // We don't actually diagnose this case immediately, because we
733 // could be within a context where we might find out later that
734 // the expression is potentially evaluated (e.g., for typeid).
735 ExprEvalContexts.back().Lambdas.push_back(Lambda);
736 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000737
Douglas Gregord5387e82012-02-14 00:00:48 +0000738 case ConstantEvaluated:
739 case PotentiallyEvaluated:
740 case PotentiallyEvaluatedIfUsed:
741 break;
742 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000743 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000744
Douglas Gregor503384f2012-02-09 00:47:04 +0000745 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746}