/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaLambda.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This file implements semantic analysis for C++ lambda expressions. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | #include "clang/Sema/DeclSpec.h" |
13 | | #include "TypeLocBuilder.h" |
14 | | #include "clang/AST/ASTLambda.h" |
15 | | #include "clang/AST/ExprCXX.h" |
16 | | #include "clang/Basic/TargetInfo.h" |
17 | | #include "clang/Sema/Initialization.h" |
18 | | #include "clang/Sema/Lookup.h" |
19 | | #include "clang/Sema/Scope.h" |
20 | | #include "clang/Sema/ScopeInfo.h" |
21 | | #include "clang/Sema/SemaInternal.h" |
22 | | #include "clang/Sema/SemaLambda.h" |
23 | | #include "clang/Sema/Template.h" |
24 | | #include "llvm/ADT/STLExtras.h" |
25 | | #include <optional> |
26 | | using namespace clang; |
27 | | using namespace sema; |
28 | | |
29 | | /// Examines the FunctionScopeInfo stack to determine the nearest |
30 | | /// enclosing lambda (to the current lambda) that is 'capture-ready' for |
31 | | /// the variable referenced in the current lambda (i.e. \p VarToCapture). |
32 | | /// If successful, returns the index into Sema's FunctionScopeInfo stack |
33 | | /// of the capture-ready lambda's LambdaScopeInfo. |
34 | | /// |
35 | | /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current |
36 | | /// lambda - is on top) to determine the index of the nearest enclosing/outer |
37 | | /// lambda that is ready to capture the \p VarToCapture being referenced in |
38 | | /// the current lambda. |
39 | | /// As we climb down the stack, we want the index of the first such lambda - |
40 | | /// that is the lambda with the highest index that is 'capture-ready'. |
41 | | /// |
42 | | /// A lambda 'L' is capture-ready for 'V' (var or this) if: |
43 | | /// - its enclosing context is non-dependent |
44 | | /// - and if the chain of lambdas between L and the lambda in which |
45 | | /// V is potentially used (i.e. the lambda at the top of the scope info |
46 | | /// stack), can all capture or have already captured V. |
47 | | /// If \p VarToCapture is 'null' then we are trying to capture 'this'. |
48 | | /// |
49 | | /// Note that a lambda that is deemed 'capture-ready' still needs to be checked |
50 | | /// for whether it is 'capture-capable' (see |
51 | | /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly |
52 | | /// capture. |
53 | | /// |
54 | | /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a |
55 | | /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda |
56 | | /// is at the top of the stack and has the highest index. |
57 | | /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. |
58 | | /// |
59 | | /// \returns An std::optional<unsigned> Index that if evaluates to 'true' |
60 | | /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost |
61 | | /// lambda which is capture-ready. If the return value evaluates to 'false' |
62 | | /// then no lambda is capture-ready for \p VarToCapture. |
63 | | |
64 | | static inline std::optional<unsigned> |
65 | | getStackIndexOfNearestEnclosingCaptureReadyLambda( |
66 | | ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, |
67 | 1.66k | ValueDecl *VarToCapture) { |
68 | | // Label failure to capture. |
69 | 1.66k | const std::optional<unsigned> NoLambdaIsCaptureReady; |
70 | | |
71 | | // Ignore all inner captured regions. |
72 | 1.66k | unsigned CurScopeIndex = FunctionScopes.size() - 1; |
73 | 1.67k | while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>( |
74 | 1.67k | FunctionScopes[CurScopeIndex])) |
75 | 5 | --CurScopeIndex; |
76 | 1.66k | assert( |
77 | 1.66k | isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && |
78 | 1.66k | "The function on the top of sema's function-info stack must be a lambda"); |
79 | | |
80 | | // If VarToCapture is null, we are attempting to capture 'this'. |
81 | 1.66k | const bool IsCapturingThis = !VarToCapture; |
82 | 1.66k | const bool IsCapturingVariable = !IsCapturingThis; |
83 | | |
84 | | // Start with the current lambda at the top of the stack (highest index). |
85 | 1.66k | DeclContext *EnclosingDC = |
86 | 1.66k | cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator; |
87 | | |
88 | 2.25k | do { |
89 | 2.25k | const clang::sema::LambdaScopeInfo *LSI = |
90 | 2.25k | cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]); |
91 | | // IF we have climbed down to an intervening enclosing lambda that contains |
92 | | // the variable declaration - it obviously can/must not capture the |
93 | | // variable. |
94 | | // Since its enclosing DC is dependent, all the lambdas between it and the |
95 | | // innermost nested lambda are dependent (otherwise we wouldn't have |
96 | | // arrived here) - so we don't yet have a lambda that can capture the |
97 | | // variable. |
98 | 2.25k | if (IsCapturingVariable && |
99 | 2.25k | VarToCapture->getDeclContext()->Equals(EnclosingDC)2.09k ) |
100 | 219 | return NoLambdaIsCaptureReady; |
101 | | |
102 | | // For an enclosing lambda to be capture ready for an entity, all |
103 | | // intervening lambda's have to be able to capture that entity. If even |
104 | | // one of the intervening lambda's is not capable of capturing the entity |
105 | | // then no enclosing lambda can ever capture that entity. |
106 | | // For e.g. |
107 | | // const int x = 10; |
108 | | // [=](auto a) { #1 |
109 | | // [](auto b) { #2 <-- an intervening lambda that can never capture 'x' |
110 | | // [=](auto c) { #3 |
111 | | // f(x, c); <-- can not lead to x's speculative capture by #1 or #2 |
112 | | // }; }; }; |
113 | | // If they do not have a default implicit capture, check to see |
114 | | // if the entity has already been explicitly captured. |
115 | | // If even a single dependent enclosing lambda lacks the capability |
116 | | // to ever capture this variable, there is no further enclosing |
117 | | // non-dependent lambda that can capture this variable. |
118 | 2.03k | if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) { |
119 | 413 | if (IsCapturingVariable && !LSI->isCaptured(VarToCapture)361 ) |
120 | 176 | return NoLambdaIsCaptureReady; |
121 | 237 | if (IsCapturingThis && !LSI->isCXXThisCaptured()52 ) |
122 | 48 | return NoLambdaIsCaptureReady; |
123 | 237 | } |
124 | 1.81k | EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); |
125 | | |
126 | 1.81k | assert(CurScopeIndex); |
127 | 1.81k | --CurScopeIndex; |
128 | 1.81k | } while (!EnclosingDC->isTranslationUnit() && |
129 | 1.81k | EnclosingDC->isDependentContext() && |
130 | 1.81k | isLambdaCallOperator(EnclosingDC)1.37k ); |
131 | | |
132 | 1.22k | assert(CurScopeIndex < (FunctionScopes.size() - 1)); |
133 | | // If the enclosingDC is not dependent, then the immediately nested lambda |
134 | | // (one index above) is capture-ready. |
135 | 1.22k | if (!EnclosingDC->isDependentContext()) |
136 | 444 | return CurScopeIndex + 1; |
137 | 779 | return NoLambdaIsCaptureReady; |
138 | 1.22k | } |
139 | | |
140 | | /// Examines the FunctionScopeInfo stack to determine the nearest |
141 | | /// enclosing lambda (to the current lambda) that is 'capture-capable' for |
142 | | /// the variable referenced in the current lambda (i.e. \p VarToCapture). |
143 | | /// If successful, returns the index into Sema's FunctionScopeInfo stack |
144 | | /// of the capture-capable lambda's LambdaScopeInfo. |
145 | | /// |
146 | | /// Given the current stack of lambdas being processed by Sema and |
147 | | /// the variable of interest, to identify the nearest enclosing lambda (to the |
148 | | /// current lambda at the top of the stack) that can truly capture |
149 | | /// a variable, it has to have the following two properties: |
150 | | /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': |
151 | | /// - climb down the stack (i.e. starting from the innermost and examining |
152 | | /// each outer lambda step by step) checking if each enclosing |
153 | | /// lambda can either implicitly or explicitly capture the variable. |
154 | | /// Record the first such lambda that is enclosed in a non-dependent |
155 | | /// context. If no such lambda currently exists return failure. |
156 | | /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly |
157 | | /// capture the variable by checking all its enclosing lambdas: |
158 | | /// - check if all outer lambdas enclosing the 'capture-ready' lambda |
159 | | /// identified above in 'a' can also capture the variable (this is done |
160 | | /// via tryCaptureVariable for variables and CheckCXXThisCapture for |
161 | | /// 'this' by passing in the index of the Lambda identified in step 'a') |
162 | | /// |
163 | | /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a |
164 | | /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda |
165 | | /// is at the top of the stack. |
166 | | /// |
167 | | /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. |
168 | | /// |
169 | | /// |
170 | | /// \returns An std::optional<unsigned> Index that if evaluates to 'true' |
171 | | /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost |
172 | | /// lambda which is capture-capable. If the return value evaluates to 'false' |
173 | | /// then no lambda is capture-capable for \p VarToCapture. |
174 | | |
175 | | std::optional<unsigned> |
176 | | clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( |
177 | | ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, |
178 | 1.66k | ValueDecl *VarToCapture, Sema &S) { |
179 | | |
180 | 1.66k | const std::optional<unsigned> NoLambdaIsCaptureCapable; |
181 | | |
182 | 1.66k | const std::optional<unsigned> OptionalStackIndex = |
183 | 1.66k | getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, |
184 | 1.66k | VarToCapture); |
185 | 1.66k | if (!OptionalStackIndex) |
186 | 1.22k | return NoLambdaIsCaptureCapable; |
187 | | |
188 | 444 | const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex; |
189 | 444 | assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || |
190 | 444 | S.getCurGenericLambda()) && |
191 | 444 | "The capture ready lambda for a potential capture can only be the " |
192 | 444 | "current lambda if it is a generic lambda"); |
193 | | |
194 | 444 | const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = |
195 | 444 | cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); |
196 | | |
197 | | // If VarToCapture is null, we are attempting to capture 'this' |
198 | 444 | const bool IsCapturingThis = !VarToCapture; |
199 | 444 | const bool IsCapturingVariable = !IsCapturingThis; |
200 | | |
201 | 444 | if (IsCapturingVariable) { |
202 | | // Check if the capture-ready lambda can truly capture the variable, by |
203 | | // checking whether all enclosing lambdas of the capture-ready lambda allow |
204 | | // the capture - i.e. make sure it is capture-capable. |
205 | 424 | QualType CaptureType, DeclRefType; |
206 | 424 | const bool CanCaptureVariable = |
207 | 424 | !S.tryCaptureVariable(VarToCapture, |
208 | 424 | /*ExprVarIsUsedInLoc*/ SourceLocation(), |
209 | 424 | clang::Sema::TryCapture_Implicit, |
210 | 424 | /*EllipsisLoc*/ SourceLocation(), |
211 | 424 | /*BuildAndDiagnose*/ false, CaptureType, |
212 | 424 | DeclRefType, &IndexOfCaptureReadyLambda); |
213 | 424 | if (!CanCaptureVariable) |
214 | 28 | return NoLambdaIsCaptureCapable; |
215 | 424 | } else { |
216 | | // Check if the capture-ready lambda can truly capture 'this' by checking |
217 | | // whether all enclosing lambdas of the capture-ready lambda can capture |
218 | | // 'this'. |
219 | 20 | const bool CanCaptureThis = |
220 | 20 | !S.CheckCXXThisCapture( |
221 | 20 | CaptureReadyLambdaLSI->PotentialThisCaptureLocation, |
222 | 20 | /*Explicit*/ false, /*BuildAndDiagnose*/ false, |
223 | 20 | &IndexOfCaptureReadyLambda); |
224 | 20 | if (!CanCaptureThis) |
225 | 4 | return NoLambdaIsCaptureCapable; |
226 | 20 | } |
227 | 412 | return IndexOfCaptureReadyLambda; |
228 | 444 | } |
229 | | |
230 | | static inline TemplateParameterList * |
231 | 32.5k | getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { |
232 | 32.5k | if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()25.6k ) { |
233 | 2.71k | LSI->GLTemplateParameterList = TemplateParameterList::Create( |
234 | 2.71k | SemaRef.Context, |
235 | 2.71k | /*Template kw loc*/ SourceLocation(), |
236 | 2.71k | /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(), |
237 | 2.71k | LSI->TemplateParams, |
238 | 2.71k | /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(), |
239 | 2.71k | LSI->RequiresClause.get()); |
240 | 2.71k | } |
241 | 32.5k | return LSI->GLTemplateParameterList; |
242 | 32.5k | } |
243 | | |
244 | | CXXRecordDecl * |
245 | | Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, |
246 | | unsigned LambdaDependencyKind, |
247 | 12.7k | LambdaCaptureDefault CaptureDefault) { |
248 | 12.7k | DeclContext *DC = CurContext; |
249 | 12.7k | while (!(DC->isFunctionOrMethod() || DC->isRecord()2.12k || DC->isFileContext()1.54k )) |
250 | 66 | DC = DC->getParent(); |
251 | | |
252 | 12.7k | bool IsGenericLambda = |
253 | 12.7k | Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this)0 ; |
254 | | // Start constructing the lambda class. |
255 | 12.7k | CXXRecordDecl *Class = CXXRecordDecl::CreateLambda( |
256 | 12.7k | Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind, |
257 | 12.7k | IsGenericLambda, CaptureDefault); |
258 | 12.7k | DC->addDecl(Class); |
259 | | |
260 | 12.7k | return Class; |
261 | 12.7k | } |
262 | | |
263 | | /// Determine whether the given context is or is enclosed in an inline |
264 | | /// function. |
265 | 1.25M | static bool isInInlineFunction(const DeclContext *DC) { |
266 | 1.72M | while (!DC->isFileContext()) { |
267 | 472k | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) |
268 | 28.0k | if (FD->isInlined()) |
269 | 11.5k | return true; |
270 | | |
271 | 461k | DC = DC->getLexicalParent(); |
272 | 461k | } |
273 | | |
274 | 1.24M | return false; |
275 | 1.25M | } |
276 | | |
277 | | std::tuple<MangleNumberingContext *, Decl *> |
278 | 1.28M | Sema::getCurrentMangleNumberContext(const DeclContext *DC) { |
279 | | // Compute the context for allocating mangling numbers in the current |
280 | | // expression, if the ABI requires them. |
281 | 1.28M | Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
282 | | |
283 | 1.28M | enum ContextKind { |
284 | 1.28M | Normal, |
285 | 1.28M | DefaultArgument, |
286 | 1.28M | DataMember, |
287 | 1.28M | InlineVariable, |
288 | 1.28M | TemplatedVariable, |
289 | 1.28M | Concept |
290 | 1.28M | } Kind = Normal; |
291 | | |
292 | 1.28M | bool IsInNonspecializedTemplate = |
293 | 1.28M | inTemplateInstantiation() || CurContext->isDependentContext()1.28M ; |
294 | | |
295 | | // Default arguments of member function parameters that appear in a class |
296 | | // definition, as well as the initializers of data members, receive special |
297 | | // treatment. Identify them. |
298 | 1.28M | if (ManglingContextDecl) { |
299 | 3.09k | if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { |
300 | 895 | if (const DeclContext *LexicalDC |
301 | 895 | = Param->getDeclContext()->getLexicalParent()) |
302 | 244 | if (LexicalDC->isRecord()) |
303 | 180 | Kind = DefaultArgument; |
304 | 2.19k | } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) { |
305 | 1.94k | if (Var->getMostRecentDecl()->isInline()) |
306 | 59 | Kind = InlineVariable; |
307 | 1.88k | else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate21 ) |
308 | 19 | Kind = TemplatedVariable; |
309 | 1.86k | else if (Var->getDescribedVarTemplate()) |
310 | 36 | Kind = TemplatedVariable; |
311 | 1.83k | else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) { |
312 | 27 | if (!VTS->isExplicitSpecialization()) |
313 | 27 | Kind = TemplatedVariable; |
314 | 27 | } |
315 | 1.94k | } else if (251 isa<FieldDecl>(ManglingContextDecl)251 ) { |
316 | 236 | Kind = DataMember; |
317 | 236 | } else if (15 isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)15 ) { |
318 | 15 | Kind = Concept; |
319 | 15 | } |
320 | 3.09k | } |
321 | | |
322 | | // Itanium ABI [5.1.7]: |
323 | | // In the following contexts [...] the one-definition rule requires closure |
324 | | // types in different translation units to "correspond": |
325 | 1.28M | switch (Kind) { |
326 | 1.28M | case Normal: { |
327 | | // -- the bodies of inline or templated functions |
328 | 1.28M | if ((IsInNonspecializedTemplate && |
329 | 1.28M | !(25.9k ManglingContextDecl25.9k && isa<ParmVarDecl>(ManglingContextDecl)1.01k )) || |
330 | 1.28M | isInInlineFunction(CurContext)1.25M ) { |
331 | 39.7k | while (auto *CD = dyn_cast<CapturedDecl>(DC)) |
332 | 2.25k | DC = CD->getParent(); |
333 | 37.5k | return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr); |
334 | 37.5k | } |
335 | | |
336 | 1.24M | return std::make_tuple(nullptr, nullptr); |
337 | 1.28M | } |
338 | | |
339 | 15 | case Concept: |
340 | | // Concept definitions aren't code generated and thus aren't mangled, |
341 | | // however the ManglingContextDecl is important for the purposes of |
342 | | // re-forming the template argument list of the lambda for constraint |
343 | | // evaluation. |
344 | 251 | case DataMember: |
345 | | // -- default member initializers |
346 | 431 | case DefaultArgument: |
347 | | // -- default arguments appearing in class definitions |
348 | 490 | case InlineVariable: |
349 | 572 | case TemplatedVariable: |
350 | | // -- the initializers of inline or templated variables |
351 | 572 | return std::make_tuple( |
352 | 572 | &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl, |
353 | 572 | ManglingContextDecl), |
354 | 572 | ManglingContextDecl); |
355 | 1.28M | } |
356 | | |
357 | 0 | llvm_unreachable("unexpected context"); |
358 | 0 | } |
359 | | |
360 | | static QualType |
361 | | buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, |
362 | | TemplateParameterList *TemplateParams, |
363 | 12.7k | TypeSourceInfo *MethodTypeInfo) { |
364 | 12.7k | assert(MethodTypeInfo && "expected a non null type"); |
365 | | |
366 | 12.7k | QualType MethodType = MethodTypeInfo->getType(); |
367 | | // If a lambda appears in a dependent context or is a generic lambda (has |
368 | | // template parameters) and has an 'auto' return type, deduce it to a |
369 | | // dependent type. |
370 | 12.7k | if (Class->isDependentContext() || TemplateParams9.45k ) { |
371 | 5.74k | const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); |
372 | 5.74k | QualType Result = FPT->getReturnType(); |
373 | 5.74k | if (Result->isUndeducedType()) { |
374 | 4.10k | Result = S.SubstAutoTypeDependent(Result); |
375 | 4.10k | MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(), |
376 | 4.10k | FPT->getExtProtoInfo()); |
377 | 4.10k | } |
378 | 5.74k | } |
379 | 12.7k | return MethodType; |
380 | 12.7k | } |
381 | | |
382 | | // [C++2b] [expr.prim.lambda.closure] p4 |
383 | | // Given a lambda with a lambda-capture, the type of the explicit object |
384 | | // parameter, if any, of the lambda's function call operator (possibly |
385 | | // instantiated from a function call operator template) shall be either: |
386 | | // - the closure type, |
387 | | // - class type derived from the closure type, or |
388 | | // - a reference to a possibly cv-qualified such type. |
389 | | void Sema::DiagnoseInvalidExplicitObjectParameterInLambda( |
390 | 26 | CXXMethodDecl *Method) { |
391 | 26 | if (!isLambdaCallWithExplicitObjectParameter(Method)) |
392 | 6 | return; |
393 | 20 | CXXRecordDecl *RD = Method->getParent(); |
394 | 20 | if (Method->getType()->isDependentType()) |
395 | 0 | return; |
396 | 20 | if (RD->isCapturelessLambda()) |
397 | 4 | return; |
398 | 16 | QualType ExplicitObjectParameterType = Method->getParamDecl(0) |
399 | 16 | ->getType() |
400 | 16 | .getNonReferenceType() |
401 | 16 | .getUnqualifiedType() |
402 | 16 | .getDesugaredType(getASTContext()); |
403 | 16 | QualType LambdaType = getASTContext().getRecordType(RD); |
404 | 16 | if (LambdaType == ExplicitObjectParameterType) |
405 | 10 | return; |
406 | 6 | if (IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType)) |
407 | 2 | return; |
408 | 4 | Diag(Method->getParamDecl(0)->getLocation(), |
409 | 4 | diag::err_invalid_explicit_object_type_in_lambda) |
410 | 4 | << ExplicitObjectParameterType; |
411 | 4 | } |
412 | | |
413 | | void Sema::handleLambdaNumbering( |
414 | | CXXRecordDecl *Class, CXXMethodDecl *Method, |
415 | 12.7k | std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) { |
416 | 12.7k | if (NumberingOverride) { |
417 | 7 | Class->setLambdaNumbering(*NumberingOverride); |
418 | 7 | return; |
419 | 7 | } |
420 | | |
421 | 12.6k | ContextRAII ManglingContext(*this, Class->getDeclContext()); |
422 | | |
423 | 12.6k | auto getMangleNumberingContext = |
424 | 12.6k | [this](CXXRecordDecl *Class, |
425 | 12.6k | Decl *ManglingContextDecl) -> MangleNumberingContext * { |
426 | | // Get mangle numbering context if there's any extra decl context. |
427 | 267 | if (ManglingContextDecl) |
428 | 0 | return &Context.getManglingNumberContext( |
429 | 0 | ASTContext::NeedExtraManglingDecl, ManglingContextDecl); |
430 | | // Otherwise, from that lambda's decl context. |
431 | 267 | auto DC = Class->getDeclContext(); |
432 | 267 | while (auto *CD = dyn_cast<CapturedDecl>(DC)) |
433 | 0 | DC = CD->getParent(); |
434 | 267 | return &Context.getManglingNumberContext(DC); |
435 | 267 | }; |
436 | | |
437 | 12.6k | CXXRecordDecl::LambdaNumbering Numbering; |
438 | 12.6k | MangleNumberingContext *MCtx; |
439 | 12.6k | std::tie(MCtx, Numbering.ContextDecl) = |
440 | 12.6k | getCurrentMangleNumberContext(Class->getDeclContext()); |
441 | 12.6k | if (!MCtx && (5.40k getLangOpts().CUDA5.40k || getLangOpts().SYCLIsDevice5.20k || |
442 | 5.40k | getLangOpts().SYCLIsHost5.13k )) { |
443 | | // Force lambda numbering in CUDA/HIP as we need to name lambdas following |
444 | | // ODR. Both device- and host-compilation need to have a consistent naming |
445 | | // on kernel functions. As lambdas are potential part of these `__global__` |
446 | | // function names, they needs numbering following ODR. |
447 | | // Also force for SYCL, since we need this for the |
448 | | // __builtin_sycl_unique_stable_name implementation, which depends on lambda |
449 | | // mangling. |
450 | 267 | MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl); |
451 | 267 | assert(MCtx && "Retrieving mangle numbering context failed!"); |
452 | 267 | Numbering.HasKnownInternalLinkage = true; |
453 | 267 | } |
454 | 12.6k | if (MCtx) { |
455 | 7.56k | Numbering.IndexInContext = MCtx->getNextLambdaIndex(); |
456 | 7.56k | Numbering.ManglingNumber = MCtx->getManglingNumber(Method); |
457 | 7.56k | Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method); |
458 | 7.56k | Class->setLambdaNumbering(Numbering); |
459 | | |
460 | 7.56k | if (auto *Source = |
461 | 7.56k | dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) |
462 | 1.85k | Source->AssignedLambdaNumbering(Class); |
463 | 7.56k | } |
464 | 12.6k | } |
465 | | |
466 | | static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, |
467 | | CXXMethodDecl *CallOperator, |
468 | 12.7k | bool ExplicitResultType) { |
469 | 12.7k | if (ExplicitResultType) { |
470 | 2.09k | LSI->HasImplicitReturnType = false; |
471 | 2.09k | LSI->ReturnType = CallOperator->getReturnType(); |
472 | 2.09k | if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType()1.55k ) |
473 | 1.07k | S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType, |
474 | 1.07k | diag::err_lambda_incomplete_result); |
475 | 10.6k | } else { |
476 | 10.6k | LSI->HasImplicitReturnType = true; |
477 | 10.6k | } |
478 | 12.7k | } |
479 | | |
480 | | void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, |
481 | | SourceRange IntroducerRange, |
482 | | LambdaCaptureDefault CaptureDefault, |
483 | | SourceLocation CaptureDefaultLoc, |
484 | 2.80k | bool ExplicitParams, bool Mutable) { |
485 | 2.80k | LSI->CallOperator = CallOperator; |
486 | 2.80k | CXXRecordDecl *LambdaClass = CallOperator->getParent(); |
487 | 2.80k | LSI->Lambda = LambdaClass; |
488 | 2.80k | if (CaptureDefault == LCD_ByCopy) |
489 | 397 | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; |
490 | 2.41k | else if (CaptureDefault == LCD_ByRef) |
491 | 181 | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; |
492 | 2.80k | LSI->CaptureDefaultLoc = CaptureDefaultLoc; |
493 | 2.80k | LSI->IntroducerRange = IntroducerRange; |
494 | 2.80k | LSI->ExplicitParams = ExplicitParams; |
495 | 2.80k | LSI->Mutable = Mutable; |
496 | 2.80k | } |
497 | | |
498 | 12.7k | void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { |
499 | 12.7k | LSI->finishedExplicitCaptures(); |
500 | 12.7k | } |
501 | | |
502 | | void Sema::ActOnLambdaExplicitTemplateParameterList( |
503 | | LambdaIntroducer &Intro, SourceLocation LAngleLoc, |
504 | | ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, |
505 | 241 | ExprResult RequiresClause) { |
506 | 241 | LambdaScopeInfo *LSI = getCurLambda(); |
507 | 241 | assert(LSI && "Expected a lambda scope"); |
508 | 241 | assert(LSI->NumExplicitTemplateParams == 0 && |
509 | 241 | "Already acted on explicit template parameters"); |
510 | 241 | assert(LSI->TemplateParams.empty() && |
511 | 241 | "Explicit template parameters should come " |
512 | 241 | "before invented (auto) ones"); |
513 | 241 | assert(!TParams.empty() && |
514 | 241 | "No template parameters to act on"); |
515 | 241 | LSI->TemplateParams.append(TParams.begin(), TParams.end()); |
516 | 241 | LSI->NumExplicitTemplateParams = TParams.size(); |
517 | 241 | LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc}; |
518 | 241 | LSI->RequiresClause = RequiresClause; |
519 | 241 | } |
520 | | |
521 | | /// If this expression is an enumerator-like expression of some type |
522 | | /// T, return the type T; otherwise, return null. |
523 | | /// |
524 | | /// Pointer comparisons on the result here should always work because |
525 | | /// it's derived from either the parent of an EnumConstantDecl |
526 | | /// (i.e. the definition) or the declaration returned by |
527 | | /// EnumType::getDecl() (i.e. the definition). |
528 | 530 | static EnumDecl *findEnumForBlockReturn(Expr *E) { |
529 | | // An expression is an enumerator-like expression of type T if, |
530 | | // ignoring parens and parens-like expressions: |
531 | 530 | E = E->IgnoreParens(); |
532 | | |
533 | | // - it is an enumerator whose enum type is T or |
534 | 530 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { |
535 | 28 | if (EnumConstantDecl *D |
536 | 28 | = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { |
537 | 28 | return cast<EnumDecl>(D->getDeclContext()); |
538 | 28 | } |
539 | 0 | return nullptr; |
540 | 28 | } |
541 | | |
542 | | // - it is a comma expression whose RHS is an enumerator-like |
543 | | // expression of type T or |
544 | 502 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { |
545 | 25 | if (BO->getOpcode() == BO_Comma) |
546 | 1 | return findEnumForBlockReturn(BO->getRHS()); |
547 | 24 | return nullptr; |
548 | 25 | } |
549 | | |
550 | | // - it is a statement-expression whose value expression is an |
551 | | // enumerator-like expression of type T or |
552 | 477 | if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) { |
553 | 1 | if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) |
554 | 1 | return findEnumForBlockReturn(last); |
555 | 0 | return nullptr; |
556 | 1 | } |
557 | | |
558 | | // - it is a ternary conditional operator (not the GNU ?: |
559 | | // extension) whose second and third operands are |
560 | | // enumerator-like expressions of type T or |
561 | 476 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { |
562 | 3 | if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) |
563 | 3 | if (ED == findEnumForBlockReturn(CO->getFalseExpr())) |
564 | 3 | return ED; |
565 | 0 | return nullptr; |
566 | 3 | } |
567 | | |
568 | | // (implicitly:) |
569 | | // - it is an implicit integral conversion applied to an |
570 | | // enumerator-like expression of type T or |
571 | 473 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { |
572 | | // We can sometimes see integral conversions in valid |
573 | | // enumerator-like expressions. |
574 | 149 | if (ICE->getCastKind() == CK_IntegralCast) |
575 | 3 | return findEnumForBlockReturn(ICE->getSubExpr()); |
576 | | |
577 | | // Otherwise, just rely on the type. |
578 | 149 | } |
579 | | |
580 | | // - it is an expression of that formal enum type. |
581 | 470 | if (const EnumType *ET = E->getType()->getAs<EnumType>()) { |
582 | 15 | return ET->getDecl(); |
583 | 15 | } |
584 | | |
585 | | // Otherwise, nope. |
586 | 455 | return nullptr; |
587 | 470 | } |
588 | | |
589 | | /// Attempt to find a type T for which the returned expression of the |
590 | | /// given statement is an enumerator-like expression of that type. |
591 | 746 | static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { |
592 | 746 | if (Expr *retValue = ret->getRetValue()) |
593 | 519 | return findEnumForBlockReturn(retValue); |
594 | 227 | return nullptr; |
595 | 746 | } |
596 | | |
597 | | /// Attempt to find a common type T for which all of the returned |
598 | | /// expressions in a block are enumerator-like expressions of that |
599 | | /// type. |
600 | 731 | static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { |
601 | 731 | ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); |
602 | | |
603 | | // Try to find one for the first return. |
604 | 731 | EnumDecl *ED = findEnumForBlockReturn(*i); |
605 | 731 | if (!ED) return nullptr704 ; |
606 | | |
607 | | // Check that the rest of the returns have the same enum. |
608 | 40 | for (++i; 27 i != e; ++i13 ) { |
609 | 15 | if (findEnumForBlockReturn(*i) != ED) |
610 | 2 | return nullptr; |
611 | 15 | } |
612 | | |
613 | | // Never infer an anonymous enum type. |
614 | 25 | if (!ED->hasNameForLinkage()) return nullptr3 ; |
615 | | |
616 | 22 | return ED; |
617 | 25 | } |
618 | | |
619 | | /// Adjust the given return statements so that they formally return |
620 | | /// the given type. It should require, at most, an IntegralCast. |
621 | | static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, |
622 | 22 | QualType returnType) { |
623 | 22 | for (ArrayRef<ReturnStmt*>::iterator |
624 | 57 | i = returns.begin(), e = returns.end(); i != e; ++i35 ) { |
625 | 35 | ReturnStmt *ret = *i; |
626 | 35 | Expr *retValue = ret->getRetValue(); |
627 | 35 | if (S.Context.hasSameType(retValue->getType(), returnType)) |
628 | 14 | continue; |
629 | | |
630 | | // Right now we only support integral fixup casts. |
631 | 21 | assert(returnType->isIntegralOrUnscopedEnumerationType()); |
632 | 21 | assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); |
633 | | |
634 | 21 | ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); |
635 | | |
636 | 21 | Expr *E = (cleanups ? cleanups->getSubExpr()0 : retValue); |
637 | 21 | E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E, |
638 | 21 | /*base path*/ nullptr, VK_PRValue, |
639 | 21 | FPOptionsOverride()); |
640 | 21 | if (cleanups) { |
641 | 0 | cleanups->setSubExpr(E); |
642 | 21 | } else { |
643 | 21 | ret->setRetValue(E); |
644 | 21 | } |
645 | 21 | } |
646 | 22 | } |
647 | | |
648 | 5.82k | void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { |
649 | 5.82k | assert(CSI.HasImplicitReturnType); |
650 | | // If it was ever a placeholder, it had to been deduced to DependentTy. |
651 | 5.82k | assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); |
652 | 5.82k | assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && |
653 | 5.82k | "lambda expressions use auto deduction in C++14 onwards"); |
654 | | |
655 | | // C++ core issue 975: |
656 | | // If a lambda-expression does not include a trailing-return-type, |
657 | | // it is as if the trailing-return-type denotes the following type: |
658 | | // - if there are no return statements in the compound-statement, |
659 | | // or all return statements return either an expression of type |
660 | | // void or no expression or braced-init-list, the type void; |
661 | | // - otherwise, if all return statements return an expression |
662 | | // and the types of the returned expressions after |
663 | | // lvalue-to-rvalue conversion (4.1 [conv.lval]), |
664 | | // array-to-pointer conversion (4.2 [conv.array]), and |
665 | | // function-to-pointer conversion (4.3 [conv.func]) are the |
666 | | // same, that common type; |
667 | | // - otherwise, the program is ill-formed. |
668 | | // |
669 | | // C++ core issue 1048 additionally removes top-level cv-qualifiers |
670 | | // from the types of returned expressions to match the C++14 auto |
671 | | // deduction rules. |
672 | | // |
673 | | // In addition, in blocks in non-C++ modes, if all of the return |
674 | | // statements are enumerator-like expressions of some type T, where |
675 | | // T has a name for linkage, then we infer the return type of the |
676 | | // block to be that type. |
677 | | |
678 | | // First case: no return statements, implicit void return type. |
679 | 5.82k | ASTContext &Ctx = getASTContext(); |
680 | 5.82k | if (CSI.Returns.empty()) { |
681 | | // It's possible there were simply no /valid/ return statements. |
682 | | // In this case, the first one we found may have at least given us a type. |
683 | 4.50k | if (CSI.ReturnType.isNull()) |
684 | 4.50k | CSI.ReturnType = Ctx.VoidTy; |
685 | 4.50k | return; |
686 | 4.50k | } |
687 | | |
688 | | // Second case: at least one return statement has dependent type. |
689 | | // Delay type checking until instantiation. |
690 | 1.31k | assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); |
691 | 1.31k | if (CSI.ReturnType->isDependentType()) |
692 | 56 | return; |
693 | | |
694 | | // Try to apply the enum-fuzz rule. |
695 | 1.26k | if (!getLangOpts().CPlusPlus) { |
696 | 731 | assert(isa<BlockScopeInfo>(CSI)); |
697 | 731 | const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); |
698 | 731 | if (ED) { |
699 | 22 | CSI.ReturnType = Context.getTypeDeclType(ED); |
700 | 22 | adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); |
701 | 22 | return; |
702 | 22 | } |
703 | 731 | } |
704 | | |
705 | | // Third case: only one return statement. Don't bother doing extra work! |
706 | 1.24k | if (CSI.Returns.size() == 1) |
707 | 1.19k | return; |
708 | | |
709 | | // General case: many return statements. |
710 | | // Check that they all have compatible return types. |
711 | | |
712 | | // We require the return types to strictly match here. |
713 | | // Note that we've already done the required promotions as part of |
714 | | // processing the return statement. |
715 | 117 | for (const ReturnStmt *RS : CSI.Returns)45 { |
716 | 117 | const Expr *RetE = RS->getRetValue(); |
717 | | |
718 | 117 | QualType ReturnType = |
719 | 117 | (RetE ? RetE->getType()112 : Context.VoidTy5 ).getUnqualifiedType(); |
720 | 117 | if (Context.getCanonicalFunctionResultType(ReturnType) == |
721 | 117 | Context.getCanonicalFunctionResultType(CSI.ReturnType)) { |
722 | | // Use the return type with the strictest possible nullability annotation. |
723 | 108 | auto RetTyNullability = ReturnType->getNullability(); |
724 | 108 | auto BlockNullability = CSI.ReturnType->getNullability(); |
725 | 108 | if (BlockNullability && |
726 | 108 | (4 !RetTyNullability4 || |
727 | 4 | hasWeakerNullability(*RetTyNullability, *BlockNullability)2 )) |
728 | 2 | CSI.ReturnType = ReturnType; |
729 | 108 | continue; |
730 | 108 | } |
731 | | |
732 | | // FIXME: This is a poor diagnostic for ReturnStmts without expressions. |
733 | | // TODO: It's possible that the *first* return is the divergent one. |
734 | 9 | Diag(RS->getBeginLoc(), |
735 | 9 | diag::err_typecheck_missing_return_type_incompatible) |
736 | 9 | << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI); |
737 | | // Continue iterating so that we keep emitting diagnostics. |
738 | 9 | } |
739 | 45 | } |
740 | | |
741 | | QualType Sema::buildLambdaInitCaptureInitialization( |
742 | | SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, |
743 | | std::optional<unsigned> NumExpansions, IdentifierInfo *Id, |
744 | 723 | bool IsDirectInit, Expr *&Init) { |
745 | | // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to |
746 | | // deduce against. |
747 | 723 | QualType DeductType = Context.getAutoDeductType(); |
748 | 723 | TypeLocBuilder TLB; |
749 | 723 | AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType); |
750 | 723 | TL.setNameLoc(Loc); |
751 | 723 | if (ByRef) { |
752 | 132 | DeductType = BuildReferenceType(DeductType, true, Loc, Id); |
753 | 132 | assert(!DeductType.isNull() && "can't build reference to auto"); |
754 | 132 | TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); |
755 | 132 | } |
756 | 723 | if (EllipsisLoc.isValid()) { |
757 | 73 | if (Init->containsUnexpandedParameterPack()) { |
758 | 72 | Diag(EllipsisLoc, getLangOpts().CPlusPlus20 |
759 | 72 | ? diag::warn_cxx17_compat_init_capture_pack41 |
760 | 72 | : diag::ext_init_capture_pack31 ); |
761 | 72 | DeductType = Context.getPackExpansionType(DeductType, NumExpansions, |
762 | 72 | /*ExpectPackInType=*/false); |
763 | 72 | TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc); |
764 | 72 | } else { |
765 | | // Just ignore the ellipsis for now and form a non-pack variable. We'll |
766 | | // diagnose this later when we try to capture it. |
767 | 1 | } |
768 | 73 | } |
769 | 723 | TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); |
770 | | |
771 | | // Deduce the type of the init capture. |
772 | 723 | QualType DeducedType = deduceVarTypeFromInitializer( |
773 | 723 | /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI, |
774 | 723 | SourceRange(Loc, Loc), IsDirectInit, Init); |
775 | 723 | if (DeducedType.isNull()) |
776 | 37 | return QualType(); |
777 | | |
778 | | // Are we a non-list direct initialization? |
779 | 686 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); |
780 | | |
781 | | // Perform initialization analysis and ensure any implicit conversions |
782 | | // (such as lvalue-to-rvalue) are enforced. |
783 | 686 | InitializedEntity Entity = |
784 | 686 | InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); |
785 | 686 | InitializationKind Kind = |
786 | 686 | IsDirectInit |
787 | 686 | ? (160 CXXDirectInit160 ? InitializationKind::CreateDirect( |
788 | 140 | Loc, Init->getBeginLoc(), Init->getEndLoc()) |
789 | 160 | : InitializationKind::CreateDirectList(Loc)20 ) |
790 | 686 | : InitializationKind::CreateCopy(Loc, Init->getBeginLoc())526 ; |
791 | | |
792 | 686 | MultiExprArg Args = Init; |
793 | 686 | if (CXXDirectInit) |
794 | 140 | Args = |
795 | 140 | MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); |
796 | 686 | QualType DclT; |
797 | 686 | InitializationSequence InitSeq(*this, Entity, Kind, Args); |
798 | 686 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); |
799 | | |
800 | 686 | if (Result.isInvalid()) |
801 | 5 | return QualType(); |
802 | | |
803 | 681 | Init = Result.getAs<Expr>(); |
804 | 681 | return DeducedType; |
805 | 686 | } |
806 | | |
807 | | VarDecl *Sema::createLambdaInitCaptureVarDecl( |
808 | | SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, |
809 | 679 | IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) { |
810 | | // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization |
811 | | // rather than reconstructing it here. |
812 | 679 | TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc); |
813 | 679 | if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) |
814 | 70 | PETL.setEllipsisLoc(EllipsisLoc); |
815 | | |
816 | | // Create a dummy variable representing the init-capture. This is not actually |
817 | | // used as a variable, and only exists as a way to name and refer to the |
818 | | // init-capture. |
819 | | // FIXME: Pass in separate source locations for '&' and identifier. |
820 | 679 | VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id, |
821 | 679 | InitCaptureType, TSI, SC_Auto); |
822 | 679 | NewVD->setInitCapture(true); |
823 | 679 | NewVD->setReferenced(true); |
824 | | // FIXME: Pass in a VarDecl::InitializationStyle. |
825 | 679 | NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle)); |
826 | 679 | NewVD->markUsed(Context); |
827 | 679 | NewVD->setInit(Init); |
828 | 679 | if (NewVD->isParameterPack()) |
829 | 70 | getCurLambda()->LocalPacks.push_back(NewVD); |
830 | 679 | return NewVD; |
831 | 679 | } |
832 | | |
833 | 677 | void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) { |
834 | 677 | assert(Var->isInitCapture() && "init capture flag should be set"); |
835 | 677 | LSI->addCapture(Var, /*isBlock=*/false, ByRef, |
836 | 677 | /*isNested=*/false, Var->getLocation(), SourceLocation(), |
837 | 677 | Var->getType(), /*Invalid=*/false); |
838 | 677 | } |
839 | | |
840 | | // Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't |
841 | | // check that the current lambda is in a consistent or fully constructed state. |
842 | 42.5k | static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) { |
843 | 42.5k | assert(!S.FunctionScopes.empty()); |
844 | 42.5k | return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]); |
845 | 42.5k | } |
846 | | |
847 | | static TypeSourceInfo * |
848 | 2.13k | getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) { |
849 | | // C++11 [expr.prim.lambda]p4: |
850 | | // If a lambda-expression does not include a lambda-declarator, it is as |
851 | | // if the lambda-declarator were (). |
852 | 2.13k | FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention( |
853 | 2.13k | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
854 | 2.13k | EPI.HasTrailingReturn = true; |
855 | 2.13k | EPI.TypeQuals.addConst(); |
856 | 2.13k | LangAS AS = S.getDefaultCXXMethodAddrSpace(); |
857 | 2.13k | if (AS != LangAS::Default) |
858 | 2 | EPI.TypeQuals.addAddressSpace(AS); |
859 | | |
860 | | // C++1y [expr.prim.lambda]: |
861 | | // The lambda return type is 'auto', which is replaced by the |
862 | | // trailing-return type if provided and/or deduced from 'return' |
863 | | // statements |
864 | | // We don't do this before C++1y, because we don't support deduced return |
865 | | // types there. |
866 | 2.13k | QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14 |
867 | 2.13k | ? S.Context.getAutoDeductType()1.55k |
868 | 2.13k | : S.Context.DependentTy581 ; |
869 | 2.13k | QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, |
870 | 2.13k | std::nullopt, EPI); |
871 | 2.13k | return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc); |
872 | 2.13k | } |
873 | | |
874 | | static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro, |
875 | | Declarator &ParamInfo, Scope *CurScope, |
876 | | SourceLocation Loc, |
877 | 9.90k | bool &ExplicitResultType) { |
878 | | |
879 | 9.90k | ExplicitResultType = false; |
880 | | |
881 | 9.90k | assert( |
882 | 9.90k | (ParamInfo.getDeclSpec().getStorageClassSpec() == |
883 | 9.90k | DeclSpec::SCS_unspecified || |
884 | 9.90k | ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) && |
885 | 9.90k | "Unexpected storage specifier"); |
886 | 9.90k | bool IsLambdaStatic = |
887 | 9.90k | ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static; |
888 | | |
889 | 9.90k | TypeSourceInfo *MethodTyInfo; |
890 | | |
891 | 9.90k | if (ParamInfo.getNumTypeObjects() == 0) { |
892 | 2.13k | MethodTyInfo = getDummyLambdaType(S, Loc); |
893 | 7.76k | } else { |
894 | | // Check explicit parameters |
895 | 7.76k | S.CheckExplicitObjectLambda(ParamInfo); |
896 | | |
897 | 7.76k | DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); |
898 | | |
899 | 7.76k | bool HasExplicitObjectParameter = |
900 | 7.76k | ParamInfo.isExplicitObjectMemberFunction(); |
901 | | |
902 | 7.76k | ExplicitResultType = FTI.hasTrailingReturnType(); |
903 | 7.76k | if (!FTI.hasMutableQualifier() && !IsLambdaStatic7.53k && |
904 | 7.76k | !HasExplicitObjectParameter7.48k ) |
905 | 7.46k | FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const, Loc); |
906 | | |
907 | 7.76k | if (ExplicitResultType && S.getLangOpts().HLSL1.25k ) { |
908 | 3 | QualType RetTy = FTI.getTrailingReturnType().get(); |
909 | 3 | if (!RetTy.isNull()) { |
910 | | // HLSL does not support specifying an address space on a lambda return |
911 | | // type. |
912 | 2 | LangAS AddressSpace = RetTy.getAddressSpace(); |
913 | 2 | if (AddressSpace != LangAS::Default) |
914 | 2 | S.Diag(FTI.getTrailingReturnTypeLoc(), |
915 | 2 | diag::err_return_value_with_address_space); |
916 | 2 | } |
917 | 3 | } |
918 | | |
919 | 7.76k | MethodTyInfo = S.GetTypeForDeclarator(ParamInfo, CurScope); |
920 | 7.76k | assert(MethodTyInfo && "no type from lambda-declarator"); |
921 | | |
922 | | // Check for unexpanded parameter packs in the method type. |
923 | 7.76k | if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) |
924 | 50 | S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo, |
925 | 50 | S.UPPC_DeclarationType); |
926 | 7.76k | } |
927 | 9.90k | return MethodTyInfo; |
928 | 9.90k | } |
929 | | |
930 | | CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange, |
931 | 12.7k | CXXRecordDecl *Class) { |
932 | | |
933 | | // C++20 [expr.prim.lambda.closure]p3: |
934 | | // The closure type for a lambda-expression has a public inline function |
935 | | // call operator (for a non-generic lambda) or function call operator |
936 | | // template (for a generic lambda) whose parameters and return type are |
937 | | // described by the lambda-expression's parameter-declaration-clause |
938 | | // and trailing-return-type respectively. |
939 | 12.7k | DeclarationName MethodName = |
940 | 12.7k | Context.DeclarationNames.getCXXOperatorName(OO_Call); |
941 | 12.7k | DeclarationNameLoc MethodNameLoc = |
942 | 12.7k | DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange.getBegin()); |
943 | 12.7k | CXXMethodDecl *Method = CXXMethodDecl::Create( |
944 | 12.7k | Context, Class, SourceLocation(), |
945 | 12.7k | DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), |
946 | 12.7k | MethodNameLoc), |
947 | 12.7k | QualType(), /*Tinfo=*/nullptr, SC_None, |
948 | 12.7k | getCurFPFeatures().isFPConstrained(), |
949 | 12.7k | /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(), |
950 | 12.7k | /*TrailingRequiresClause=*/nullptr); |
951 | 12.7k | Method->setAccess(AS_public); |
952 | 12.7k | return Method; |
953 | 12.7k | } |
954 | | |
955 | | void Sema::AddTemplateParametersToLambdaCallOperator( |
956 | | CXXMethodDecl *CallOperator, CXXRecordDecl *Class, |
957 | 4.17k | TemplateParameterList *TemplateParams) { |
958 | 4.17k | assert(TemplateParams && "no template parameters"); |
959 | 4.17k | FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create( |
960 | 4.17k | Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(), |
961 | 4.17k | TemplateParams, CallOperator); |
962 | 4.17k | TemplateMethod->setAccess(AS_public); |
963 | 4.17k | CallOperator->setDescribedFunctionTemplate(TemplateMethod); |
964 | 4.17k | } |
965 | | |
966 | | void Sema::CompleteLambdaCallOperator( |
967 | | CXXMethodDecl *Method, SourceLocation LambdaLoc, |
968 | | SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, |
969 | | TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, |
970 | | StorageClass SC, ArrayRef<ParmVarDecl *> Params, |
971 | 12.7k | bool HasExplicitResultType) { |
972 | | |
973 | 12.7k | LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); |
974 | | |
975 | 12.7k | if (TrailingRequiresClause) |
976 | 117 | Method->setTrailingRequiresClause(TrailingRequiresClause); |
977 | | |
978 | 12.7k | TemplateParameterList *TemplateParams = |
979 | 12.7k | getGenericLambdaTemplateParameterList(LSI, *this); |
980 | | |
981 | 12.7k | DeclContext *DC = Method->getLexicalDeclContext(); |
982 | 12.7k | Method->setLexicalDeclContext(LSI->Lambda); |
983 | 12.7k | if (TemplateParams) { |
984 | 4.17k | FunctionTemplateDecl *TemplateMethod = |
985 | 4.17k | Method->getDescribedFunctionTemplate(); |
986 | 4.17k | assert(TemplateMethod && |
987 | 4.17k | "AddTemplateParametersToLambdaCallOperator should have been called"); |
988 | | |
989 | 4.17k | LSI->Lambda->addDecl(TemplateMethod); |
990 | 4.17k | TemplateMethod->setLexicalDeclContext(DC); |
991 | 8.53k | } else { |
992 | 8.53k | LSI->Lambda->addDecl(Method); |
993 | 8.53k | } |
994 | 12.7k | LSI->Lambda->setLambdaIsGeneric(TemplateParams); |
995 | 12.7k | LSI->Lambda->setLambdaTypeInfo(MethodTyInfo); |
996 | | |
997 | 12.7k | Method->setLexicalDeclContext(DC); |
998 | 12.7k | Method->setLocation(LambdaLoc); |
999 | 12.7k | Method->setInnerLocStart(CallOperatorLoc); |
1000 | 12.7k | Method->setTypeSourceInfo(MethodTyInfo); |
1001 | 12.7k | Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda, |
1002 | 12.7k | TemplateParams, MethodTyInfo)); |
1003 | 12.7k | Method->setConstexprKind(ConstexprKind); |
1004 | 12.7k | Method->setStorageClass(SC); |
1005 | 12.7k | if (!Params.empty()) { |
1006 | 6.46k | CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false); |
1007 | 6.46k | Method->setParams(Params); |
1008 | 7.79k | for (auto P : Method->parameters()) { |
1009 | 7.79k | assert(P && "null in a parameter list"); |
1010 | 7.79k | P->setOwningFunction(Method); |
1011 | 7.79k | } |
1012 | 6.46k | } |
1013 | | |
1014 | 12.7k | buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType); |
1015 | 12.7k | } |
1016 | | |
1017 | | void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, |
1018 | 9.90k | Scope *CurrentScope) { |
1019 | | |
1020 | 9.90k | LambdaScopeInfo *LSI = getCurLambda(); |
1021 | 9.90k | assert(LSI && "LambdaScopeInfo should be on stack!"); |
1022 | | |
1023 | 9.90k | if (Intro.Default == LCD_ByCopy) |
1024 | 986 | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; |
1025 | 8.91k | else if (Intro.Default == LCD_ByRef) |
1026 | 2.37k | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; |
1027 | 9.90k | LSI->CaptureDefaultLoc = Intro.DefaultLoc; |
1028 | 9.90k | LSI->IntroducerRange = Intro.Range; |
1029 | 9.90k | LSI->AfterParameterList = false; |
1030 | | |
1031 | 9.90k | assert(LSI->NumExplicitTemplateParams == 0); |
1032 | | |
1033 | | // Determine if we're within a context where we know that the lambda will |
1034 | | // be dependent, because there are template parameters in scope. |
1035 | 9.90k | CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind = |
1036 | 9.90k | CXXRecordDecl::LDK_Unknown; |
1037 | 9.90k | if (LSI->NumExplicitTemplateParams > 0) { |
1038 | 0 | Scope *TemplateParamScope = CurScope->getTemplateParamParent(); |
1039 | 0 | assert(TemplateParamScope && |
1040 | 0 | "Lambda with explicit template param list should establish a " |
1041 | 0 | "template param scope"); |
1042 | 0 | assert(TemplateParamScope->getParent()); |
1043 | 0 | if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr) |
1044 | 0 | LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; |
1045 | 9.90k | } else if (CurScope->getTemplateParamParent() != nullptr) { |
1046 | 2.12k | LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent; |
1047 | 2.12k | } |
1048 | | |
1049 | 9.90k | CXXRecordDecl *Class = createLambdaClosureType( |
1050 | 9.90k | Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default); |
1051 | 9.90k | LSI->Lambda = Class; |
1052 | | |
1053 | 9.90k | CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class); |
1054 | 9.90k | LSI->CallOperator = Method; |
1055 | 9.90k | Method->setLexicalDeclContext(CurContext); |
1056 | | |
1057 | 9.90k | PushDeclContext(CurScope, Method); |
1058 | | |
1059 | 9.90k | bool ContainsUnexpandedParameterPack = false; |
1060 | | |
1061 | | // Distinct capture names, for diagnostics. |
1062 | 9.90k | llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames; |
1063 | | |
1064 | | // Handle explicit captures. |
1065 | 9.90k | SourceLocation PrevCaptureLoc = |
1066 | 9.90k | Intro.Default == LCD_None ? Intro.Range.getBegin()6.53k : Intro.DefaultLoc3.36k ; |
1067 | 12.0k | for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; |
1068 | 9.90k | PrevCaptureLoc = C->Loc, ++C2.13k ) { |
1069 | 2.13k | if (C->Kind == LCK_This || C->Kind == LCK_StarThis1.84k ) { |
1070 | 409 | if (C->Kind == LCK_StarThis) |
1071 | 126 | Diag(C->Loc, !getLangOpts().CPlusPlus17 |
1072 | 126 | ? diag::ext_star_this_lambda_capture_cxx172 |
1073 | 126 | : diag::warn_cxx14_compat_star_this_lambda_capture124 ); |
1074 | | |
1075 | | // C++11 [expr.prim.lambda]p8: |
1076 | | // An identifier or this shall not appear more than once in a |
1077 | | // lambda-capture. |
1078 | 409 | if (LSI->isCXXThisCaptured()) { |
1079 | 5 | Diag(C->Loc, diag::err_capture_more_than_once) |
1080 | 5 | << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) |
1081 | 5 | << FixItHint::CreateRemoval( |
1082 | 5 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1083 | 5 | continue; |
1084 | 5 | } |
1085 | | |
1086 | | // C++20 [expr.prim.lambda]p8: |
1087 | | // If a lambda-capture includes a capture-default that is =, |
1088 | | // each simple-capture of that lambda-capture shall be of the form |
1089 | | // "&identifier", "this", or "* this". [ Note: The form [&,this] is |
1090 | | // redundant but accepted for compatibility with ISO C++14. --end note ] |
1091 | 404 | if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis9 ) |
1092 | 5 | Diag(C->Loc, !getLangOpts().CPlusPlus20 |
1093 | 5 | ? diag::ext_equals_this_lambda_capture_cxx203 |
1094 | 5 | : diag::warn_cxx17_compat_equals_this_lambda_capture2 ); |
1095 | | |
1096 | | // C++11 [expr.prim.lambda]p12: |
1097 | | // If this is captured by a local lambda expression, its nearest |
1098 | | // enclosing function shall be a non-static member function. |
1099 | 404 | QualType ThisCaptureType = getCurrentThisType(); |
1100 | 404 | if (ThisCaptureType.isNull()) { |
1101 | 5 | Diag(C->Loc, diag::err_this_capture) << true; |
1102 | 5 | continue; |
1103 | 5 | } |
1104 | | |
1105 | 399 | CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, |
1106 | 399 | /*FunctionScopeIndexToStopAtPtr*/ nullptr, |
1107 | 399 | C->Kind == LCK_StarThis); |
1108 | 399 | if (!LSI->Captures.empty()) |
1109 | 397 | LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; |
1110 | 399 | continue; |
1111 | 404 | } |
1112 | | |
1113 | 1.72k | assert(C->Id && "missing identifier for capture"); |
1114 | | |
1115 | 1.72k | if (C->Init.isInvalid()) |
1116 | 7 | continue; |
1117 | | |
1118 | 1.71k | ValueDecl *Var = nullptr; |
1119 | 1.71k | if (C->Init.isUsable()) { |
1120 | 566 | Diag(C->Loc, getLangOpts().CPlusPlus14 |
1121 | 566 | ? diag::warn_cxx11_compat_init_capture508 |
1122 | 566 | : diag::ext_init_capture58 ); |
1123 | | |
1124 | | // If the initializer expression is usable, but the InitCaptureType |
1125 | | // is not, then an error has occurred - so ignore the capture for now. |
1126 | | // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. |
1127 | | // FIXME: we should create the init capture variable and mark it invalid |
1128 | | // in this case. |
1129 | 566 | if (C->InitCaptureType.get().isNull()) |
1130 | 33 | continue; |
1131 | | |
1132 | 533 | if (C->Init.get()->containsUnexpandedParameterPack() && |
1133 | 533 | !C->InitCaptureType.get()->getAs<PackExpansionType>()86 ) |
1134 | 16 | DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer); |
1135 | | |
1136 | 533 | unsigned InitStyle; |
1137 | 533 | switch (C->InitKind) { |
1138 | 0 | case LambdaCaptureInitKind::NoInit: |
1139 | 0 | llvm_unreachable("not an init-capture?"); |
1140 | 420 | case LambdaCaptureInitKind::CopyInit: |
1141 | 420 | InitStyle = VarDecl::CInit; |
1142 | 420 | break; |
1143 | 94 | case LambdaCaptureInitKind::DirectInit: |
1144 | 94 | InitStyle = VarDecl::CallInit; |
1145 | 94 | break; |
1146 | 19 | case LambdaCaptureInitKind::ListInit: |
1147 | 19 | InitStyle = VarDecl::ListInit; |
1148 | 19 | break; |
1149 | 533 | } |
1150 | 533 | Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), |
1151 | 533 | C->EllipsisLoc, C->Id, InitStyle, |
1152 | 533 | C->Init.get(), Method); |
1153 | 533 | assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?"); |
1154 | 533 | if (auto *V = dyn_cast<VarDecl>(Var)) |
1155 | 533 | CheckShadow(CurrentScope, V); |
1156 | 533 | PushOnScopeChains(Var, CurrentScope, false); |
1157 | 1.15k | } else { |
1158 | 1.15k | assert(C->InitKind == LambdaCaptureInitKind::NoInit && |
1159 | 1.15k | "init capture has valid but null init?"); |
1160 | | |
1161 | | // C++11 [expr.prim.lambda]p8: |
1162 | | // If a lambda-capture includes a capture-default that is &, the |
1163 | | // identifiers in the lambda-capture shall not be preceded by &. |
1164 | | // If a lambda-capture includes a capture-default that is =, [...] |
1165 | | // each identifier it contains shall be preceded by &. |
1166 | 1.15k | if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef390 ) { |
1167 | 7 | Diag(C->Loc, diag::err_reference_capture_with_reference_default) |
1168 | 7 | << FixItHint::CreateRemoval( |
1169 | 7 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1170 | 7 | continue; |
1171 | 1.14k | } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy760 ) { |
1172 | 1 | Diag(C->Loc, diag::err_copy_capture_with_copy_default) |
1173 | 1 | << FixItHint::CreateRemoval( |
1174 | 1 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1175 | 1 | continue; |
1176 | 1 | } |
1177 | | |
1178 | | // C++11 [expr.prim.lambda]p10: |
1179 | | // The identifiers in a capture-list are looked up using the usual |
1180 | | // rules for unqualified name lookup (3.4.1) |
1181 | 1.14k | DeclarationNameInfo Name(C->Id, C->Loc); |
1182 | 1.14k | LookupResult R(*this, Name, LookupOrdinaryName); |
1183 | 1.14k | LookupName(R, CurScope); |
1184 | 1.14k | if (R.isAmbiguous()) |
1185 | 1 | continue; |
1186 | 1.14k | if (R.empty()) { |
1187 | | // FIXME: Disable corrections that would add qualification? |
1188 | 2 | CXXScopeSpec ScopeSpec; |
1189 | 2 | DeclFilterCCC<VarDecl> Validator{}; |
1190 | 2 | if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) |
1191 | 1 | continue; |
1192 | 2 | } |
1193 | | |
1194 | 1.14k | if (auto *BD = R.getAsSingle<BindingDecl>()) |
1195 | 41 | Var = BD; |
1196 | 1.09k | else |
1197 | 1.09k | Var = R.getAsSingle<VarDecl>(); |
1198 | 1.14k | if (Var && DiagnoseUseOfDecl(Var, C->Loc)1.12k ) |
1199 | 2 | continue; |
1200 | 1.14k | } |
1201 | | |
1202 | | // C++11 [expr.prim.lambda]p10: |
1203 | | // [...] each such lookup shall find a variable with automatic storage |
1204 | | // duration declared in the reaching scope of the local lambda expression. |
1205 | | // Note that the 'reaching scope' check happens in tryCaptureVariable(). |
1206 | 1.67k | if (!Var) { |
1207 | 12 | Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; |
1208 | 12 | continue; |
1209 | 12 | } |
1210 | | |
1211 | | // C++11 [expr.prim.lambda]p8: |
1212 | | // An identifier or this shall not appear more than once in a |
1213 | | // lambda-capture. |
1214 | 1.65k | if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var}); |
1215 | 1.65k | !Inserted) { |
1216 | 10 | if (C->InitKind == LambdaCaptureInitKind::NoInit && |
1217 | 10 | !Var->isInitCapture()7 ) { |
1218 | 6 | Diag(C->Loc, diag::err_capture_more_than_once) |
1219 | 6 | << C->Id << It->second->getBeginLoc() |
1220 | 6 | << FixItHint::CreateRemoval( |
1221 | 6 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1222 | 6 | Var->setInvalidDecl(); |
1223 | 6 | } else if (4 Var4 && Var->isPlaceholderVar(getLangOpts())4 ) { |
1224 | 1 | DiagPlaceholderVariableDefinition(C->Loc); |
1225 | 3 | } else { |
1226 | | // Previous capture captured something different (one or both was |
1227 | | // an init-capture): no fixit. |
1228 | 3 | Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; |
1229 | 3 | continue; |
1230 | 3 | } |
1231 | 10 | } |
1232 | | |
1233 | | // Ignore invalid decls; they'll just confuse the code later. |
1234 | 1.65k | if (Var->isInvalidDecl()) |
1235 | 15 | continue; |
1236 | | |
1237 | 1.64k | VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); |
1238 | | |
1239 | 1.64k | if (!Underlying->hasLocalStorage()) { |
1240 | 6 | Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; |
1241 | 6 | Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; |
1242 | 6 | continue; |
1243 | 6 | } |
1244 | | |
1245 | | // C++11 [expr.prim.lambda]p23: |
1246 | | // A capture followed by an ellipsis is a pack expansion (14.5.3). |
1247 | 1.63k | SourceLocation EllipsisLoc; |
1248 | 1.63k | if (C->EllipsisLoc.isValid()) { |
1249 | 153 | if (Var->isParameterPack()) { |
1250 | 149 | EllipsisLoc = C->EllipsisLoc; |
1251 | 149 | } else { |
1252 | 4 | Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
1253 | 4 | << (C->Init.isUsable() ? C->Init.get()->getSourceRange()1 |
1254 | 4 | : SourceRange(C->Loc)3 ); |
1255 | | |
1256 | | // Just ignore the ellipsis. |
1257 | 4 | } |
1258 | 1.48k | } else if (Var->isParameterPack()) { |
1259 | 13 | ContainsUnexpandedParameterPack = true; |
1260 | 13 | } |
1261 | | |
1262 | 1.63k | if (C->Init.isUsable()) { |
1263 | 531 | addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef); |
1264 | 531 | PushOnScopeChains(Var, CurScope, false); |
1265 | 1.10k | } else { |
1266 | 1.10k | TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef377 |
1267 | 1.10k | : TryCapture_ExplicitByVal727 ; |
1268 | 1.10k | tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); |
1269 | 1.10k | } |
1270 | 1.63k | if (!LSI->Captures.empty()) |
1271 | 1.63k | LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange; |
1272 | 1.63k | } |
1273 | 9.90k | finishLambdaExplicitCaptures(LSI); |
1274 | 9.90k | LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack; |
1275 | 9.90k | PopDeclContext(); |
1276 | 9.90k | } |
1277 | | |
1278 | | void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, |
1279 | 9.99k | SourceLocation MutableLoc) { |
1280 | | |
1281 | 9.99k | LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); |
1282 | 9.99k | LSI->Mutable = MutableLoc.isValid(); |
1283 | 9.99k | ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false); |
1284 | | |
1285 | | // C++11 [expr.prim.lambda]p9: |
1286 | | // A lambda-expression whose smallest enclosing scope is a block scope is a |
1287 | | // local lambda expression; any other lambda expression shall not have a |
1288 | | // capture-default or simple-capture in its lambda-introducer. |
1289 | | // |
1290 | | // For simple-captures, this is covered by the check below that any named |
1291 | | // entity is a variable that can be captured. |
1292 | | // |
1293 | | // For DR1632, we also allow a capture-default in any context where we can |
1294 | | // odr-use 'this' (in particular, in a default initializer for a non-static |
1295 | | // data member). |
1296 | 9.99k | if (Intro.Default != LCD_None && |
1297 | 9.99k | !LSI->Lambda->getParent()->isFunctionOrMethod()3.37k && |
1298 | 9.99k | (37 getCurrentThisType().isNull()37 || |
1299 | 37 | CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true, |
1300 | 29 | /*BuildAndDiagnose=*/false))) |
1301 | 8 | Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); |
1302 | 9.99k | } |
1303 | | |
1304 | | void Sema::ActOnLambdaClosureParameters( |
1305 | 9.90k | Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) { |
1306 | 9.90k | LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); |
1307 | 9.90k | PushDeclContext(LambdaScope, LSI->CallOperator); |
1308 | | |
1309 | 9.90k | for (const DeclaratorChunk::ParamInfo &P : Params) { |
1310 | 5.08k | auto *Param = cast<ParmVarDecl>(P.Param); |
1311 | 5.08k | Param->setOwningFunction(LSI->CallOperator); |
1312 | 5.08k | if (Param->getIdentifier()) |
1313 | 4.68k | PushOnScopeChains(Param, LambdaScope, false); |
1314 | 5.08k | } |
1315 | | |
1316 | | // After the parameter list, we may parse a noexcept/requires/trailing return |
1317 | | // type which need to know whether the call operator constiture a dependent |
1318 | | // context, so we need to setup the FunctionTemplateDecl of generic lambdas |
1319 | | // now. |
1320 | 9.90k | TemplateParameterList *TemplateParams = |
1321 | 9.90k | getGenericLambdaTemplateParameterList(LSI, *this); |
1322 | 9.90k | if (TemplateParams) { |
1323 | 2.71k | AddTemplateParametersToLambdaCallOperator(LSI->CallOperator, LSI->Lambda, |
1324 | 2.71k | TemplateParams); |
1325 | 2.71k | LSI->Lambda->setLambdaIsGeneric(true); |
1326 | 2.71k | } |
1327 | 9.90k | LSI->AfterParameterList = true; |
1328 | 9.90k | } |
1329 | | |
1330 | | void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, |
1331 | | Declarator &ParamInfo, |
1332 | 9.90k | const DeclSpec &DS) { |
1333 | | |
1334 | 9.90k | LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(*this); |
1335 | 9.90k | LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier()); |
1336 | | |
1337 | 9.90k | SmallVector<ParmVarDecl *, 8> Params; |
1338 | 9.90k | bool ExplicitResultType; |
1339 | | |
1340 | 9.90k | SourceLocation TypeLoc, CallOperatorLoc; |
1341 | 9.90k | if (ParamInfo.getNumTypeObjects() == 0) { |
1342 | 2.13k | CallOperatorLoc = TypeLoc = Intro.Range.getEnd(); |
1343 | 7.76k | } else { |
1344 | 7.76k | unsigned Index; |
1345 | 7.76k | ParamInfo.isFunctionDeclarator(Index); |
1346 | 7.76k | const auto &Object = ParamInfo.getTypeObject(Index); |
1347 | 7.76k | TypeLoc = |
1348 | 7.76k | Object.Loc.isValid() ? Object.Loc7.67k : ParamInfo.getSourceRange().getEnd()94 ; |
1349 | 7.76k | CallOperatorLoc = ParamInfo.getSourceRange().getEnd(); |
1350 | 7.76k | } |
1351 | | |
1352 | 9.90k | CXXRecordDecl *Class = LSI->Lambda; |
1353 | 9.90k | CXXMethodDecl *Method = LSI->CallOperator; |
1354 | | |
1355 | 9.90k | TypeSourceInfo *MethodTyInfo = getLambdaType( |
1356 | 9.90k | *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType); |
1357 | | |
1358 | 9.90k | LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0; |
1359 | | |
1360 | 9.90k | if (ParamInfo.isFunctionDeclarator() != 0 && |
1361 | 9.90k | !FTIHasSingleVoidParameter(ParamInfo.getFunctionTypeInfo())7.76k ) { |
1362 | 7.74k | const auto &FTI = ParamInfo.getFunctionTypeInfo(); |
1363 | 7.74k | Params.reserve(Params.size()); |
1364 | 12.8k | for (unsigned I = 0; I < FTI.NumParams; ++I5.05k ) { |
1365 | 5.05k | auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param); |
1366 | 5.05k | Param->setScopeInfo(0, Params.size()); |
1367 | 5.05k | Params.push_back(Param); |
1368 | 5.05k | } |
1369 | 7.74k | } |
1370 | | |
1371 | 9.90k | bool IsLambdaStatic = |
1372 | 9.90k | ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static; |
1373 | | |
1374 | 9.90k | CompleteLambdaCallOperator( |
1375 | 9.90k | Method, Intro.Range.getBegin(), CallOperatorLoc, |
1376 | 9.90k | ParamInfo.getTrailingRequiresClause(), MethodTyInfo, |
1377 | 9.90k | ParamInfo.getDeclSpec().getConstexprSpecifier(), |
1378 | 9.90k | IsLambdaStatic ? SC_Static57 : SC_None9.84k , Params, ExplicitResultType); |
1379 | | |
1380 | 9.90k | CheckCXXDefaultArguments(Method); |
1381 | | |
1382 | | // This represents the function body for the lambda function, check if we |
1383 | | // have to apply optnone due to a pragma. |
1384 | 9.90k | AddRangeBasedOptnone(Method); |
1385 | | |
1386 | | // code_seg attribute on lambda apply to the method. |
1387 | 9.90k | if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction( |
1388 | 9.90k | Method, /*IsDefinition=*/true)) |
1389 | 2 | Method->addAttr(A); |
1390 | | |
1391 | | // Attributes on the lambda apply to the method. |
1392 | 9.90k | ProcessDeclAttributes(CurScope, Method, ParamInfo); |
1393 | | |
1394 | | // CUDA lambdas get implicit host and device attributes. |
1395 | 9.90k | if (getLangOpts().CUDA) |
1396 | 245 | CUDASetLambdaAttrs(Method); |
1397 | | |
1398 | | // OpenMP lambdas might get assumumption attributes. |
1399 | 9.90k | if (LangOpts.OpenMP) |
1400 | 1.55k | ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method); |
1401 | | |
1402 | 9.90k | handleLambdaNumbering(Class, Method); |
1403 | | |
1404 | 9.90k | for (auto &&C : LSI->Captures) { |
1405 | 2.04k | if (!C.isVariableCapture()) |
1406 | 416 | continue; |
1407 | 1.63k | ValueDecl *Var = C.getVariable(); |
1408 | 1.63k | if (Var && Var->isInitCapture()) { |
1409 | 548 | PushOnScopeChains(Var, CurScope, false); |
1410 | 548 | } |
1411 | 1.63k | } |
1412 | | |
1413 | 9.90k | auto CheckRedefinition = [&](ParmVarDecl *Param) { |
1414 | 4.68k | for (const auto &Capture : Intro.Captures) { |
1415 | 509 | if (Capture.Id == Param->getIdentifier()) { |
1416 | 16 | Diag(Param->getLocation(), diag::err_parameter_shadow_capture); |
1417 | 16 | Diag(Capture.Loc, diag::note_var_explicitly_captured_here) |
1418 | 16 | << Capture.Id << true; |
1419 | 16 | return false; |
1420 | 16 | } |
1421 | 509 | } |
1422 | 4.66k | return true; |
1423 | 4.68k | }; |
1424 | | |
1425 | 9.90k | for (ParmVarDecl *P : Params) { |
1426 | 5.05k | if (!P->getIdentifier()) |
1427 | 379 | continue; |
1428 | 4.68k | if (CheckRedefinition(P)) |
1429 | 4.66k | CheckShadow(CurScope, P); |
1430 | 4.68k | PushOnScopeChains(P, CurScope); |
1431 | 4.68k | } |
1432 | | |
1433 | | // C++23 [expr.prim.lambda.capture]p5: |
1434 | | // If an identifier in a capture appears as the declarator-id of a parameter |
1435 | | // of the lambda-declarator's parameter-declaration-clause or as the name of a |
1436 | | // template parameter of the lambda-expression's template-parameter-list, the |
1437 | | // program is ill-formed. |
1438 | 9.90k | TemplateParameterList *TemplateParams = |
1439 | 9.90k | getGenericLambdaTemplateParameterList(LSI, *this); |
1440 | 9.90k | if (TemplateParams) { |
1441 | 3.02k | for (const auto *TP : TemplateParams->asArray()) { |
1442 | 3.02k | if (!TP->getIdentifier()) |
1443 | 64 | continue; |
1444 | 2.96k | for (const auto &Capture : Intro.Captures) { |
1445 | 281 | if (Capture.Id == TP->getIdentifier()) { |
1446 | 5 | Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id; |
1447 | 5 | Diag(TP->getLocation(), diag::note_template_param_here); |
1448 | 5 | } |
1449 | 281 | } |
1450 | 2.96k | } |
1451 | 2.71k | } |
1452 | | |
1453 | | // C++20: dcl.decl.general p4: |
1454 | | // The optional requires-clause ([temp.pre]) in an init-declarator or |
1455 | | // member-declarator shall be present only if the declarator declares a |
1456 | | // templated function ([dcl.fct]). |
1457 | 9.90k | if (Expr *TRC = Method->getTrailingRequiresClause()) { |
1458 | | // [temp.pre]/8: |
1459 | | // An entity is templated if it is |
1460 | | // - a template, |
1461 | | // - an entity defined ([basic.def]) or created ([class.temporary]) in a |
1462 | | // templated entity, |
1463 | | // - a member of a templated entity, |
1464 | | // - an enumerator for an enumeration that is a templated entity, or |
1465 | | // - the closure type of a lambda-expression ([expr.prim.lambda.closure]) |
1466 | | // appearing in the declaration of a templated entity. [Note 6: A local |
1467 | | // class, a local or block variable, or a friend function defined in a |
1468 | | // templated entity is a templated entity. — end note] |
1469 | | // |
1470 | | // A templated function is a function template or a function that is |
1471 | | // templated. A templated class is a class template or a class that is |
1472 | | // templated. A templated variable is a variable template or a variable |
1473 | | // that is templated. |
1474 | | |
1475 | | // Note: we only have to check if this is defined in a template entity, OR |
1476 | | // if we are a template, since the rest don't apply. The requires clause |
1477 | | // applies to the call operator, which we already know is a member function, |
1478 | | // AND defined. |
1479 | 61 | if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()30 ) { |
1480 | 2 | Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); |
1481 | 2 | } |
1482 | 61 | } |
1483 | | |
1484 | | // Enter a new evaluation context to insulate the lambda from any |
1485 | | // cleanups from the enclosing full-expression. |
1486 | 9.90k | PushExpressionEvaluationContext( |
1487 | 9.90k | LSI->CallOperator->isConsteval() |
1488 | 9.90k | ? ExpressionEvaluationContext::ImmediateFunctionContext15 |
1489 | 9.90k | : ExpressionEvaluationContext::PotentiallyEvaluated9.88k ); |
1490 | 9.90k | ExprEvalContexts.back().InImmediateFunctionContext = |
1491 | 9.90k | LSI->CallOperator->isConsteval(); |
1492 | 9.90k | ExprEvalContexts.back().InImmediateEscalatingFunctionContext = |
1493 | 9.90k | getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating()2.21k ; |
1494 | 9.90k | } |
1495 | | |
1496 | | void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, |
1497 | 252 | bool IsInstantiation) { |
1498 | 252 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back()); |
1499 | | |
1500 | | // Leave the expression-evaluation context. |
1501 | 252 | DiscardCleanupsInEvaluationContext(); |
1502 | 252 | PopExpressionEvaluationContext(); |
1503 | | |
1504 | | // Leave the context of the lambda. |
1505 | 252 | if (!IsInstantiation) |
1506 | 206 | PopDeclContext(); |
1507 | | |
1508 | | // Finalize the lambda. |
1509 | 252 | CXXRecordDecl *Class = LSI->Lambda; |
1510 | 252 | Class->setInvalidDecl(); |
1511 | 252 | SmallVector<Decl*, 4> Fields(Class->fields()); |
1512 | 252 | ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), |
1513 | 252 | SourceLocation(), ParsedAttributesView()); |
1514 | 252 | CheckCompletedCXXClass(nullptr, Class); |
1515 | | |
1516 | 252 | PopFunctionScopeInfo(); |
1517 | 252 | } |
1518 | | |
1519 | | template <typename Func> |
1520 | | static void repeatForLambdaConversionFunctionCallingConvs( |
1521 | 6.56k | Sema &S, const FunctionProtoType &CallOpProto, Func F) { |
1522 | 6.56k | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( |
1523 | 6.56k | CallOpProto.isVariadic(), /*IsCXXMethod=*/false); |
1524 | 6.56k | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( |
1525 | 6.56k | CallOpProto.isVariadic(), /*IsCXXMethod=*/true); |
1526 | 6.56k | CallingConv CallOpCC = CallOpProto.getCallConv(); |
1527 | | |
1528 | | /// Implement emitting a version of the operator for many of the calling |
1529 | | /// conventions for MSVC, as described here: |
1530 | | /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623. |
1531 | | /// Experimentally, we determined that cdecl, stdcall, fastcall, and |
1532 | | /// vectorcall are generated by MSVC when it is supported by the target. |
1533 | | /// Additionally, we are ensuring that the default-free/default-member and |
1534 | | /// call-operator calling convention are generated as well. |
1535 | | /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the |
1536 | | /// 'member default', despite MSVC not doing so. We do this in order to ensure |
1537 | | /// that someone who intentionally places 'thiscall' on the lambda call |
1538 | | /// operator will still get that overload, since we don't have the a way of |
1539 | | /// detecting the attribute by the time we get here. |
1540 | 6.56k | if (S.getLangOpts().MSVCCompat) { |
1541 | 88 | CallingConv Convs[] = { |
1542 | 88 | CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall, |
1543 | 88 | DefaultFree, DefaultMember, CallOpCC}; |
1544 | 88 | llvm::sort(Convs); |
1545 | 88 | llvm::iterator_range<CallingConv *> Range( |
1546 | 88 | std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs))); |
1547 | 88 | const TargetInfo &TI = S.getASTContext().getTargetInfo(); |
1548 | | |
1549 | 354 | for (CallingConv C : Range) { |
1550 | 354 | if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK) |
1551 | 182 | F(C); |
1552 | 354 | } |
1553 | 88 | return; |
1554 | 88 | } |
1555 | | |
1556 | 6.48k | if (CallOpCC == DefaultMember && DefaultMember != DefaultFree6.45k ) { |
1557 | 1.61k | F(DefaultFree); |
1558 | 1.61k | F(DefaultMember); |
1559 | 4.86k | } else { |
1560 | 4.86k | F(CallOpCC); |
1561 | 4.86k | } |
1562 | 6.48k | } |
1563 | | |
1564 | | // Returns the 'standard' calling convention to be used for the lambda |
1565 | | // conversion function, that is, the 'free' function calling convention unless |
1566 | | // it is overridden by a non-default calling convention attribute. |
1567 | | static CallingConv |
1568 | | getLambdaConversionFunctionCallConv(Sema &S, |
1569 | 178 | const FunctionProtoType *CallOpProto) { |
1570 | 178 | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( |
1571 | 178 | CallOpProto->isVariadic(), /*IsCXXMethod=*/false); |
1572 | 178 | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( |
1573 | 178 | CallOpProto->isVariadic(), /*IsCXXMethod=*/true); |
1574 | 178 | CallingConv CallOpCC = CallOpProto->getCallConv(); |
1575 | | |
1576 | | // If the call-operator hasn't been changed, return both the 'free' and |
1577 | | // 'member' function calling convention. |
1578 | 178 | if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) |
1579 | 0 | return DefaultFree; |
1580 | 178 | return CallOpCC; |
1581 | 178 | } |
1582 | | |
1583 | | QualType Sema::getLambdaConversionFunctionResultType( |
1584 | 8.85k | const FunctionProtoType *CallOpProto, CallingConv CC) { |
1585 | 8.85k | const FunctionProtoType::ExtProtoInfo CallOpExtInfo = |
1586 | 8.85k | CallOpProto->getExtProtoInfo(); |
1587 | 8.85k | FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; |
1588 | 8.85k | InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); |
1589 | 8.85k | InvokerExtInfo.TypeQuals = Qualifiers(); |
1590 | 8.85k | assert(InvokerExtInfo.RefQualifier == RQ_None && |
1591 | 8.85k | "Lambda's call operator should not have a reference qualifier"); |
1592 | 8.85k | return Context.getFunctionType(CallOpProto->getReturnType(), |
1593 | 8.85k | CallOpProto->getParamTypes(), InvokerExtInfo); |
1594 | 8.85k | } |
1595 | | |
1596 | | /// Add a lambda's conversion to function pointer, as described in |
1597 | | /// C++11 [expr.prim.lambda]p6. |
1598 | | static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, |
1599 | | CXXRecordDecl *Class, |
1600 | | CXXMethodDecl *CallOperator, |
1601 | 8.28k | QualType InvokerFunctionTy) { |
1602 | | // This conversion is explicitly disabled if the lambda's function has |
1603 | | // pass_object_size attributes on any of its parameters. |
1604 | 8.28k | auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) { |
1605 | 7.75k | return P->hasAttr<PassObjectSizeAttr>(); |
1606 | 7.75k | }; |
1607 | 8.28k | if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr)) |
1608 | 2 | return; |
1609 | | |
1610 | | // Add the conversion to function pointer. |
1611 | 8.27k | QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); |
1612 | | |
1613 | | // Create the type of the conversion function. |
1614 | 8.27k | FunctionProtoType::ExtProtoInfo ConvExtInfo( |
1615 | 8.27k | S.Context.getDefaultCallingConvention( |
1616 | 8.27k | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
1617 | | // The conversion function is always const and noexcept. |
1618 | 8.27k | ConvExtInfo.TypeQuals = Qualifiers(); |
1619 | 8.27k | ConvExtInfo.TypeQuals.addConst(); |
1620 | 8.27k | ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept; |
1621 | 8.27k | QualType ConvTy = |
1622 | 8.27k | S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo); |
1623 | | |
1624 | 8.27k | SourceLocation Loc = IntroducerRange.getBegin(); |
1625 | 8.27k | DeclarationName ConversionName |
1626 | 8.27k | = S.Context.DeclarationNames.getCXXConversionFunctionName( |
1627 | 8.27k | S.Context.getCanonicalType(PtrToFunctionTy)); |
1628 | | // Construct a TypeSourceInfo for the conversion function, and wire |
1629 | | // all the parameters appropriately for the FunctionProtoTypeLoc |
1630 | | // so that everything works during transformation/instantiation of |
1631 | | // generic lambdas. |
1632 | | // The main reason for wiring up the parameters of the conversion |
1633 | | // function with that of the call operator is so that constructs |
1634 | | // like the following work: |
1635 | | // auto L = [](auto b) { <-- 1 |
1636 | | // return [](auto a) -> decltype(a) { <-- 2 |
1637 | | // return a; |
1638 | | // }; |
1639 | | // }; |
1640 | | // int (*fp)(int) = L(5); |
1641 | | // Because the trailing return type can contain DeclRefExprs that refer |
1642 | | // to the original call operator's variables, we hijack the call |
1643 | | // operators ParmVarDecls below. |
1644 | 8.27k | TypeSourceInfo *ConvNamePtrToFunctionTSI = |
1645 | 8.27k | S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); |
1646 | 8.27k | DeclarationNameLoc ConvNameLoc = |
1647 | 8.27k | DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI); |
1648 | | |
1649 | | // The conversion function is a conversion to a pointer-to-function. |
1650 | 8.27k | TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); |
1651 | 8.27k | FunctionProtoTypeLoc ConvTL = |
1652 | 8.27k | ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); |
1653 | | // Get the result of the conversion function which is a pointer-to-function. |
1654 | 8.27k | PointerTypeLoc PtrToFunctionTL = |
1655 | 8.27k | ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); |
1656 | | // Do the same for the TypeSourceInfo that is used to name the conversion |
1657 | | // operator. |
1658 | 8.27k | PointerTypeLoc ConvNamePtrToFunctionTL = |
1659 | 8.27k | ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); |
1660 | | |
1661 | | // Get the underlying function types that the conversion function will |
1662 | | // be converting to (should match the type of the call operator). |
1663 | 8.27k | FunctionProtoTypeLoc CallOpConvTL = |
1664 | 8.27k | PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); |
1665 | 8.27k | FunctionProtoTypeLoc CallOpConvNameTL = |
1666 | 8.27k | ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); |
1667 | | |
1668 | | // Wire up the FunctionProtoTypeLocs with the call operator's parameters. |
1669 | | // These parameter's are essentially used to transform the name and |
1670 | | // the type of the conversion operator. By using the same parameters |
1671 | | // as the call operator's we don't have to fix any back references that |
1672 | | // the trailing return type of the call operator's uses (such as |
1673 | | // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) |
1674 | | // - we can simply use the return type of the call operator, and |
1675 | | // everything should work. |
1676 | 8.27k | SmallVector<ParmVarDecl *, 4> InvokerParams; |
1677 | 16.0k | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I7.75k ) { |
1678 | 7.75k | ParmVarDecl *From = CallOperator->getParamDecl(I); |
1679 | | |
1680 | 7.75k | InvokerParams.push_back(ParmVarDecl::Create( |
1681 | 7.75k | S.Context, |
1682 | | // Temporarily add to the TU. This is set to the invoker below. |
1683 | 7.75k | S.Context.getTranslationUnitDecl(), From->getBeginLoc(), |
1684 | 7.75k | From->getLocation(), From->getIdentifier(), From->getType(), |
1685 | 7.75k | From->getTypeSourceInfo(), From->getStorageClass(), |
1686 | 7.75k | /*DefArg=*/nullptr)); |
1687 | 7.75k | CallOpConvTL.setParam(I, From); |
1688 | 7.75k | CallOpConvNameTL.setParam(I, From); |
1689 | 7.75k | } |
1690 | | |
1691 | 8.27k | CXXConversionDecl *Conversion = CXXConversionDecl::Create( |
1692 | 8.27k | S.Context, Class, Loc, |
1693 | 8.27k | DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI, |
1694 | 8.27k | S.getCurFPFeatures().isFPConstrained(), |
1695 | 8.27k | /*isInline=*/true, ExplicitSpecifier(), |
1696 | 8.27k | S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr2.92k |
1697 | 8.27k | : ConstexprSpecKind::Unspecified5.35k , |
1698 | 8.27k | CallOperator->getBody()->getEndLoc()); |
1699 | 8.27k | Conversion->setAccess(AS_public); |
1700 | 8.27k | Conversion->setImplicit(true); |
1701 | | |
1702 | | // A non-generic lambda may still be a templated entity. We need to preserve |
1703 | | // constraints when converting the lambda to a function pointer. See GH63181. |
1704 | 8.27k | if (Expr *Requires = CallOperator->getTrailingRequiresClause()) |
1705 | 82 | Conversion->setTrailingRequiresClause(Requires); |
1706 | | |
1707 | 8.27k | if (Class->isGenericLambda()) { |
1708 | | // Create a template version of the conversion operator, using the template |
1709 | | // parameter list of the function call operator. |
1710 | 4.02k | FunctionTemplateDecl *TemplateCallOperator = |
1711 | 4.02k | CallOperator->getDescribedFunctionTemplate(); |
1712 | 4.02k | FunctionTemplateDecl *ConversionTemplate = |
1713 | 4.02k | FunctionTemplateDecl::Create(S.Context, Class, |
1714 | 4.02k | Loc, ConversionName, |
1715 | 4.02k | TemplateCallOperator->getTemplateParameters(), |
1716 | 4.02k | Conversion); |
1717 | 4.02k | ConversionTemplate->setAccess(AS_public); |
1718 | 4.02k | ConversionTemplate->setImplicit(true); |
1719 | 4.02k | Conversion->setDescribedFunctionTemplate(ConversionTemplate); |
1720 | 4.02k | Class->addDecl(ConversionTemplate); |
1721 | 4.02k | } else |
1722 | 4.25k | Class->addDecl(Conversion); |
1723 | | |
1724 | | // If the lambda is not static, we need to add a static member |
1725 | | // function that will be the result of the conversion with a |
1726 | | // certain unique ID. |
1727 | | // When it is static we just return the static call operator instead. |
1728 | 8.27k | if (CallOperator->isImplicitObjectMemberFunction()) { |
1729 | 8.21k | DeclarationName InvokerName = |
1730 | 8.21k | &S.Context.Idents.get(getLambdaStaticInvokerName()); |
1731 | | // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() |
1732 | | // we should get a prebuilt TrivialTypeSourceInfo from Context |
1733 | | // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc |
1734 | | // then rewire the parameters accordingly, by hoisting up the InvokeParams |
1735 | | // loop below and then use its Params to set Invoke->setParams(...) below. |
1736 | | // This would avoid the 'const' qualifier of the calloperator from |
1737 | | // contaminating the type of the invoker, which is currently adjusted |
1738 | | // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the |
1739 | | // trailing return type of the invoker would require a visitor to rebuild |
1740 | | // the trailing return type and adjusting all back DeclRefExpr's to refer |
1741 | | // to the new static invoker parameters - not the call operator's. |
1742 | 8.21k | CXXMethodDecl *Invoke = CXXMethodDecl::Create( |
1743 | 8.21k | S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc), |
1744 | 8.21k | InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static, |
1745 | 8.21k | S.getCurFPFeatures().isFPConstrained(), |
1746 | 8.21k | /*isInline=*/true, CallOperator->getConstexprKind(), |
1747 | 8.21k | CallOperator->getBody()->getEndLoc()); |
1748 | 15.9k | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I7.73k ) |
1749 | 7.73k | InvokerParams[I]->setOwningFunction(Invoke); |
1750 | 8.21k | Invoke->setParams(InvokerParams); |
1751 | 8.21k | Invoke->setAccess(AS_private); |
1752 | 8.21k | Invoke->setImplicit(true); |
1753 | 8.21k | if (Class->isGenericLambda()) { |
1754 | 4.02k | FunctionTemplateDecl *TemplateCallOperator = |
1755 | 4.02k | CallOperator->getDescribedFunctionTemplate(); |
1756 | 4.02k | FunctionTemplateDecl *StaticInvokerTemplate = |
1757 | 4.02k | FunctionTemplateDecl::Create( |
1758 | 4.02k | S.Context, Class, Loc, InvokerName, |
1759 | 4.02k | TemplateCallOperator->getTemplateParameters(), Invoke); |
1760 | 4.02k | StaticInvokerTemplate->setAccess(AS_private); |
1761 | 4.02k | StaticInvokerTemplate->setImplicit(true); |
1762 | 4.02k | Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); |
1763 | 4.02k | Class->addDecl(StaticInvokerTemplate); |
1764 | 4.02k | } else |
1765 | 4.19k | Class->addDecl(Invoke); |
1766 | 8.21k | } |
1767 | 8.27k | } |
1768 | | |
1769 | | /// Add a lambda's conversion to function pointers, as described in |
1770 | | /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a |
1771 | | /// single pointer conversion. In the event that the default calling convention |
1772 | | /// for free and member functions is different, it will emit both conventions. |
1773 | | static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, |
1774 | | CXXRecordDecl *Class, |
1775 | 6.56k | CXXMethodDecl *CallOperator) { |
1776 | 6.56k | const FunctionProtoType *CallOpProto = |
1777 | 6.56k | CallOperator->getType()->castAs<FunctionProtoType>(); |
1778 | | |
1779 | 6.56k | repeatForLambdaConversionFunctionCallingConvs( |
1780 | 8.28k | S, *CallOpProto, [&](CallingConv CC) { |
1781 | 8.28k | QualType InvokerFunctionTy = |
1782 | 8.28k | S.getLambdaConversionFunctionResultType(CallOpProto, CC); |
1783 | 8.28k | addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator, |
1784 | 8.28k | InvokerFunctionTy); |
1785 | 8.28k | }); |
1786 | 6.56k | } |
1787 | | |
1788 | | /// Add a lambda's conversion to block pointer. |
1789 | | static void addBlockPointerConversion(Sema &S, |
1790 | | SourceRange IntroducerRange, |
1791 | | CXXRecordDecl *Class, |
1792 | 178 | CXXMethodDecl *CallOperator) { |
1793 | 178 | const FunctionProtoType *CallOpProto = |
1794 | 178 | CallOperator->getType()->castAs<FunctionProtoType>(); |
1795 | 178 | QualType FunctionTy = S.getLambdaConversionFunctionResultType( |
1796 | 178 | CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto)); |
1797 | 178 | QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); |
1798 | | |
1799 | 178 | FunctionProtoType::ExtProtoInfo ConversionEPI( |
1800 | 178 | S.Context.getDefaultCallingConvention( |
1801 | 178 | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
1802 | 178 | ConversionEPI.TypeQuals = Qualifiers(); |
1803 | 178 | ConversionEPI.TypeQuals.addConst(); |
1804 | 178 | QualType ConvTy = |
1805 | 178 | S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI); |
1806 | | |
1807 | 178 | SourceLocation Loc = IntroducerRange.getBegin(); |
1808 | 178 | DeclarationName Name |
1809 | 178 | = S.Context.DeclarationNames.getCXXConversionFunctionName( |
1810 | 178 | S.Context.getCanonicalType(BlockPtrTy)); |
1811 | 178 | DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc( |
1812 | 178 | S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc)); |
1813 | 178 | CXXConversionDecl *Conversion = CXXConversionDecl::Create( |
1814 | 178 | S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy, |
1815 | 178 | S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), |
1816 | 178 | S.getCurFPFeatures().isFPConstrained(), |
1817 | 178 | /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, |
1818 | 178 | CallOperator->getBody()->getEndLoc()); |
1819 | 178 | Conversion->setAccess(AS_public); |
1820 | 178 | Conversion->setImplicit(true); |
1821 | 178 | Class->addDecl(Conversion); |
1822 | 178 | } |
1823 | | |
1824 | | ExprResult Sema::BuildCaptureInit(const Capture &Cap, |
1825 | | SourceLocation ImplicitCaptureLoc, |
1826 | 515k | bool IsOpenMPMapping) { |
1827 | | // VLA captures don't have a stored initialization expression. |
1828 | 515k | if (Cap.isVLATypeCapture()) |
1829 | 9.36k | return ExprResult(); |
1830 | | |
1831 | | // An init-capture is initialized directly from its stored initializer. |
1832 | 505k | if (Cap.isInitCapture()) |
1833 | 673 | return cast<VarDecl>(Cap.getVariable())->getInit(); |
1834 | | |
1835 | | // For anything else, build an initialization expression. For an implicit |
1836 | | // capture, the capture notionally happens at the capture-default, so use |
1837 | | // that location here. |
1838 | 505k | SourceLocation Loc = |
1839 | 505k | ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc503k : Cap.getLocation()1.87k ; |
1840 | | |
1841 | | // C++11 [expr.prim.lambda]p21: |
1842 | | // When the lambda-expression is evaluated, the entities that |
1843 | | // are captured by copy are used to direct-initialize each |
1844 | | // corresponding non-static data member of the resulting closure |
1845 | | // object. (For array members, the array elements are |
1846 | | // direct-initialized in increasing subscript order.) These |
1847 | | // initializations are performed in the (unspecified) order in |
1848 | | // which the non-static data members are declared. |
1849 | | |
1850 | | // C++ [expr.prim.lambda]p12: |
1851 | | // An entity captured by a lambda-expression is odr-used (3.2) in |
1852 | | // the scope containing the lambda-expression. |
1853 | 505k | ExprResult Init; |
1854 | 505k | IdentifierInfo *Name = nullptr; |
1855 | 505k | if (Cap.isThisCapture()) { |
1856 | 13.4k | QualType ThisTy = getCurrentThisType(); |
1857 | 13.4k | Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid()); |
1858 | 13.4k | if (Cap.isCopyCapture()) |
1859 | 142 | Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This); |
1860 | 13.3k | else |
1861 | 13.3k | Init = This; |
1862 | 491k | } else { |
1863 | 491k | assert(Cap.isVariableCapture() && "unknown kind of capture"); |
1864 | 491k | ValueDecl *Var = Cap.getVariable(); |
1865 | 491k | Name = Var->getIdentifier(); |
1866 | 491k | Init = BuildDeclarationNameExpr( |
1867 | 491k | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); |
1868 | 491k | } |
1869 | | |
1870 | | // In OpenMP, the capture kind doesn't actually describe how to capture: |
1871 | | // variables are "mapped" onto the device in a process that does not formally |
1872 | | // make a copy, even for a "copy capture". |
1873 | 505k | if (IsOpenMPMapping) |
1874 | 498k | return Init; |
1875 | | |
1876 | 6.28k | if (Init.isInvalid()) |
1877 | 0 | return ExprError(); |
1878 | | |
1879 | 6.28k | Expr *InitExpr = Init.get(); |
1880 | 6.28k | InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture( |
1881 | 6.28k | Name, Cap.getCaptureType(), Loc); |
1882 | 6.28k | InitializationKind InitKind = |
1883 | 6.28k | InitializationKind::CreateDirect(Loc, Loc, Loc); |
1884 | 6.28k | InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr); |
1885 | 6.28k | return InitSeq.Perform(*this, Entity, InitKind, InitExpr); |
1886 | 6.28k | } |
1887 | | |
1888 | | ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, |
1889 | 9.69k | Scope *CurScope) { |
1890 | 9.69k | LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); |
1891 | 9.69k | ActOnFinishFunctionBody(LSI.CallOperator, Body); |
1892 | 9.69k | return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); |
1893 | 9.69k | } |
1894 | | |
1895 | | static LambdaCaptureDefault |
1896 | 12.4k | mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) { |
1897 | 12.4k | switch (ICS) { |
1898 | 8.51k | case CapturingScopeInfo::ImpCap_None: |
1899 | 8.51k | return LCD_None; |
1900 | 1.38k | case CapturingScopeInfo::ImpCap_LambdaByval: |
1901 | 1.38k | return LCD_ByCopy; |
1902 | 0 | case CapturingScopeInfo::ImpCap_CapturedRegion: |
1903 | 2.55k | case CapturingScopeInfo::ImpCap_LambdaByref: |
1904 | 2.55k | return LCD_ByRef; |
1905 | 0 | case CapturingScopeInfo::ImpCap_Block: |
1906 | 0 | llvm_unreachable("block capture in lambda"); |
1907 | 12.4k | } |
1908 | 0 | llvm_unreachable("Unknown implicit capture style"); |
1909 | 0 | } |
1910 | | |
1911 | 856 | bool Sema::CaptureHasSideEffects(const Capture &From) { |
1912 | 856 | if (From.isInitCapture()) { |
1913 | 261 | Expr *Init = cast<VarDecl>(From.getVariable())->getInit(); |
1914 | 261 | if (Init && Init->HasSideEffects(Context)) |
1915 | 61 | return true; |
1916 | 261 | } |
1917 | | |
1918 | 795 | if (!From.isCopyCapture()) |
1919 | 204 | return false; |
1920 | | |
1921 | 591 | const QualType T = From.isThisCapture() |
1922 | 591 | ? getCurrentThisType()->getPointeeType()43 |
1923 | 591 | : From.getCaptureType()548 ; |
1924 | | |
1925 | 591 | if (T.isVolatileQualified()) |
1926 | 6 | return true; |
1927 | | |
1928 | 585 | const Type *BaseT = T->getBaseElementTypeUnsafe(); |
1929 | 585 | if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl()) |
1930 | 108 | return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() || |
1931 | 108 | !RD->hasTrivialDestructor()84 ; |
1932 | | |
1933 | 477 | return false; |
1934 | 585 | } |
1935 | | |
1936 | | bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, |
1937 | 856 | const Capture &From) { |
1938 | 856 | if (CaptureHasSideEffects(From)) |
1939 | 105 | return false; |
1940 | | |
1941 | 751 | if (From.isVLATypeCapture()) |
1942 | 22 | return false; |
1943 | | |
1944 | | // FIXME: maybe we should warn on these if we can find a sensible diagnostic |
1945 | | // message |
1946 | 729 | if (From.isInitCapture() && |
1947 | 729 | From.getVariable()->isPlaceholderVar(getLangOpts())200 ) |
1948 | 3 | return false; |
1949 | | |
1950 | 726 | auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture); |
1951 | 726 | if (From.isThisCapture()) |
1952 | 101 | diag << "'this'"; |
1953 | 625 | else |
1954 | 625 | diag << From.getVariable(); |
1955 | 726 | diag << From.isNonODRUsed(); |
1956 | 726 | diag << FixItHint::CreateRemoval(CaptureRange); |
1957 | 726 | return true; |
1958 | 729 | } |
1959 | | |
1960 | | /// Create a field within the lambda class or captured statement record for the |
1961 | | /// given capture. |
1962 | | FieldDecl *Sema::BuildCaptureField(RecordDecl *RD, |
1963 | 515k | const sema::Capture &Capture) { |
1964 | 515k | SourceLocation Loc = Capture.getLocation(); |
1965 | 515k | QualType FieldType = Capture.getCaptureType(); |
1966 | | |
1967 | 515k | TypeSourceInfo *TSI = nullptr; |
1968 | 515k | if (Capture.isVariableCapture()) { |
1969 | 492k | const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable()); |
1970 | 492k | if (Var && Var->isInitCapture()492k ) |
1971 | 720 | TSI = Var->getTypeSourceInfo(); |
1972 | 492k | } |
1973 | | |
1974 | | // FIXME: Should we really be doing this? A null TypeSourceInfo seems more |
1975 | | // appropriate, at least for an implicit capture. |
1976 | 515k | if (!TSI) |
1977 | 514k | TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc); |
1978 | | |
1979 | | // Build the non-static data member. |
1980 | 515k | FieldDecl *Field = |
1981 | 515k | FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc, |
1982 | 515k | /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr, |
1983 | 515k | /*Mutable=*/false, ICIS_NoInit); |
1984 | | // If the variable being captured has an invalid type, mark the class as |
1985 | | // invalid as well. |
1986 | 515k | if (!FieldType->isDependentType()) { |
1987 | 510k | if (RequireCompleteSizedType(Loc, FieldType, |
1988 | 510k | diag::err_field_incomplete_or_sizeless)) { |
1989 | 3 | RD->setInvalidDecl(); |
1990 | 3 | Field->setInvalidDecl(); |
1991 | 510k | } else { |
1992 | 510k | NamedDecl *Def; |
1993 | 510k | FieldType->isIncompleteType(&Def); |
1994 | 510k | if (Def && Def->isInvalidDecl()350 ) { |
1995 | 2 | RD->setInvalidDecl(); |
1996 | 2 | Field->setInvalidDecl(); |
1997 | 2 | } |
1998 | 510k | } |
1999 | 510k | } |
2000 | 515k | Field->setImplicit(true); |
2001 | 515k | Field->setAccess(AS_private); |
2002 | 515k | RD->addDecl(Field); |
2003 | | |
2004 | 515k | if (Capture.isVLATypeCapture()) |
2005 | 9.36k | Field->setCapturedVLAType(Capture.getCapturedVLAType()); |
2006 | | |
2007 | 515k | return Field; |
2008 | 515k | } |
2009 | | |
2010 | | ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
2011 | 12.4k | LambdaScopeInfo *LSI) { |
2012 | | // Collect information from the lambda scope. |
2013 | 12.4k | SmallVector<LambdaCapture, 4> Captures; |
2014 | 12.4k | SmallVector<Expr *, 4> CaptureInits; |
2015 | 12.4k | SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc; |
2016 | 12.4k | LambdaCaptureDefault CaptureDefault = |
2017 | 12.4k | mapImplicitCaptureStyle(LSI->ImpCaptureStyle); |
2018 | 12.4k | CXXRecordDecl *Class; |
2019 | 12.4k | CXXMethodDecl *CallOperator; |
2020 | 12.4k | SourceRange IntroducerRange; |
2021 | 12.4k | bool ExplicitParams; |
2022 | 12.4k | bool ExplicitResultType; |
2023 | 12.4k | CleanupInfo LambdaCleanup; |
2024 | 12.4k | bool ContainsUnexpandedParameterPack; |
2025 | 12.4k | bool IsGenericLambda; |
2026 | 12.4k | { |
2027 | 12.4k | CallOperator = LSI->CallOperator; |
2028 | 12.4k | Class = LSI->Lambda; |
2029 | 12.4k | IntroducerRange = LSI->IntroducerRange; |
2030 | 12.4k | ExplicitParams = LSI->ExplicitParams; |
2031 | 12.4k | ExplicitResultType = !LSI->HasImplicitReturnType; |
2032 | 12.4k | LambdaCleanup = LSI->Cleanup; |
2033 | 12.4k | ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; |
2034 | 12.4k | IsGenericLambda = Class->isGenericLambda(); |
2035 | | |
2036 | 12.4k | CallOperator->setLexicalDeclContext(Class); |
2037 | 12.4k | Decl *TemplateOrNonTemplateCallOperatorDecl = |
2038 | 12.4k | CallOperator->getDescribedFunctionTemplate() |
2039 | 12.4k | ? CallOperator->getDescribedFunctionTemplate()4.15k |
2040 | 12.4k | : cast<Decl>(CallOperator)8.29k ; |
2041 | | |
2042 | | // FIXME: Is this really the best choice? Keeping the lexical decl context |
2043 | | // set as CurContext seems more faithful to the source. |
2044 | 12.4k | TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); |
2045 | | |
2046 | 12.4k | PopExpressionEvaluationContext(); |
2047 | | |
2048 | | // True if the current capture has a used capture or default before it. |
2049 | 12.4k | bool CurHasPreviousCapture = CaptureDefault != LCD_None; |
2050 | 12.4k | SourceLocation PrevCaptureLoc = CurHasPreviousCapture ? |
2051 | 8.51k | CaptureDefaultLoc3.93k : IntroducerRange.getBegin(); |
2052 | | |
2053 | 19.1k | for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I6.68k ) { |
2054 | 6.71k | const Capture &From = LSI->Captures[I]; |
2055 | | |
2056 | 6.71k | if (From.isInvalid()) |
2057 | 27 | return ExprError(); |
2058 | | |
2059 | 6.68k | assert(!From.isBlockCapture() && "Cannot capture __block variables"); |
2060 | 6.68k | bool IsImplicit = I >= LSI->NumExplicitCaptures; |
2061 | 6.68k | SourceLocation ImplicitCaptureLoc = |
2062 | 6.68k | IsImplicit ? CaptureDefaultLoc4.21k : SourceLocation()2.46k ; |
2063 | | |
2064 | | // Use source ranges of explicit captures for fixits where available. |
2065 | 6.68k | SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I]; |
2066 | | |
2067 | | // Warn about unused explicit captures. |
2068 | 6.68k | bool IsCaptureUsed = true; |
2069 | 6.68k | if (!CurContext->isDependentContext() && !IsImplicit5.97k && |
2070 | 6.68k | !From.isODRUsed()1.91k ) { |
2071 | | // Initialized captures that are non-ODR used may not be eliminated. |
2072 | | // FIXME: Where did the IsGenericLambda here come from? |
2073 | 885 | bool NonODRUsedInitCapture = |
2074 | 885 | IsGenericLambda && From.isNonODRUsed()78 && From.isInitCapture()31 ; |
2075 | 885 | if (!NonODRUsedInitCapture) { |
2076 | 856 | bool IsLast = (I + 1) == LSI->NumExplicitCaptures; |
2077 | 856 | SourceRange FixItRange; |
2078 | 856 | if (CaptureRange.isValid()) { |
2079 | 661 | if (!CurHasPreviousCapture && !IsLast582 ) { |
2080 | | // If there are no captures preceding this capture, remove the |
2081 | | // following comma. |
2082 | 114 | FixItRange = SourceRange(CaptureRange.getBegin(), |
2083 | 114 | getLocForEndOfToken(CaptureRange.getEnd())); |
2084 | 547 | } else { |
2085 | | // Otherwise, remove the comma since the last used capture. |
2086 | 547 | FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc), |
2087 | 547 | CaptureRange.getEnd()); |
2088 | 547 | } |
2089 | 661 | } |
2090 | | |
2091 | 856 | IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From); |
2092 | 856 | } |
2093 | 885 | } |
2094 | | |
2095 | 6.68k | if (CaptureRange.isValid()) { |
2096 | 1.99k | CurHasPreviousCapture |= IsCaptureUsed; |
2097 | 1.99k | PrevCaptureLoc = CaptureRange.getEnd(); |
2098 | 1.99k | } |
2099 | | |
2100 | | // Map the capture to our AST representation. |
2101 | 6.68k | LambdaCapture Capture = [&] { |
2102 | 6.68k | if (From.isThisCapture()) { |
2103 | | // Capturing 'this' implicitly with a default of '[=]' is deprecated, |
2104 | | // because it results in a reference capture. Don't warn prior to |
2105 | | // C++2a; there's nothing that can be done about it before then. |
2106 | 877 | if (getLangOpts().CPlusPlus20 && IsImplicit109 && |
2107 | 877 | CaptureDefault == LCD_ByCopy65 ) { |
2108 | 42 | Diag(From.getLocation(), diag::warn_deprecated_this_capture); |
2109 | 42 | Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture) |
2110 | 42 | << FixItHint::CreateInsertion( |
2111 | 42 | getLocForEndOfToken(CaptureDefaultLoc), ", this"); |
2112 | 42 | } |
2113 | 877 | return LambdaCapture(From.getLocation(), IsImplicit, |
2114 | 877 | From.isCopyCapture() ? LCK_StarThis142 : LCK_This735 ); |
2115 | 5.80k | } else if (From.isVLATypeCapture()) { |
2116 | 50 | return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType); |
2117 | 5.75k | } else { |
2118 | 5.75k | assert(From.isVariableCapture() && "unknown kind of capture"); |
2119 | 5.75k | ValueDecl *Var = From.getVariable(); |
2120 | 5.75k | LambdaCaptureKind Kind = |
2121 | 5.75k | From.isCopyCapture() ? LCK_ByCopy2.13k : LCK_ByRef3.61k ; |
2122 | 5.75k | return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var, |
2123 | 5.75k | From.getEllipsisLoc()); |
2124 | 5.75k | } |
2125 | 6.68k | }(); |
2126 | | |
2127 | | // Form the initializer for the capture field. |
2128 | 6.68k | ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc); |
2129 | | |
2130 | | // FIXME: Skip this capture if the capture is not used, the initializer |
2131 | | // has no side-effects, the type of the capture is trivial, and the |
2132 | | // lambda is not externally visible. |
2133 | | |
2134 | | // Add a FieldDecl for the capture and form its initializer. |
2135 | 6.68k | BuildCaptureField(Class, From); |
2136 | 6.68k | Captures.push_back(Capture); |
2137 | 6.68k | CaptureInits.push_back(Init.get()); |
2138 | | |
2139 | 6.68k | if (LangOpts.CUDA) |
2140 | 98 | CUDACheckLambdaCapture(CallOperator, From); |
2141 | 6.68k | } |
2142 | | |
2143 | 12.4k | Class->setCaptures(Context, Captures); |
2144 | | |
2145 | | // C++11 [expr.prim.lambda]p6: |
2146 | | // The closure type for a lambda-expression with no lambda-capture |
2147 | | // has a public non-virtual non-explicit const conversion function |
2148 | | // to pointer to function having the same parameter and return |
2149 | | // types as the closure type's function call operator. |
2150 | 12.4k | if (Captures.empty() && CaptureDefault == LCD_None8.09k ) |
2151 | 6.56k | addFunctionPointerConversions(*this, IntroducerRange, Class, |
2152 | 6.56k | CallOperator); |
2153 | | |
2154 | | // Objective-C++: |
2155 | | // The closure type for a lambda-expression has a public non-virtual |
2156 | | // non-explicit const conversion function to a block pointer having the |
2157 | | // same parameter and return types as the closure type's function call |
2158 | | // operator. |
2159 | | // FIXME: Fix generic lambda to block conversions. |
2160 | 12.4k | if (getLangOpts().Blocks && getLangOpts().ObjC6.25k && !IsGenericLambda192 ) |
2161 | 178 | addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); |
2162 | | |
2163 | | // Finalize the lambda class. |
2164 | 12.4k | SmallVector<Decl*, 4> Fields(Class->fields()); |
2165 | 12.4k | ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), |
2166 | 12.4k | SourceLocation(), ParsedAttributesView()); |
2167 | 12.4k | CheckCompletedCXXClass(nullptr, Class); |
2168 | 12.4k | } |
2169 | | |
2170 | 0 | Cleanup.mergeFrom(LambdaCleanup); |
2171 | | |
2172 | 12.4k | LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, |
2173 | 12.4k | CaptureDefault, CaptureDefaultLoc, |
2174 | 12.4k | ExplicitParams, ExplicitResultType, |
2175 | 12.4k | CaptureInits, EndLoc, |
2176 | 12.4k | ContainsUnexpandedParameterPack); |
2177 | | // If the lambda expression's call operator is not explicitly marked constexpr |
2178 | | // and we are not in a dependent context, analyze the call operator to infer |
2179 | | // its constexpr-ness, suppressing diagnostics while doing so. |
2180 | 12.4k | if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl()5.28k && |
2181 | 12.4k | !CallOperator->isConstexpr()5.24k && |
2182 | 12.4k | !isa<CoroutineBodyStmt>(CallOperator->getBody())4.96k && |
2183 | 12.4k | !Class->getDeclContext()->isDependentContext()4.93k ) { |
2184 | 3.52k | CallOperator->setConstexprKind( |
2185 | 3.52k | CheckConstexprFunctionDefinition(CallOperator, |
2186 | 3.52k | CheckConstexprKind::CheckValid) |
2187 | 3.52k | ? ConstexprSpecKind::Constexpr3.31k |
2188 | 3.52k | : ConstexprSpecKind::Unspecified214 ); |
2189 | 3.52k | } |
2190 | | |
2191 | | // Emit delayed shadowing warnings now that the full capture list is known. |
2192 | 12.4k | DiagnoseShadowingLambdaDecls(LSI); |
2193 | | |
2194 | 12.4k | if (!CurContext->isDependentContext()) { |
2195 | 9.30k | switch (ExprEvalContexts.back().Context) { |
2196 | | // C++11 [expr.prim.lambda]p2: |
2197 | | // A lambda-expression shall not appear in an unevaluated operand |
2198 | | // (Clause 5). |
2199 | 161 | case ExpressionEvaluationContext::Unevaluated: |
2200 | 161 | case ExpressionEvaluationContext::UnevaluatedList: |
2201 | 161 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
2202 | | // C++1y [expr.const]p2: |
2203 | | // A conditional-expression e is a core constant expression unless the |
2204 | | // evaluation of e, following the rules of the abstract machine, would |
2205 | | // evaluate [...] a lambda-expression. |
2206 | | // |
2207 | | // This is technically incorrect, there are some constant evaluated contexts |
2208 | | // where this should be allowed. We should probably fix this when DR1607 is |
2209 | | // ratified, it lays out the exact set of conditions where we shouldn't |
2210 | | // allow a lambda-expression. |
2211 | 378 | case ExpressionEvaluationContext::ConstantEvaluated: |
2212 | 378 | case ExpressionEvaluationContext::ImmediateFunctionContext: |
2213 | | // We don't actually diagnose this case immediately, because we |
2214 | | // could be within a context where we might find out later that |
2215 | | // the expression is potentially evaluated (e.g., for typeid). |
2216 | 378 | ExprEvalContexts.back().Lambdas.push_back(Lambda); |
2217 | 378 | break; |
2218 | | |
2219 | 0 | case ExpressionEvaluationContext::DiscardedStatement: |
2220 | 8.49k | case ExpressionEvaluationContext::PotentiallyEvaluated: |
2221 | 8.92k | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
2222 | 8.92k | break; |
2223 | 9.30k | } |
2224 | 9.30k | } |
2225 | | |
2226 | 12.4k | return MaybeBindToTemporary(Lambda); |
2227 | 12.4k | } |
2228 | | |
2229 | | ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, |
2230 | | SourceLocation ConvLocation, |
2231 | | CXXConversionDecl *Conv, |
2232 | 31 | Expr *Src) { |
2233 | | // Make sure that the lambda call operator is marked used. |
2234 | 31 | CXXRecordDecl *Lambda = Conv->getParent(); |
2235 | 31 | CXXMethodDecl *CallOperator |
2236 | 31 | = cast<CXXMethodDecl>( |
2237 | 31 | Lambda->lookup( |
2238 | 31 | Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); |
2239 | 31 | CallOperator->setReferenced(); |
2240 | 31 | CallOperator->markUsed(Context); |
2241 | | |
2242 | 31 | ExprResult Init = PerformCopyInitialization( |
2243 | 31 | InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()), |
2244 | 31 | CurrentLocation, Src); |
2245 | 31 | if (!Init.isInvalid()) |
2246 | 31 | Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); |
2247 | | |
2248 | 31 | if (Init.isInvalid()) |
2249 | 0 | return ExprError(); |
2250 | | |
2251 | | // Create the new block to be returned. |
2252 | 31 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); |
2253 | | |
2254 | | // Set the type information. |
2255 | 31 | Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); |
2256 | 31 | Block->setIsVariadic(CallOperator->isVariadic()); |
2257 | 31 | Block->setBlockMissingReturnType(false); |
2258 | | |
2259 | | // Add parameters. |
2260 | 31 | SmallVector<ParmVarDecl *, 4> BlockParams; |
2261 | 42 | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I11 ) { |
2262 | 11 | ParmVarDecl *From = CallOperator->getParamDecl(I); |
2263 | 11 | BlockParams.push_back(ParmVarDecl::Create( |
2264 | 11 | Context, Block, From->getBeginLoc(), From->getLocation(), |
2265 | 11 | From->getIdentifier(), From->getType(), From->getTypeSourceInfo(), |
2266 | 11 | From->getStorageClass(), |
2267 | 11 | /*DefArg=*/nullptr)); |
2268 | 11 | } |
2269 | 31 | Block->setParams(BlockParams); |
2270 | | |
2271 | 31 | Block->setIsConversionFromLambda(true); |
2272 | | |
2273 | | // Add capture. The capture uses a fake variable, which doesn't correspond |
2274 | | // to any actual memory location. However, the initializer copy-initializes |
2275 | | // the lambda object. |
2276 | 31 | TypeSourceInfo *CapVarTSI = |
2277 | 31 | Context.getTrivialTypeSourceInfo(Src->getType()); |
2278 | 31 | VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, |
2279 | 31 | ConvLocation, nullptr, |
2280 | 31 | Src->getType(), CapVarTSI, |
2281 | 31 | SC_None); |
2282 | 31 | BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false, |
2283 | 31 | /*nested=*/false, /*copy=*/Init.get()); |
2284 | 31 | Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); |
2285 | | |
2286 | | // Add a fake function body to the block. IR generation is responsible |
2287 | | // for filling in the actual body, which cannot be expressed as an AST. |
2288 | 31 | Block->setBody(new (Context) CompoundStmt(ConvLocation)); |
2289 | | |
2290 | | // Create the block literal expression. |
2291 | 31 | Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); |
2292 | 31 | ExprCleanupObjects.push_back(Block); |
2293 | 31 | Cleanup.setExprNeedsCleanups(true); |
2294 | | |
2295 | 31 | return BuildBlock; |
2296 | 31 | } |
2297 | | |
2298 | 2.82k | static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) { |
2299 | 2.82k | if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) { |
2300 | 191 | while (FD->getInstantiatedFromMemberFunction()) |
2301 | 99 | FD = FD->getInstantiatedFromMemberFunction(); |
2302 | 92 | return FD; |
2303 | 92 | } |
2304 | | |
2305 | 2.73k | if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) |
2306 | 0 | return FD->getInstantiatedFromDecl(); |
2307 | | |
2308 | 2.73k | FunctionTemplateDecl *FTD = FD->getPrimaryTemplate(); |
2309 | 2.73k | if (!FTD) |
2310 | 2.67k | return nullptr; |
2311 | | |
2312 | 91 | while (55 FTD->getInstantiatedFromMemberTemplate()) |
2313 | 36 | FTD = FTD->getInstantiatedFromMemberTemplate(); |
2314 | | |
2315 | 55 | return FTD->getTemplatedDecl(); |
2316 | 2.73k | } |
2317 | | |
2318 | | Sema::LambdaScopeForCallOperatorInstantiationRAII:: |
2319 | | LambdaScopeForCallOperatorInstantiationRAII( |
2320 | | Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, |
2321 | | LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope) |
2322 | 1.47M | : FunctionScopeRAII(SemaRef) { |
2323 | 1.47M | if (!isLambdaCallOperator(FD)) { |
2324 | 1.47M | FunctionScopeRAII::disable(); |
2325 | 1.47M | return; |
2326 | 1.47M | } |
2327 | | |
2328 | 2.82k | SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD)); |
2329 | | |
2330 | 2.82k | FunctionDecl *Pattern = getPatternFunctionDecl(FD); |
2331 | 2.82k | if (Pattern) { |
2332 | 147 | SemaRef.addInstantiatedCapturesToScope(FD, Pattern, Scope, MLTAL); |
2333 | | |
2334 | 147 | FunctionDecl *ParentFD = FD; |
2335 | 263 | while (ShouldAddDeclsFromParentScope) { |
2336 | | |
2337 | 249 | ParentFD = |
2338 | 249 | dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(ParentFD)); |
2339 | 249 | Pattern = |
2340 | 249 | dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(Pattern)); |
2341 | | |
2342 | 249 | if (!FD || !Pattern) |
2343 | 133 | break; |
2344 | | |
2345 | 116 | SemaRef.addInstantiatedParametersToScope(ParentFD, Pattern, Scope, MLTAL); |
2346 | 116 | SemaRef.addInstantiatedLocalVarsToScope(ParentFD, Pattern, Scope); |
2347 | 116 | } |
2348 | 147 | } |
2349 | 2.82k | } |