blob: 2e391f4d4532396a34049647e1aa675e9314c9ce [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 Gregorf54486a2012-04-04 17:40:10 +000039/// \brief Determine whether the given context is or is enclosed in an inline
40/// function.
41static bool isInInlineFunction(const DeclContext *DC) {
42 while (!DC->isFileContext()) {
43 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
44 if (FD->isInlined())
45 return true;
46
47 DC = DC->getLexicalParent();
48 }
49
50 return false;
51}
52
Douglas Gregordfca6f52012-02-13 22:00:16 +000053CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +000054 SourceRange IntroducerRange,
55 TypeSourceInfo *MethodType,
56 SourceLocation EndLoc,
57 llvm::ArrayRef<ParmVarDecl *> Params,
58 llvm::Optional<unsigned> ManglingNumber,
59 Decl *ContextDecl) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000060 // C++11 [expr.prim.lambda]p5:
61 // The closure type for a lambda-expression has a public inline function
62 // call operator (13.5.4) whose parameters and return type are described by
63 // the lambda-expression's parameter-declaration-clause and
64 // trailing-return-type respectively.
65 DeclarationName MethodName
66 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67 DeclarationNameLoc MethodNameLoc;
68 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69 = IntroducerRange.getBegin().getRawEncoding();
70 MethodNameLoc.CXXOperatorName.EndOpNameLoc
71 = IntroducerRange.getEnd().getRawEncoding();
72 CXXMethodDecl *Method
73 = CXXMethodDecl::Create(Context, Class, EndLoc,
74 DeclarationNameInfo(MethodName,
75 IntroducerRange.getBegin(),
76 MethodNameLoc),
77 MethodType->getType(), MethodType,
78 /*isStatic=*/false,
79 SC_None,
80 /*isInline=*/true,
81 /*isConstExpr=*/false,
82 EndLoc);
83 Method->setAccess(AS_public);
84
85 // Temporarily set the lexical declaration context to the current
86 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000087 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000088
Douglas Gregorc6889e72012-02-14 22:28:59 +000089 // Add parameters.
90 if (!Params.empty()) {
91 Method->setParams(Params);
92 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93 const_cast<ParmVarDecl **>(Params.end()),
94 /*CheckParameterNames=*/false);
95
96 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97 PEnd = Method->param_end();
98 P != PEnd; ++P)
99 (*P)->setOwningFunction(Method);
100 }
101
Douglas Gregorf54486a2012-04-04 17:40:10 +0000102 // If we don't already have a mangling number for this lambda expression,
103 // allocate one now.
104 if (!ManglingNumber) {
105 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
106
107 enum ContextKind {
108 Normal,
109 DefaultArgument,
110 DataMember,
111 StaticDataMember
112 } Kind = Normal;
113
114 // Default arguments of member function parameters that appear in a class
115 // definition, as well as the initializers of data members, receive special
116 // treatment. Identify them.
117 if (ContextDecl) {
118 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
119 if (const DeclContext *LexicalDC
120 = Param->getDeclContext()->getLexicalParent())
121 if (LexicalDC->isRecord())
122 Kind = DefaultArgument;
123 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
124 if (Var->getDeclContext()->isRecord())
125 Kind = StaticDataMember;
126 } else if (isa<FieldDecl>(ContextDecl)) {
127 Kind = DataMember;
128 }
129 }
130
131 switch (Kind) {
132 case Normal:
133 if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134 ManglingNumber = Context.getLambdaManglingNumber(Method);
135 else
136 ManglingNumber = 0;
137
138 // There is no special context for this lambda.
139 ContextDecl = 0;
140 break;
141
142 case StaticDataMember:
143 if (!CurContext->isDependentContext()) {
144 ManglingNumber = 0;
145 ContextDecl = 0;
146 break;
147 }
148 // Fall through to assign a mangling number.
149
150 case DataMember:
151 case DefaultArgument:
152 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153 .getManglingNumber(Method);
154 break;
155 }
156 }
157
158 Class->setLambdaMangling(*ManglingNumber, ContextDecl);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 return Method;
160}
161
162LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163 SourceRange IntroducerRange,
164 LambdaCaptureDefault CaptureDefault,
165 bool ExplicitParams,
166 bool ExplicitResultType,
167 bool Mutable) {
168 PushLambdaScope(CallOperator->getParent(), CallOperator);
169 LambdaScopeInfo *LSI = getCurLambda();
170 if (CaptureDefault == LCD_ByCopy)
171 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
172 else if (CaptureDefault == LCD_ByRef)
173 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
174 LSI->IntroducerRange = IntroducerRange;
175 LSI->ExplicitParams = ExplicitParams;
176 LSI->Mutable = Mutable;
177
178 if (ExplicitResultType) {
179 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000180
181 if (!LSI->ReturnType->isDependentType() &&
182 !LSI->ReturnType->isVoidType()) {
183 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184 diag::err_lambda_incomplete_result)) {
185 // Do nothing.
186 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
188 << LSI->ReturnType;
189 }
190 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 } else {
192 LSI->HasImplicitReturnType = true;
193 }
194
195 return LSI;
196}
197
198void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199 LSI->finishedExplicitCaptures();
200}
201
Douglas Gregorc6889e72012-02-14 22:28:59 +0000202void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000203 // Introduce our parameters into the function scope
204 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
205 p < NumParams; ++p) {
206 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000207
208 // If this has an identifier, add it to the scope stack.
209 if (CurScope && Param->getIdentifier()) {
210 CheckShadow(CurScope, Param);
211
212 PushOnScopeChains(Param, CurScope);
213 }
214 }
215}
216
217void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
218 Declarator &ParamInfo,
219 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000220 // Determine if we're within a context where we know that the lambda will
221 // be dependent, because there are template parameters in scope.
222 bool KnownDependent = false;
223 if (Scope *TmplScope = CurScope->getTemplateParamParent())
224 if (!TmplScope->decl_empty())
225 KnownDependent = true;
226
227 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000228
229 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000230 TypeSourceInfo *MethodTyInfo;
231 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000232 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000233 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000234 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000235 if (ParamInfo.getNumTypeObjects() == 0) {
236 // C++11 [expr.prim.lambda]p4:
237 // If a lambda-expression does not include a lambda-declarator, it is as
238 // if the lambda-declarator were ().
239 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000240 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000241 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000242 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
243 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000244 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
245 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000246 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000247 EndLoc = Intro.Range.getEnd();
248 } else {
249 assert(ParamInfo.isFunctionDeclarator() &&
250 "lambda-declarator is a function");
251 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
252
253 // C++11 [expr.prim.lambda]p5:
254 // This function call operator is declared const (9.3.1) if and only if
255 // the lambda-expression's parameter-declaration-clause is not followed
256 // by mutable. It is neither virtual nor declared volatile. [...]
257 if (!FTI.hasMutableQualifier())
258 FTI.TypeQuals |= DeclSpec::TQ_const;
259
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000260 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000261 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000262 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000263
264 ExplicitResultType
265 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
266 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000267
268 TypeLoc TL = MethodTyInfo->getTypeLoc();
269 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
270 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
271 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000272 }
273
Douglas Gregordfca6f52012-02-13 22:00:16 +0000274 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000275 MethodTyInfo, EndLoc, Params);
276
277 if (ExplicitParams)
278 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000279
Douglas Gregor503384f2012-02-09 00:47:04 +0000280 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000281 ProcessDeclAttributes(CurScope, Method, ParamInfo);
282
Douglas Gregor503384f2012-02-09 00:47:04 +0000283 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000284 PushDeclContext(CurScope, Method);
285
286 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000287 LambdaScopeInfo *LSI
288 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
289 ExplicitResultType,
290 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000291
292 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000293 SourceLocation PrevCaptureLoc
294 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000295 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
296 C = Intro.Captures.begin(),
297 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000298 C != E;
299 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000300 if (C->Kind == LCK_This) {
301 // C++11 [expr.prim.lambda]p8:
302 // An identifier or this shall not appear more than once in a
303 // lambda-capture.
304 if (LSI->isCXXThisCaptured()) {
305 Diag(C->Loc, diag::err_capture_more_than_once)
306 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000307 << SourceRange(LSI->getCXXThisCapture().getLocation())
308 << FixItHint::CreateRemoval(
309 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000310 continue;
311 }
312
313 // C++11 [expr.prim.lambda]p8:
314 // If a lambda-capture includes a capture-default that is =, the
315 // lambda-capture shall not contain this [...].
316 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000317 Diag(C->Loc, diag::err_this_capture_with_copy_default)
318 << FixItHint::CreateRemoval(
319 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000320 continue;
321 }
322
323 // C++11 [expr.prim.lambda]p12:
324 // If this is captured by a local lambda expression, its nearest
325 // enclosing function shall be a non-static member function.
326 QualType ThisCaptureType = getCurrentThisType();
327 if (ThisCaptureType.isNull()) {
328 Diag(C->Loc, diag::err_this_capture) << true;
329 continue;
330 }
331
332 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
333 continue;
334 }
335
336 assert(C->Id && "missing identifier for capture");
337
338 // C++11 [expr.prim.lambda]p8:
339 // If a lambda-capture includes a capture-default that is &, the
340 // identifiers in the lambda-capture shall not be preceded by &.
341 // If a lambda-capture includes a capture-default that is =, [...]
342 // each identifier it contains shall be preceded by &.
343 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000344 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
345 << FixItHint::CreateRemoval(
346 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000347 continue;
348 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000349 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
350 << FixItHint::CreateRemoval(
351 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000352 continue;
353 }
354
355 DeclarationNameInfo Name(C->Id, C->Loc);
356 LookupResult R(*this, Name, LookupOrdinaryName);
357 LookupName(R, CurScope);
358 if (R.isAmbiguous())
359 continue;
360 if (R.empty()) {
361 // FIXME: Disable corrections that would add qualification?
362 CXXScopeSpec ScopeSpec;
363 DeclFilterCCC<VarDecl> Validator;
364 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
365 continue;
366 }
367
368 // C++11 [expr.prim.lambda]p10:
369 // The identifiers in a capture-list are looked up using the usual rules
370 // for unqualified name lookup (3.4.1); each such lookup shall find a
371 // variable with automatic storage duration declared in the reaching
372 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000373 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000374 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000375 VarDecl *Var = R.getAsSingle<VarDecl>();
376 if (!Var) {
377 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
378 continue;
379 }
380
381 if (!Var->hasLocalStorage()) {
382 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
383 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
384 continue;
385 }
386
387 // C++11 [expr.prim.lambda]p8:
388 // An identifier or this shall not appear more than once in a
389 // lambda-capture.
390 if (LSI->isCaptured(Var)) {
391 Diag(C->Loc, diag::err_capture_more_than_once)
392 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000393 << SourceRange(LSI->getCapture(Var).getLocation())
394 << FixItHint::CreateRemoval(
395 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000396 continue;
397 }
398
Douglas Gregora7365242012-02-14 19:27:52 +0000399 // C++11 [expr.prim.lambda]p23:
400 // A capture followed by an ellipsis is a pack expansion (14.5.3).
401 SourceLocation EllipsisLoc;
402 if (C->EllipsisLoc.isValid()) {
403 if (Var->isParameterPack()) {
404 EllipsisLoc = C->EllipsisLoc;
405 } else {
406 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
407 << SourceRange(C->Loc);
408
409 // Just ignore the ellipsis.
410 }
411 } else if (Var->isParameterPack()) {
412 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
413 continue;
414 }
415
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000416 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
417 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000418 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000419 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000420 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000421
Douglas Gregorc6889e72012-02-14 22:28:59 +0000422 // Add lambda parameters into scope.
423 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000424
Douglas Gregordfca6f52012-02-13 22:00:16 +0000425 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000426 // cleanups from the enclosing full-expression.
427 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000428}
429
Douglas Gregordfca6f52012-02-13 22:00:16 +0000430void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
431 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000432 // Leave the expression-evaluation context.
433 DiscardCleanupsInEvaluationContext();
434 PopExpressionEvaluationContext();
435
436 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000437 if (!IsInstantiation)
438 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000439
440 // Finalize the lambda.
441 LambdaScopeInfo *LSI = getCurLambda();
442 CXXRecordDecl *Class = LSI->Lambda;
443 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000444 SmallVector<Decl*, 4> Fields;
445 for (RecordDecl::field_iterator i = Class->field_begin(),
446 e = Class->field_end(); i != e; ++i)
447 Fields.push_back(&*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000448 ActOnFields(0, Class->getLocation(), Class, Fields,
449 SourceLocation(), SourceLocation(), 0);
450 CheckCompletedCXXClass(Class);
451
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000452 PopFunctionScopeInfo();
453}
454
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000455/// \brief Add a lambda's conversion to function pointer, as described in
456/// C++11 [expr.prim.lambda]p6.
457static void addFunctionPointerConversion(Sema &S,
458 SourceRange IntroducerRange,
459 CXXRecordDecl *Class,
460 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000461 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000462 const FunctionProtoType *Proto
463 = CallOperator->getType()->getAs<FunctionProtoType>();
464 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000465 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000466 {
467 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
468 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000469 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
470 Proto->arg_type_begin(),
471 Proto->getNumArgs(),
472 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000473 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
474 }
475
476 FunctionProtoType::ExtProtoInfo ExtInfo;
477 ExtInfo.TypeQuals = Qualifiers::Const;
478 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
479
480 SourceLocation Loc = IntroducerRange.getBegin();
481 DeclarationName Name
482 = S.Context.DeclarationNames.getCXXConversionFunctionName(
483 S.Context.getCanonicalType(FunctionPtrTy));
484 DeclarationNameLoc NameLoc;
485 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
486 Loc);
487 CXXConversionDecl *Conversion
488 = CXXConversionDecl::Create(S.Context, Class, Loc,
489 DeclarationNameInfo(Name, Loc, NameLoc),
490 ConvTy,
491 S.Context.getTrivialTypeSourceInfo(ConvTy,
492 Loc),
493 /*isInline=*/false, /*isExplicit=*/false,
494 /*isConstexpr=*/false,
495 CallOperator->getBody()->getLocEnd());
496 Conversion->setAccess(AS_public);
497 Conversion->setImplicit(true);
498 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000499
500 // Add a non-static member function "__invoke" that will be the result of
501 // the conversion.
502 Name = &S.Context.Idents.get("__invoke");
503 CXXMethodDecl *Invoke
504 = CXXMethodDecl::Create(S.Context, Class, Loc,
505 DeclarationNameInfo(Name, Loc), FunctionTy,
506 CallOperator->getTypeSourceInfo(),
507 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
508 /*IsConstexpr=*/false,
509 CallOperator->getBody()->getLocEnd());
510 SmallVector<ParmVarDecl *, 4> InvokeParams;
511 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
512 ParmVarDecl *From = CallOperator->getParamDecl(I);
513 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
514 From->getLocStart(),
515 From->getLocation(),
516 From->getIdentifier(),
517 From->getType(),
518 From->getTypeSourceInfo(),
519 From->getStorageClass(),
520 From->getStorageClassAsWritten(),
521 /*DefaultArg=*/0));
522 }
523 Invoke->setParams(InvokeParams);
524 Invoke->setAccess(AS_private);
525 Invoke->setImplicit(true);
526 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000527}
528
Douglas Gregorc2956e52012-02-15 22:08:38 +0000529/// \brief Add a lambda's conversion to block pointer.
530static void addBlockPointerConversion(Sema &S,
531 SourceRange IntroducerRange,
532 CXXRecordDecl *Class,
533 CXXMethodDecl *CallOperator) {
534 const FunctionProtoType *Proto
535 = CallOperator->getType()->getAs<FunctionProtoType>();
536 QualType BlockPtrTy;
537 {
538 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
539 ExtInfo.TypeQuals = 0;
540 QualType FunctionTy
541 = S.Context.getFunctionType(Proto->getResultType(),
542 Proto->arg_type_begin(),
543 Proto->getNumArgs(),
544 ExtInfo);
545 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
546 }
547
548 FunctionProtoType::ExtProtoInfo ExtInfo;
549 ExtInfo.TypeQuals = Qualifiers::Const;
550 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
551
552 SourceLocation Loc = IntroducerRange.getBegin();
553 DeclarationName Name
554 = S.Context.DeclarationNames.getCXXConversionFunctionName(
555 S.Context.getCanonicalType(BlockPtrTy));
556 DeclarationNameLoc NameLoc;
557 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
558 CXXConversionDecl *Conversion
559 = CXXConversionDecl::Create(S.Context, Class, Loc,
560 DeclarationNameInfo(Name, Loc, NameLoc),
561 ConvTy,
562 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
563 /*isInline=*/false, /*isExplicit=*/false,
564 /*isConstexpr=*/false,
565 CallOperator->getBody()->getLocEnd());
566 Conversion->setAccess(AS_public);
567 Conversion->setImplicit(true);
568 Class->addDecl(Conversion);
569}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000570
Douglas Gregordfca6f52012-02-13 22:00:16 +0000571ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000572 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000573 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000574 // Collect information from the lambda scope.
575 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
576 llvm::SmallVector<Expr *, 4> CaptureInits;
577 LambdaCaptureDefault CaptureDefault;
578 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000579 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 SourceRange IntroducerRange;
581 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000582 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000583 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000584 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
585 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000586 {
587 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000588 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000589 Class = LSI->Lambda;
590 IntroducerRange = LSI->IntroducerRange;
591 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000592 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000593 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000594 ArrayIndexVars.swap(LSI->ArrayIndexVars);
595 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
596
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000597 // Translate captures.
598 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
599 LambdaScopeInfo::Capture From = LSI->Captures[I];
600 assert(!From.isBlockCapture() && "Cannot capture __block variables");
601 bool IsImplicit = I >= LSI->NumExplicitCaptures;
602
603 // Handle 'this' capture.
604 if (From.isThisCapture()) {
605 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
606 IsImplicit,
607 LCK_This));
608 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
609 getCurrentThisType(),
610 /*isImplicit=*/true));
611 continue;
612 }
613
614 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000615 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
616 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000617 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000618 CaptureInits.push_back(From.getCopyExpr());
619 }
620
621 switch (LSI->ImpCaptureStyle) {
622 case CapturingScopeInfo::ImpCap_None:
623 CaptureDefault = LCD_None;
624 break;
625
626 case CapturingScopeInfo::ImpCap_LambdaByval:
627 CaptureDefault = LCD_ByCopy;
628 break;
629
630 case CapturingScopeInfo::ImpCap_LambdaByref:
631 CaptureDefault = LCD_ByRef;
632 break;
633
634 case CapturingScopeInfo::ImpCap_Block:
635 llvm_unreachable("block capture in lambda");
636 break;
637 }
638
Douglas Gregor54042f12012-02-09 10:18:50 +0000639 // C++11 [expr.prim.lambda]p4:
640 // If a lambda-expression does not include a
641 // trailing-return-type, it is as if the trailing-return-type
642 // denotes the following type:
643 // FIXME: Assumes current resolution to core issue 975.
644 if (LSI->HasImplicitReturnType) {
645 // - if there are no return statements in the
646 // compound-statement, or all return statements return
647 // either an expression of type void or no expression or
648 // braced-init-list, the type void;
649 if (LSI->ReturnType.isNull()) {
650 LSI->ReturnType = Context.VoidTy;
651 } else {
652 // C++11 [expr.prim.lambda]p4:
653 // - if the compound-statement is of the form
654 //
655 // { attribute-specifier-seq[opt] return expression ; }
656 //
657 // the type of the returned expression after
658 // lvalue-to-rvalue conversion (4.1), array-to-pointer
659 // conver- sion (4.2), and function-to-pointer conversion
660 // (4.3);
661 //
662 // Since we're accepting the resolution to a post-C++11 core
663 // issue with a non-trivial extension, provide a warning (by
664 // default).
665 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
666 if (!(CompoundBody->size() == 1 &&
667 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
668 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
669 Diag(IntroducerRange.getBegin(),
670 diag::ext_lambda_implies_void_return);
671 }
672
673 // Create a function type with the inferred return type.
674 const FunctionProtoType *Proto
675 = CallOperator->getType()->getAs<FunctionProtoType>();
676 QualType FunctionTy
677 = Context.getFunctionType(LSI->ReturnType,
678 Proto->arg_type_begin(),
679 Proto->getNumArgs(),
680 Proto->getExtProtoInfo());
681 CallOperator->setType(FunctionTy);
682 }
683
Douglas Gregor215e4e12012-02-12 17:34:23 +0000684 // C++ [expr.prim.lambda]p7:
685 // The lambda-expression's compound-statement yields the
686 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000687 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000688 CallOperator->setLexicalDeclContext(Class);
689 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +0000690 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +0000691
Douglas Gregorb5559712012-02-10 16:13:20 +0000692 // C++11 [expr.prim.lambda]p6:
693 // The closure type for a lambda-expression with no lambda-capture
694 // has a public non-virtual non-explicit const conversion function
695 // to pointer to function having the same parameter and return
696 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000697 if (Captures.empty() && CaptureDefault == LCD_None)
698 addFunctionPointerConversion(*this, IntroducerRange, Class,
699 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000700
Douglas Gregorc2956e52012-02-15 22:08:38 +0000701 // Objective-C++:
702 // The closure type for a lambda-expression has a public non-virtual
703 // non-explicit const conversion function to a block pointer having the
704 // same parameter and return types as the closure type's function call
705 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +0000707 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
708
Douglas Gregorb5559712012-02-10 16:13:20 +0000709 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +0000710 SmallVector<Decl*, 4> Fields;
711 for (RecordDecl::field_iterator i = Class->field_begin(),
712 e = Class->field_end(); i != e; ++i)
713 Fields.push_back(&*i);
Douglas Gregorb5559712012-02-10 16:13:20 +0000714 ActOnFields(0, Class->getLocation(), Class, Fields,
715 SourceLocation(), SourceLocation(), 0);
716 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000717 }
718
Douglas Gregor503384f2012-02-09 00:47:04 +0000719 if (LambdaExprNeedsCleanups)
720 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000721
Douglas Gregore2c59132012-02-09 08:14:43 +0000722 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
723 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000724 ExplicitParams, ExplicitResultType,
725 CaptureInits, ArrayIndexVars,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000726 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000727
728 // C++11 [expr.prim.lambda]p2:
729 // A lambda-expression shall not appear in an unevaluated operand
730 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000731 if (!CurContext->isDependentContext()) {
732 switch (ExprEvalContexts.back().Context) {
733 case Unevaluated:
734 // We don't actually diagnose this case immediately, because we
735 // could be within a context where we might find out later that
736 // the expression is potentially evaluated (e.g., for typeid).
737 ExprEvalContexts.back().Lambdas.push_back(Lambda);
738 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000739
Douglas Gregord5387e82012-02-14 00:00:48 +0000740 case ConstantEvaluated:
741 case PotentiallyEvaluated:
742 case PotentiallyEvaluatedIfUsed:
743 break;
744 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000745 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000746
Douglas Gregor503384f2012-02-09 00:47:04 +0000747 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000748}
Eli Friedman23f02672012-03-01 04:01:32 +0000749
750ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
751 SourceLocation ConvLocation,
752 CXXConversionDecl *Conv,
753 Expr *Src) {
754 // Make sure that the lambda call operator is marked used.
755 CXXRecordDecl *Lambda = Conv->getParent();
756 CXXMethodDecl *CallOperator
757 = cast<CXXMethodDecl>(
758 *Lambda->lookup(
759 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
760 CallOperator->setReferenced();
761 CallOperator->setUsed();
762
763 ExprResult Init = PerformCopyInitialization(
764 InitializedEntity::InitializeBlock(ConvLocation,
765 Src->getType(),
766 /*NRVO=*/false),
767 CurrentLocation, Src);
768 if (!Init.isInvalid())
769 Init = ActOnFinishFullExpr(Init.take());
770
771 if (Init.isInvalid())
772 return ExprError();
773
774 // Create the new block to be returned.
775 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
776
777 // Set the type information.
778 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
779 Block->setIsVariadic(CallOperator->isVariadic());
780 Block->setBlockMissingReturnType(false);
781
782 // Add parameters.
783 SmallVector<ParmVarDecl *, 4> BlockParams;
784 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
785 ParmVarDecl *From = CallOperator->getParamDecl(I);
786 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
787 From->getLocStart(),
788 From->getLocation(),
789 From->getIdentifier(),
790 From->getType(),
791 From->getTypeSourceInfo(),
792 From->getStorageClass(),
793 From->getStorageClassAsWritten(),
794 /*DefaultArg=*/0));
795 }
796 Block->setParams(BlockParams);
797
798 Block->setIsConversionFromLambda(true);
799
800 // Add capture. The capture uses a fake variable, which doesn't correspond
801 // to any actual memory location. However, the initializer copy-initializes
802 // the lambda object.
803 TypeSourceInfo *CapVarTSI =
804 Context.getTrivialTypeSourceInfo(Src->getType());
805 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
806 ConvLocation, 0,
807 Src->getType(), CapVarTSI,
808 SC_None, SC_None);
809 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
810 /*Nested=*/false, /*Copy=*/Init.take());
811 Block->setCaptures(Context, &Capture, &Capture + 1,
812 /*CapturesCXXThis=*/false);
813
814 // Add a fake function body to the block. IR generation is responsible
815 // for filling in the actual body, which cannot be expressed as an AST.
816 Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
817 ConvLocation,
818 ConvLocation));
819
820 // Create the block literal expression.
821 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
822 ExprCleanupObjects.push_back(Block);
823 ExprNeedsCleanups = true;
824
825 return BuildBlock;
826}