clang 23.0.0git
SemaLambda.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ExprCXX.h"
19#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
24#include "clang/Sema/SemaARM.h"
25#include "clang/Sema/SemaCUDA.h"
28#include "clang/Sema/SemaSYCL.h"
29#include "clang/Sema/Template.h"
30#include "llvm/ADT/STLExtras.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Examines the FunctionScopeInfo stack to determine the nearest
36/// enclosing lambda (to the current lambda) that is 'capture-ready' for
37/// the variable referenced in the current lambda (i.e. \p VarToCapture).
38/// If successful, returns the index into Sema's FunctionScopeInfo stack
39/// of the capture-ready lambda's LambdaScopeInfo.
40///
41/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
42/// lambda - is on top) to determine the index of the nearest enclosing/outer
43/// lambda that is ready to capture the \p VarToCapture being referenced in
44/// the current lambda.
45/// As we climb down the stack, we want the index of the first such lambda -
46/// that is the lambda with the highest index that is 'capture-ready'.
47///
48/// A lambda 'L' is capture-ready for 'V' (var or this) if:
49/// - its enclosing context is non-dependent
50/// - and if the chain of lambdas between L and the lambda in which
51/// V is potentially used (i.e. the lambda at the top of the scope info
52/// stack), can all capture or have already captured V.
53/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
54///
55/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
56/// for whether it is 'capture-capable' (see
57/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
58/// capture.
59///
60/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
61/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
62/// is at the top of the stack and has the highest index.
63/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
64///
65/// \returns An UnsignedOrNone Index that if evaluates to 'true'
66/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
67/// lambda which is capture-ready. If the return value evaluates to 'false'
68/// then no lambda is capture-ready for \p VarToCapture.
69
72 ValueDecl *VarToCapture) {
73 // Label failure to capture.
74 const UnsignedOrNone NoLambdaIsCaptureReady = std::nullopt;
75
76 // Ignore all inner captured regions.
77 unsigned CurScopeIndex = FunctionScopes.size() - 1;
78 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
79 FunctionScopes[CurScopeIndex]))
80 --CurScopeIndex;
81 assert(
82 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
83 "The function on the top of sema's function-info stack must be a lambda");
84
85 // If VarToCapture is null, we are attempting to capture 'this'.
86 const bool IsCapturingThis = !VarToCapture;
87 const bool IsCapturingVariable = !IsCapturingThis;
88
89 // Start with the current lambda at the top of the stack (highest index).
90 DeclContext *EnclosingDC =
91 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
92
93 do {
95 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
96 // IF we have climbed down to an intervening enclosing lambda that contains
97 // the variable declaration - it obviously can/must not capture the
98 // variable.
99 // Since its enclosing DC is dependent, all the lambdas between it and the
100 // innermost nested lambda are dependent (otherwise we wouldn't have
101 // arrived here) - so we don't yet have a lambda that can capture the
102 // variable.
103 if (IsCapturingVariable &&
104 VarToCapture->getDeclContext()->Equals(EnclosingDC))
105 return NoLambdaIsCaptureReady;
106
107 // For an enclosing lambda to be capture ready for an entity, all
108 // intervening lambda's have to be able to capture that entity. If even
109 // one of the intervening lambda's is not capable of capturing the entity
110 // then no enclosing lambda can ever capture that entity.
111 // For e.g.
112 // const int x = 10;
113 // [=](auto a) { #1
114 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
115 // [=](auto c) { #3
116 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
117 // }; }; };
118 // If they do not have a default implicit capture, check to see
119 // if the entity has already been explicitly captured.
120 // If even a single dependent enclosing lambda lacks the capability
121 // to ever capture this variable, there is no further enclosing
122 // non-dependent lambda that can capture this variable.
124 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
125 return NoLambdaIsCaptureReady;
126 if (IsCapturingThis && !LSI->isCXXThisCaptured())
127 return NoLambdaIsCaptureReady;
128 }
129 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
130
131 assert(CurScopeIndex);
132 --CurScopeIndex;
133 } while (!EnclosingDC->isTranslationUnit() &&
134 EnclosingDC->isDependentContext() &&
135 isLambdaCallOperator(EnclosingDC));
136
137 assert(CurScopeIndex < (FunctionScopes.size() - 1));
138 // If the enclosingDC is not dependent, then the immediately nested lambda
139 // (one index above) is capture-ready.
140 if (!EnclosingDC->isDependentContext())
141 return CurScopeIndex + 1;
142 return NoLambdaIsCaptureReady;
143}
144
145/// Examines the FunctionScopeInfo stack to determine the nearest
146/// enclosing lambda (to the current lambda) that is 'capture-capable' for
147/// the variable referenced in the current lambda (i.e. \p VarToCapture).
148/// If successful, returns the index into Sema's FunctionScopeInfo stack
149/// of the capture-capable lambda's LambdaScopeInfo.
150///
151/// Given the current stack of lambdas being processed by Sema and
152/// the variable of interest, to identify the nearest enclosing lambda (to the
153/// current lambda at the top of the stack) that can truly capture
154/// a variable, it has to have the following two properties:
155/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
156/// - climb down the stack (i.e. starting from the innermost and examining
157/// each outer lambda step by step) checking if each enclosing
158/// lambda can either implicitly or explicitly capture the variable.
159/// Record the first such lambda that is enclosed in a non-dependent
160/// context. If no such lambda currently exists return failure.
161/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
162/// capture the variable by checking all its enclosing lambdas:
163/// - check if all outer lambdas enclosing the 'capture-ready' lambda
164/// identified above in 'a' can also capture the variable (this is done
165/// via tryCaptureVariable for variables and CheckCXXThisCapture for
166/// 'this' by passing in the index of the Lambda identified in step 'a')
167///
168/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
169/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
170/// is at the top of the stack.
171///
172/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
173///
174///
175/// \returns An UnsignedOrNone Index that if evaluates to 'true'
176/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
177/// lambda which is capture-capable. If the return value evaluates to 'false'
178/// then no lambda is capture-capable for \p VarToCapture.
179
182 ValueDecl *VarToCapture, Sema &S) {
183
184 const UnsignedOrNone NoLambdaIsCaptureCapable = std::nullopt;
185
186 const UnsignedOrNone OptionalStackIndex =
188 VarToCapture);
189 if (!OptionalStackIndex)
190 return NoLambdaIsCaptureCapable;
191
192 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
193 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
194 S.getCurGenericLambda()) &&
195 "The capture ready lambda for a potential capture can only be the "
196 "current lambda if it is a generic lambda");
197
198 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
199 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
200
201 // If VarToCapture is null, we are attempting to capture 'this'
202 const bool IsCapturingThis = !VarToCapture;
203 const bool IsCapturingVariable = !IsCapturingThis;
204
205 if (IsCapturingVariable) {
206 // Check if the capture-ready lambda can truly capture the variable, by
207 // checking whether all enclosing lambdas of the capture-ready lambda allow
208 // the capture - i.e. make sure it is capture-capable.
209 QualType CaptureType, DeclRefType;
210 const bool CanCaptureVariable = !S.tryCaptureVariable(
211 VarToCapture,
212 /*ExprVarIsUsedInLoc*/ SourceLocation(), TryCaptureKind::Implicit,
213 /*EllipsisLoc*/ SourceLocation(),
214 /*BuildAndDiagnose*/ false, CaptureType, DeclRefType,
215 &IndexOfCaptureReadyLambda);
216 if (!CanCaptureVariable)
217 return NoLambdaIsCaptureCapable;
218 } else {
219 // Check if the capture-ready lambda can truly capture 'this' by checking
220 // whether all enclosing lambdas of the capture-ready lambda can capture
221 // 'this'.
222 const bool CanCaptureThis =
224 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
225 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
226 &IndexOfCaptureReadyLambda);
227 if (!CanCaptureThis)
228 return NoLambdaIsCaptureCapable;
229 }
230 return IndexOfCaptureReadyLambda;
231}
232
233static inline TemplateParameterList *
235 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
237 SemaRef.Context,
238 /*Begin loc of the lambda expression*/ LSI->IntroducerRange.getBegin(),
239 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
240 LSI->TemplateParams,
241 /*R angle loc*/ LSI->ExplicitTemplateParamsRange.getEnd(),
242 LSI->RequiresClause.get());
243 }
244 return LSI->GLTemplateParameterList;
245}
246
249 unsigned LambdaDependencyKind,
250 LambdaCaptureDefault CaptureDefault) {
252
253 bool IsGenericLambda =
255 // Start constructing the lambda class.
257 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
258 IsGenericLambda, CaptureDefault);
259 DC->addDecl(Class);
260
261 return Class;
262}
263
264std::tuple<MangleNumberingContext *, Decl *>
266 // Compute the context for allocating mangling numbers in the current
267 // expression, if the ABI requires them.
268 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
269
270 enum ContextKind {
271 Normal,
273 DataMember,
274 InlineVariable,
275 TemplatedVariable,
276 ExternallyVisibleVariableInModulePurview,
277 Concept,
278 } Kind = Normal;
279
280 bool IsInNonspecializedTemplate =
281 inTemplateInstantiation() || CurContext->isDependentContext();
282
283 // Checks if a VarDecl or FunctionDecl is from a module purview and externally
284 // visible. These Decls should be treated as "inline" for the purpose of
285 // mangling in the code below.
286 //
287 // See discussion in https://github.com/itanium-cxx-abi/cxx-abi/issues/186
288 //
289 // zygoloid:
290 // Yeah, I think the only cases left where lambdas don't need a
291 // mangling are when they have (effectively) internal linkage or
292 // appear in a non-inline function in a non-module translation unit.
293 static constexpr auto IsExternallyVisibleInModulePurview =
294 [](const NamedDecl *ND) -> bool {
295 return (ND->isInNamedModule() || ND->isFromGlobalModule()) &&
296 ND->isExternallyVisible();
297 };
298
299 // Default arguments of member function parameters that appear in a class
300 // definition, as well as the initializers of data members, receive special
301 // treatment. Identify them.
302 Kind = [&]() {
303 if (!ManglingContextDecl)
304 return Normal;
305
306 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
307 if (const DeclContext *LexicalDC
308 = Param->getDeclContext()->getLexicalParent())
309 if (LexicalDC->isRecord())
310 return DefaultArgument;
311 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
312 if (Var->getMostRecentDecl()->isInline())
313 return InlineVariable;
314
315 if (IsExternallyVisibleInModulePurview(Var))
316 return ExternallyVisibleVariableInModulePurview;
317
318 if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
319 return TemplatedVariable;
320
321 if (Var->getDescribedVarTemplate())
322 return TemplatedVariable;
323
324 if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
325 if (!VTS->isExplicitSpecialization())
326 return TemplatedVariable;
327 }
328 } else if (isa<FieldDecl>(ManglingContextDecl)) {
329 return DataMember;
330 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
331 return Concept;
332 }
333
334 return Normal;
335 }();
336
337 // Determine whether the given context is or is enclosed in a function that
338 // requires Decl's inside to be mangled, so either:
339 // - an inline function
340 // - or a function in a module purview that is externally visible
341 static constexpr auto IsInFunctionThatRequiresMangling =
342 [](const DeclContext *DC) -> bool {
343 while (!DC->isFileContext()) {
344 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
345 if (FD->isInlined() || IsExternallyVisibleInModulePurview(FD))
346 return true;
347
348 DC = DC->getLexicalParent();
349 }
350
351 return false;
352 };
353
354 // Itanium ABI [5.1.8]:
355 // In the following contexts [...] the one-definition rule requires closure
356 // types in different translation units to "correspond":
357 switch (Kind) {
358 case Normal: {
359 // -- the bodies of inline or templated functions
360 // -- the bodies of externally visible functions in a module purview
361 // (note: this is not yet part of the Itanium ABI, see the linked Github
362 // discussion above)
363 if ((IsInNonspecializedTemplate &&
364 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
365 IsInFunctionThatRequiresMangling(CurContext)) {
366 while (auto *CD = dyn_cast<CapturedDecl>(DC))
367 DC = CD->getParent();
368 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
369 }
370
371 return std::make_tuple(nullptr, nullptr);
372 }
373
374 case Concept:
375 // Concept definitions aren't code generated and thus aren't mangled,
376 // however the ManglingContextDecl is important for the purposes of
377 // re-forming the template argument list of the lambda for constraint
378 // evaluation.
379 case DataMember:
380 // -- default member initializers
381 case DefaultArgument:
382 // -- default arguments appearing in class definitions
383 case InlineVariable:
384 case ExternallyVisibleVariableInModulePurview:
385 case TemplatedVariable:
386 // -- the initializers of inline or templated variables
387 // -- the initializers of externally visible variables in a module purview
388 // (note: this is not yet part of the Itanium ABI, see the linked Github
389 // discussion above)
390 return std::make_tuple(
391 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
392 ManglingContextDecl),
393 ManglingContextDecl);
394 }
395
396 llvm_unreachable("unexpected context");
397}
398
399static QualType
401 TemplateParameterList *TemplateParams,
402 TypeSourceInfo *MethodTypeInfo) {
403 assert(MethodTypeInfo && "expected a non null type");
404
405 QualType MethodType = MethodTypeInfo->getType();
406 // If a lambda appears in a dependent context or is a generic lambda (has
407 // template parameters) and has an 'auto' return type, deduce it to a
408 // dependent type.
409 if (Class->isDependentContext() || TemplateParams) {
410 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
411 QualType Result = FPT->getReturnType();
412 if (Result->isUndeducedType()) {
413 Result = S.SubstAutoTypeDependent(Result);
414 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
415 FPT->getExtProtoInfo());
416 }
417 }
418 return MethodType;
419}
420
421// [C++2b] [expr.prim.lambda.closure] p4
422// Given a lambda with a lambda-capture, the type of the explicit object
423// parameter, if any, of the lambda's function call operator (possibly
424// instantiated from a function call operator template) shall be either:
425// - the closure type,
426// - class type publicly and unambiguously derived from the closure type, or
427// - a reference to a possibly cv-qualified such type.
431 return false;
432 CXXRecordDecl *RD = Method->getParent();
433 if (Method->getType()->isDependentType())
434 return false;
435 if (RD->isCapturelessLambda())
436 return false;
437
438 ParmVarDecl *Param = Method->getParamDecl(0);
439 QualType ExplicitObjectParameterType = Param->getType()
440 .getNonReferenceType()
441 .getUnqualifiedType()
442 .getDesugaredType(getASTContext());
444 if (LambdaType == ExplicitObjectParameterType)
445 return false;
446
447 // Don't check the same instantiation twice.
448 //
449 // If this call operator is ill-formed, there is no point in issuing
450 // a diagnostic every time it is called because the problem is in the
451 // definition of the derived type, not at the call site.
452 //
453 // FIXME: Move this check to where we instantiate the method? This should
454 // be possible, but the naive approach of just marking the method as invalid
455 // leads to us emitting more diagnostics than we should have to for this case
456 // (1 error here *and* 1 error about there being no matching overload at the
457 // call site). It might be possible to avoid that by also checking if there
458 // is an empty cast path for the method stored in the context (signalling that
459 // we've already diagnosed it) and then just not building the call, but that
460 // doesn't really seem any simpler than diagnosing it at the call site...
461 auto [It, Inserted] = Context.LambdaCastPaths.try_emplace(Method);
462 if (!Inserted)
463 return It->second.empty();
464
465 CXXCastPath &Path = It->second;
466 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
467 /*DetectVirtual=*/false);
468 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
469 Paths)) {
470 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
471 << ExplicitObjectParameterType;
472 return true;
473 }
474
475 if (Paths.isAmbiguous(LambdaType)) {
476 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
477 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
478 << LambdaType << PathsDisplay;
479 return true;
480 }
481
482 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
483 Paths.front(),
484 diag::err_explicit_object_lambda_inaccessible_base))
485 return true;
486
487 BuildBasePathArray(Paths, Path);
488 return false;
489}
490
493 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
494 ContextRAII ManglingContext(*this, Class->getDeclContext());
495
496 auto getMangleNumberingContext =
497 [this](CXXRecordDecl *Class,
498 Decl *ManglingContextDecl) -> MangleNumberingContext * {
499 // Get mangle numbering context if there's any extra decl context.
500 if (ManglingContextDecl)
501 return &Context.getManglingNumberContext(
502 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
503 // Otherwise, from that lambda's decl context.
504 auto DC = Class->getDeclContext();
505 while (auto *CD = dyn_cast<CapturedDecl>(DC))
506 DC = CD->getParent();
507 return &Context.getManglingNumberContext(DC);
508 };
509
511 Decl *ContextDecl;
512 std::tie(MCtx, ContextDecl) =
513 getCurrentMangleNumberContext(Class->getDeclContext());
514 // getManglingNumber(Method) below may trigger mangling of dependent types
515 // that reference init-captures. Publish the lambda context declaration early
516 // so such mangling can resolve the surrounding context without recursing
517 // through the lambda call operator. This avoids publishing provisional
518 // numbering state before final numbering is assigned below.
519 if (ContextDecl)
520 Class->setLambdaContextDecl(ContextDecl);
521 if (NumberingOverride) {
522 Class->setLambdaNumbering(*NumberingOverride);
523 return;
524 }
525
527 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
528 getLangOpts().SYCLIsHost)) {
529 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
530 // ODR. Both device- and host-compilation need to have a consistent naming
531 // on kernel functions. As lambdas are potential part of these `__global__`
532 // function names, they needs numbering following ODR.
533 // Also force for SYCL, since we need this for the
534 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
535 // mangling.
536 MCtx = getMangleNumberingContext(Class, ContextDecl);
537 assert(MCtx && "Retrieving mangle numbering context failed!");
538 Numbering.HasKnownInternalLinkage = true;
539 }
540 if (MCtx) {
541 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
542 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
544 Class->setLambdaNumbering(Numbering);
545
546 if (auto *Source =
547 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
548 Source->AssignedLambdaNumbering(Class);
549 }
550}
551
553 CXXMethodDecl *CallOperator,
554 bool ExplicitResultType) {
555 if (ExplicitResultType) {
556 LSI->HasImplicitReturnType = false;
557 LSI->ReturnType = CallOperator->getReturnType();
558 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
559 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
560 diag::err_lambda_incomplete_result);
561 } else {
562 LSI->HasImplicitReturnType = true;
563 }
564}
565
567 SourceRange IntroducerRange,
568 LambdaCaptureDefault CaptureDefault,
569 SourceLocation CaptureDefaultLoc,
570 bool ExplicitParams, bool Mutable) {
571 LSI->CallOperator = CallOperator;
572 CXXRecordDecl *LambdaClass = CallOperator->getParent();
573 LSI->Lambda = LambdaClass;
574 if (CaptureDefault == LCD_ByCopy)
575 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
576 else if (CaptureDefault == LCD_ByRef)
577 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
578 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
579 LSI->IntroducerRange = IntroducerRange;
580 LSI->ExplicitParams = ExplicitParams;
581 LSI->Mutable = Mutable;
582}
583
587
589 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
590 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
591 ExprResult RequiresClause) {
593 assert(LSI && "Expected a lambda scope");
594 assert(LSI->NumExplicitTemplateParams == 0 &&
595 "Already acted on explicit template parameters");
596 assert(LSI->TemplateParams.empty() &&
597 "Explicit template parameters should come "
598 "before invented (auto) ones");
599 assert(!TParams.empty() &&
600 "No template parameters to act on");
601 LSI->TemplateParams.append(TParams.begin(), TParams.end());
602 LSI->NumExplicitTemplateParams = TParams.size();
603 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
604 LSI->RequiresClause = RequiresClause;
605}
606
607/// If this expression is an enumerator-like expression of some type
608/// T, return the type T; otherwise, return null.
609///
610/// Pointer comparisons on the result here should always work because
611/// it's derived from either the parent of an EnumConstantDecl
612/// (i.e. the definition) or the declaration returned by
613/// EnumType::getDecl() (i.e. the definition).
615 // An expression is an enumerator-like expression of type T if,
616 // ignoring parens and parens-like expressions:
617 E = E->IgnoreParens();
618
619 // - it is an enumerator whose enum type is T or
620 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
621 if (EnumConstantDecl *D
622 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
623 return cast<EnumDecl>(D->getDeclContext());
624 }
625 return nullptr;
626 }
627
628 // - it is a comma expression whose RHS is an enumerator-like
629 // expression of type T or
630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
631 if (BO->getOpcode() == BO_Comma)
632 return findEnumForBlockReturn(BO->getRHS());
633 return nullptr;
634 }
635
636 // - it is a statement-expression whose value expression is an
637 // enumerator-like expression of type T or
638 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
639 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
640 return findEnumForBlockReturn(last);
641 return nullptr;
642 }
643
644 // - it is a ternary conditional operator (not the GNU ?:
645 // extension) whose second and third operands are
646 // enumerator-like expressions of type T or
647 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
648 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
649 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
650 return ED;
651 return nullptr;
652 }
653
654 // (implicitly:)
655 // - it is an implicit integral conversion applied to an
656 // enumerator-like expression of type T or
657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
658 // We can sometimes see integral conversions in valid
659 // enumerator-like expressions.
660 if (ICE->getCastKind() == CK_IntegralCast)
661 return findEnumForBlockReturn(ICE->getSubExpr());
662
663 // Otherwise, just rely on the type.
664 }
665
666 // - it is an expression of that formal enum type.
667 if (auto *ED = E->getType()->getAsEnumDecl())
668 return ED;
669
670 // Otherwise, nope.
671 return nullptr;
672}
673
674/// Attempt to find a type T for which the returned expression of the
675/// given statement is an enumerator-like expression of that type.
677 if (Expr *retValue = ret->getRetValue())
678 return findEnumForBlockReturn(retValue);
679 return nullptr;
680}
681
682/// Attempt to find a common type T for which all of the returned
683/// expressions in a block are enumerator-like expressions of that
684/// type.
686 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
687
688 // Try to find one for the first return.
690 if (!ED) return nullptr;
691
692 // Check that the rest of the returns have the same enum.
693 for (++i; i != e; ++i) {
694 if (findEnumForBlockReturn(*i) != ED)
695 return nullptr;
696 }
697
698 // Never infer an anonymous enum type.
699 if (!ED->hasNameForLinkage()) return nullptr;
700
701 return ED;
702}
703
704/// Adjust the given return statements so that they formally return
705/// the given type. It should require, at most, an IntegralCast.
707 QualType returnType) {
709 i = returns.begin(), e = returns.end(); i != e; ++i) {
710 ReturnStmt *ret = *i;
711 Expr *retValue = ret->getRetValue();
712 if (S.Context.hasSameType(retValue->getType(), returnType))
713 continue;
714
715 // Right now we only support integral fixup casts.
716 assert(returnType->isIntegralOrUnscopedEnumerationType());
717 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
718
719 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
720
721 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
722 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
723 /*base path*/ nullptr, VK_PRValue,
725 if (cleanups) {
726 cleanups->setSubExpr(E);
727 } else {
728 ret->setRetValue(E);
729 }
730 }
731}
732
734 assert(CSI.HasImplicitReturnType);
735 // If it was ever a placeholder, it had to been deduced to DependentTy.
736 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
737 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
738 "lambda expressions use auto deduction in C++14 onwards");
739
740 // C++ core issue 975:
741 // If a lambda-expression does not include a trailing-return-type,
742 // it is as if the trailing-return-type denotes the following type:
743 // - if there are no return statements in the compound-statement,
744 // or all return statements return either an expression of type
745 // void or no expression or braced-init-list, the type void;
746 // - otherwise, if all return statements return an expression
747 // and the types of the returned expressions after
748 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
749 // array-to-pointer conversion (4.2 [conv.array]), and
750 // function-to-pointer conversion (4.3 [conv.func]) are the
751 // same, that common type;
752 // - otherwise, the program is ill-formed.
753 //
754 // C++ core issue 1048 additionally removes top-level cv-qualifiers
755 // from the types of returned expressions to match the C++14 auto
756 // deduction rules.
757 //
758 // In addition, in blocks in non-C++ modes, if all of the return
759 // statements are enumerator-like expressions of some type T, where
760 // T has a name for linkage, then we infer the return type of the
761 // block to be that type.
762
763 // First case: no return statements, implicit void return type.
764 ASTContext &Ctx = getASTContext();
765 if (CSI.Returns.empty()) {
766 // It's possible there were simply no /valid/ return statements.
767 // In this case, the first one we found may have at least given us a type.
768 if (CSI.ReturnType.isNull())
769 CSI.ReturnType = Ctx.VoidTy;
770 return;
771 }
772
773 // Second case: at least one return statement has dependent type.
774 // Delay type checking until instantiation.
775 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
776 if (CSI.ReturnType->isDependentType())
777 return;
778
779 // Try to apply the enum-fuzz rule.
780 if (!getLangOpts().CPlusPlus) {
781 assert(isa<BlockScopeInfo>(CSI));
783 if (ED) {
784 CSI.ReturnType = Context.getCanonicalTagType(ED);
786 return;
787 }
788 }
789
790 // Third case: only one return statement. Don't bother doing extra work!
791 if (CSI.Returns.size() == 1)
792 return;
793
794 // General case: many return statements.
795 // Check that they all have compatible return types.
796
797 // We require the return types to strictly match here.
798 // Note that we've already done the required promotions as part of
799 // processing the return statement.
800 for (const ReturnStmt *RS : CSI.Returns) {
801 const Expr *RetE = RS->getRetValue();
802
803 QualType ReturnType =
804 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
805 if (Context.getCanonicalFunctionResultType(ReturnType) ==
806 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
807 // Use the return type with the strictest possible nullability annotation.
808 auto RetTyNullability = ReturnType->getNullability();
809 auto BlockNullability = CSI.ReturnType->getNullability();
810 if (BlockNullability &&
811 (!RetTyNullability ||
812 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
813 CSI.ReturnType = ReturnType;
814 continue;
815 }
816
817 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
818 // TODO: It's possible that the *first* return is the divergent one.
819 Diag(RS->getBeginLoc(),
820 diag::err_typecheck_missing_return_type_incompatible)
821 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
822 // Continue iterating so that we keep emitting diagnostics.
823 }
824}
825
827 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
828 UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
829 Expr *&Init) {
830 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
831 // deduce against.
832 QualType DeductType = Context.getAutoDeductType();
833 TypeLocBuilder TLB;
834 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
835 TL.setNameLoc(Loc);
836 if (ByRef) {
837 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
838 assert(!DeductType.isNull() && "can't build reference to auto");
839 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
840 }
841 if (EllipsisLoc.isValid()) {
842 if (Init->containsUnexpandedParameterPack()) {
843 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
844 ? diag::warn_cxx17_compat_init_capture_pack
845 : diag::ext_init_capture_pack);
846 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
847 /*ExpectPackInType=*/false);
848 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
849 } else {
850 // Just ignore the ellipsis for now and form a non-pack variable. We'll
851 // diagnose this later when we try to capture it.
852 }
853 }
854 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
855
856 // Deduce the type of the init capture.
858 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
859 SourceRange(Loc, Loc), IsDirectInit, Init);
860 if (DeducedType.isNull())
861 return QualType();
862
863 // Are we a non-list direct initialization?
864 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
865
866 // Perform initialization analysis and ensure any implicit conversions
867 // (such as lvalue-to-rvalue) are enforced.
868 InitializedEntity Entity =
869 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
870 InitializationKind Kind =
871 IsDirectInit
872 ? (CXXDirectInit ? InitializationKind::CreateDirect(
873 Loc, Init->getBeginLoc(), Init->getEndLoc())
875 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
876
877 MultiExprArg Args = Init;
878 if (CXXDirectInit)
879 Args =
880 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
881 QualType DclT;
882 InitializationSequence InitSeq(*this, Entity, Kind, Args);
883 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
884
885 if (Result.isInvalid())
886 return QualType();
887
888 Init = Result.getAs<Expr>();
889 return DeducedType;
890}
891
893 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
894 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
895 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
896 // rather than reconstructing it here.
897 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
898 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
899 PETL.setEllipsisLoc(EllipsisLoc);
900
901 // Create a dummy variable representing the init-capture. This is not actually
902 // used as a variable, and only exists as a way to name and refer to the
903 // init-capture.
904 // FIXME: Pass in separate source locations for '&' and identifier.
905 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
906 InitCaptureType, TSI, SC_Auto);
907 NewVD->setInitCapture(true);
908 NewVD->setReferenced(true);
909 // FIXME: Pass in a VarDecl::InitializationStyle.
910 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
911 NewVD->markUsed(Context);
912 NewVD->setInit(Init);
913 if (NewVD->isParameterPack())
914 getCurLambda()->LocalPacks.push_back(NewVD);
915 return NewVD;
916}
917
918void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
919 assert(Var->isInitCapture() && "init capture flag should be set");
920 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
921 /*isNested=*/false, Var->getLocation(), SourceLocation(),
922 Var->getType(), /*Invalid=*/false);
923}
924
925// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
926// check that the current lambda is in a consistent or fully constructed state.
928 assert(!S.FunctionScopes.empty());
930}
931
932static TypeSourceInfo *
934 // C++11 [expr.prim.lambda]p4:
935 // If a lambda-expression does not include a lambda-declarator, it is as
936 // if the lambda-declarator were ().
938 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
939 EPI.HasTrailingReturn = true;
940 EPI.TypeQuals.addConst();
942 if (AS != LangAS::Default)
944
945 // C++1y [expr.prim.lambda]:
946 // The lambda return type is 'auto', which is replaced by the
947 // trailing-return type if provided and/or deduced from 'return'
948 // statements
949 // We don't do this before C++1y, because we don't support deduced return
950 // types there.
951 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
954 QualType MethodTy =
955 S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, {}, EPI);
956 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
957}
958
960 Declarator &ParamInfo, Scope *CurScope,
961 SourceLocation Loc,
962 bool &ExplicitResultType) {
963
964 ExplicitResultType = false;
965
966 assert(
967 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
970 "Unexpected storage specifier");
971 bool IsLambdaStatic =
973
974 TypeSourceInfo *MethodTyInfo;
975
976 if (ParamInfo.getNumTypeObjects() == 0) {
977 MethodTyInfo = getDummyLambdaType(S, Loc);
978 } else {
979 // Check explicit parameters
980 S.CheckExplicitObjectLambda(ParamInfo);
981
983
984 bool HasExplicitObjectParameter =
986
987 ExplicitResultType = FTI.hasTrailingReturnType();
988 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
989 !HasExplicitObjectParameter)
991
992 if (ExplicitResultType && S.getLangOpts().HLSL) {
993 QualType RetTy = FTI.getTrailingReturnType().get();
994 if (!RetTy.isNull()) {
995 // HLSL does not support specifying an address space on a lambda return
996 // type.
997 LangAS AddressSpace = RetTy.getAddressSpace();
998 if (AddressSpace != LangAS::Default)
1000 diag::err_return_value_with_address_space);
1001 }
1002 }
1003
1004 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
1005 assert(MethodTyInfo && "no type from lambda-declarator");
1006
1007 // Check for unexpanded parameter packs in the method type.
1008 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
1009 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
1011 }
1012 return MethodTyInfo;
1013}
1014
1017
1018 // C++20 [expr.prim.lambda.closure]p3:
1019 // The closure type for a lambda-expression has a public inline function
1020 // call operator (for a non-generic lambda) or function call operator
1021 // template (for a generic lambda) whose parameters and return type are
1022 // described by the lambda-expression's parameter-declaration-clause
1023 // and trailing-return-type respectively.
1024 DeclarationName MethodName =
1025 Context.DeclarationNames.getCXXOperatorName(OO_Call);
1026 DeclarationNameLoc MethodNameLoc =
1030 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
1031 MethodNameLoc),
1032 QualType(), /*Tinfo=*/nullptr, SC_None,
1033 getCurFPFeatures().isFPConstrained(),
1034 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
1035 /*TrailingRequiresClause=*/{});
1036 Method->setAccess(AS_public);
1037 return Method;
1038}
1039
1041 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1042 TemplateParameterList *TemplateParams) {
1043 assert(TemplateParams && "no template parameters");
1045 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1046 TemplateParams, CallOperator);
1047 TemplateMethod->setAccess(AS_public);
1048 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1049}
1050
1053 SourceLocation CallOperatorLoc,
1054 const AssociatedConstraint &TrailingRequiresClause,
1055 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1057 bool HasExplicitResultType) {
1058
1060
1061 if (TrailingRequiresClause)
1062 Method->setTrailingRequiresClause(TrailingRequiresClause);
1063
1064 TemplateParameterList *TemplateParams =
1066
1067 DeclContext *DC = Method->getLexicalDeclContext();
1068 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1069 // lexical context of the Method. Do so.
1070 Method->setLexicalDeclContext(LSI->Lambda);
1071 if (TemplateParams) {
1072 FunctionTemplateDecl *TemplateMethod =
1073 Method->getDescribedFunctionTemplate();
1074 assert(TemplateMethod &&
1075 "AddTemplateParametersToLambdaCallOperator should have been called");
1076
1077 LSI->Lambda->addDecl(TemplateMethod);
1078 TemplateMethod->setLexicalDeclContext(DC);
1079 } else {
1080 LSI->Lambda->addDecl(Method);
1081 }
1082 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1083 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1084
1085 Method->setLexicalDeclContext(DC);
1086 Method->setLocation(LambdaLoc);
1087 Method->setInnerLocStart(CallOperatorLoc);
1088 Method->setTypeSourceInfo(MethodTyInfo);
1089 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1090 TemplateParams, MethodTyInfo));
1091 Method->setConstexprKind(ConstexprKind);
1092 Method->setStorageClass(SC);
1093 if (!Params.empty()) {
1094 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1095 Method->setParams(Params);
1096 for (auto P : Method->parameters()) {
1097 assert(P && "null in a parameter list");
1098 P->setOwningFunction(Method);
1099 }
1100 }
1101
1102 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1103}
1104
1106 Scope *CurrentScope) {
1107
1109 assert(LSI && "LambdaScopeInfo should be on stack!");
1110
1111 if (Intro.Default == LCD_ByCopy)
1112 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1113 else if (Intro.Default == LCD_ByRef)
1114 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1115 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1116 LSI->IntroducerRange = Intro.Range;
1117 LSI->AfterParameterList = false;
1118
1119 assert(LSI->NumExplicitTemplateParams == 0);
1120
1121 // Determine if we're within a context where we know that the lambda will
1122 // be dependent, because there are template parameters in scope.
1123 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1125 if (CurScope->getTemplateParamParent() != nullptr) {
1126 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1127 } else if (Scope *ParentScope = CurScope->getParent()) {
1128 // Given a lambda defined inside a requires expression,
1129 //
1130 // struct S {
1131 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1132 // {}
1133 // };
1134 //
1135 // The parameter var is not injected into the function Decl at the point of
1136 // parsing lambda. In such scenarios, perceiving it as dependent could
1137 // result in the constraint being evaluated, which matches what GCC does.
1138 Scope *LookupScope = ParentScope;
1139 while (LookupScope->getEntity() &&
1140 LookupScope->getEntity()->isRequiresExprBody())
1141 LookupScope = LookupScope->getParent();
1142
1143 if (LookupScope != ParentScope &&
1144 LookupScope->isFunctionDeclarationScope() &&
1145 llvm::any_of(LookupScope->decls(), [](Decl *D) {
1146 return isa<ParmVarDecl>(D) &&
1147 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1148 }))
1149 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1150 }
1151
1153 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1154 LSI->Lambda = Class;
1155
1157 LSI->CallOperator = Method;
1158 // Temporarily set the lexical declaration context to the current
1159 // context, so that the Scope stack matches the lexical nesting.
1160 Method->setLexicalDeclContext(CurContext);
1161
1162 PushDeclContext(CurScope, Method);
1163
1164 bool ContainsUnexpandedParameterPack = false;
1165
1166 // Distinct capture names, for diagnostics.
1167 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1168
1169 // Handle explicit captures.
1170 SourceLocation PrevCaptureLoc =
1171 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1172 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1173 PrevCaptureLoc = C->Loc, ++C) {
1174 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1175 if (C->Kind == LCK_StarThis)
1176 Diag(C->Loc, !getLangOpts().CPlusPlus17
1177 ? diag::ext_star_this_lambda_capture_cxx17
1178 : diag::warn_cxx14_compat_star_this_lambda_capture);
1179
1180 // C++11 [expr.prim.lambda]p8:
1181 // An identifier or this shall not appear more than once in a
1182 // lambda-capture.
1183 if (LSI->isCXXThisCaptured()) {
1184 Diag(C->Loc, diag::err_capture_more_than_once)
1185 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1187 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1188 continue;
1189 }
1190
1191 // C++20 [expr.prim.lambda]p8:
1192 // If a lambda-capture includes a capture-default that is =,
1193 // each simple-capture of that lambda-capture shall be of the form
1194 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1195 // redundant but accepted for compatibility with ISO C++14. --end note ]
1196 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1197 Diag(C->Loc, !getLangOpts().CPlusPlus20
1198 ? diag::ext_equals_this_lambda_capture_cxx20
1199 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1200
1201 // C++11 [expr.prim.lambda]p12:
1202 // If this is captured by a local lambda expression, its nearest
1203 // enclosing function shall be a non-static member function.
1204 QualType ThisCaptureType = getCurrentThisType();
1205 if (ThisCaptureType.isNull()) {
1206 Diag(C->Loc, diag::err_this_capture) << true;
1207 continue;
1208 }
1209
1210 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1211 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1212 C->Kind == LCK_StarThis);
1213 if (!LSI->Captures.empty())
1214 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1215 continue;
1216 }
1217
1218 assert(C->Id && "missing identifier for capture");
1219
1220 if (C->Init.isInvalid())
1221 continue;
1222
1223 ValueDecl *Var = nullptr;
1224 if (C->Init.isUsable()) {
1226 ? diag::warn_cxx11_compat_init_capture
1227 : diag::ext_init_capture);
1228
1229 // If the initializer expression is usable, but the InitCaptureType
1230 // is not, then an error has occurred - so ignore the capture for now.
1231 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1232 // FIXME: we should create the init capture variable and mark it invalid
1233 // in this case.
1234 if (C->InitCaptureType.get().isNull())
1235 continue;
1236
1237 if (C->Init.get()->containsUnexpandedParameterPack() &&
1238 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1240
1241 unsigned InitStyle;
1242 switch (C->InitKind) {
1244 llvm_unreachable("not an init-capture?");
1246 InitStyle = VarDecl::CInit;
1247 break;
1249 InitStyle = VarDecl::CallInit;
1250 break;
1252 InitStyle = VarDecl::ListInit;
1253 break;
1254 }
1255 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1256 C->EllipsisLoc, C->Id, InitStyle,
1257 C->Init.get(), Method);
1258 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1259 if (auto *V = dyn_cast<VarDecl>(Var))
1260 CheckShadow(CurrentScope, V);
1261 PushOnScopeChains(Var, CurrentScope, false);
1262 } else {
1263 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1264 "init capture has valid but null init?");
1265
1266 // C++11 [expr.prim.lambda]p8:
1267 // If a lambda-capture includes a capture-default that is &, the
1268 // identifiers in the lambda-capture shall not be preceded by &.
1269 // If a lambda-capture includes a capture-default that is =, [...]
1270 // each identifier it contains shall be preceded by &.
1271 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1272 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1274 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1275 continue;
1276 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1277 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1279 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1280 continue;
1281 }
1282
1283 // C++11 [expr.prim.lambda]p10:
1284 // The identifiers in a capture-list are looked up using the usual
1285 // rules for unqualified name lookup (3.4.1)
1286 DeclarationNameInfo Name(C->Id, C->Loc);
1287 LookupResult R(*this, Name, LookupOrdinaryName);
1288 LookupName(R, CurScope);
1289 if (R.isAmbiguous())
1290 continue;
1291 if (R.empty()) {
1292 // FIXME: Disable corrections that would add qualification?
1293 CXXScopeSpec ScopeSpec;
1294 DeclFilterCCC<VarDecl> Validator{};
1295 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1296 continue;
1297 }
1298
1299 if (auto *BD = R.getAsSingle<BindingDecl>())
1300 Var = BD;
1301 else if (R.getAsSingle<FieldDecl>()) {
1302 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1303 << C->Id;
1304 continue;
1305 } else
1306 Var = R.getAsSingle<VarDecl>();
1307 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1308 continue;
1309 }
1310
1311 // C++11 [expr.prim.lambda]p10:
1312 // [...] each such lookup shall find a variable with automatic storage
1313 // duration declared in the reaching scope of the local lambda expression.
1314 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1315 if (!Var) {
1316 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1317 continue;
1318 }
1319
1320 // C++11 [expr.prim.lambda]p8:
1321 // An identifier or this shall not appear more than once in a
1322 // lambda-capture.
1323 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1324 !Inserted) {
1325 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1326 !Var->isInitCapture()) {
1327 Diag(C->Loc, diag::err_capture_more_than_once)
1328 << C->Id << It->second->getBeginLoc()
1330 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1331 Var->setInvalidDecl();
1332 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1334 } else {
1335 // Previous capture captured something different (one or both was
1336 // an init-capture): no fixit.
1337 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1338 continue;
1339 }
1340 }
1341
1342 // Ignore invalid decls; they'll just confuse the code later.
1343 if (Var->isInvalidDecl())
1344 continue;
1345
1346 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1347
1348 if (!Underlying->hasLocalStorage()) {
1349 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1350 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1351 continue;
1352 }
1353
1354 // C++11 [expr.prim.lambda]p23:
1355 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1356 SourceLocation EllipsisLoc;
1357 if (C->EllipsisLoc.isValid()) {
1358 if (Var->isParameterPack()) {
1359 EllipsisLoc = C->EllipsisLoc;
1360 } else {
1361 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1362 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1363 : SourceRange(C->Loc));
1364
1365 // Just ignore the ellipsis.
1366 }
1367 } else if (Var->isParameterPack()) {
1368 ContainsUnexpandedParameterPack = true;
1369 }
1370
1371 if (C->Init.isUsable()) {
1372 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1373 } else {
1374 TryCaptureKind Kind = C->Kind == LCK_ByRef
1377 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1378 }
1379 if (!LSI->Captures.empty())
1380 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1381 }
1383 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1385}
1386
1388 SourceLocation MutableLoc) {
1389
1391 LSI->Mutable = MutableLoc.isValid();
1392 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1393
1394 // C++11 [expr.prim.lambda]p9:
1395 // A lambda-expression whose smallest enclosing scope is a block scope is a
1396 // local lambda expression; any other lambda expression shall not have a
1397 // capture-default or simple-capture in its lambda-introducer.
1398 //
1399 // For simple-captures, this is covered by the check below that any named
1400 // entity is a variable that can be captured.
1401 //
1402 // For DR1632, we also allow a capture-default in any context where we can
1403 // odr-use 'this' (in particular, in a default initializer for a non-static
1404 // data member).
1405 if (Intro.Default != LCD_None &&
1406 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1407 (getCurrentThisType().isNull() ||
1408 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1409 /*BuildAndDiagnose=*/false)))
1410 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1411}
1412
1416 PushDeclContext(LambdaScope, LSI->CallOperator);
1417
1418 for (const DeclaratorChunk::ParamInfo &P : Params) {
1419 auto *Param = cast<ParmVarDecl>(P.Param);
1420 Param->setOwningFunction(LSI->CallOperator);
1421 if (Param->getIdentifier())
1422 PushOnScopeChains(Param, LambdaScope, false);
1423 }
1424
1425 // After the parameter list, we may parse a noexcept/requires/trailing return
1426 // type which need to know whether the call operator constiture a dependent
1427 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1428 // now.
1429 TemplateParameterList *TemplateParams =
1431 if (TemplateParams) {
1433 TemplateParams);
1434 LSI->Lambda->setLambdaIsGeneric(true);
1436 TemplateParams->containsUnexpandedParameterPack();
1437 }
1438 LSI->AfterParameterList = true;
1439}
1440
1442 Declarator &ParamInfo,
1443 const DeclSpec &DS) {
1444
1447
1449 bool ExplicitResultType;
1450
1451 SourceLocation TypeLoc, CallOperatorLoc;
1452 if (ParamInfo.getNumTypeObjects() == 0) {
1453 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1454 } else {
1455 unsigned Index;
1456 ParamInfo.isFunctionDeclarator(Index);
1457 const auto &Object = ParamInfo.getTypeObject(Index);
1458 TypeLoc =
1459 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1460 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1461 }
1462
1463 CXXRecordDecl *Class = LSI->Lambda;
1465
1466 TypeSourceInfo *MethodTyInfo = getLambdaType(
1467 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1468
1469 if (ParamInfo.isFunctionDeclarator() != 0) {
1470 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1471 LSI->ExplicitParams = FTI.getLParenLoc().isValid();
1472 if (!FTIHasSingleVoidParameter(FTI)) {
1473 Params.reserve(Params.size());
1474 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1475 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1476 Param->setScopeInfo(0, Params.size());
1477 Params.push_back(Param);
1478 }
1479 }
1480 }
1481
1482 bool IsLambdaStatic =
1484
1486 Method, Intro.Range.getBegin(), CallOperatorLoc,
1487 AssociatedConstraint(ParamInfo.getTrailingRequiresClause()), MethodTyInfo,
1488 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1489 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1490
1492
1493 // This represents the function body for the lambda function, check if we
1494 // have to apply optnone due to a pragma.
1496
1497 // code_seg attribute on lambda apply to the method.
1499 Method, /*IsDefinition=*/true))
1500 Method->addAttr(A);
1501
1502 // Attributes on the lambda apply to the method.
1503 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1504
1505 if (Context.getTargetInfo().getTriple().isAArch64())
1507
1508 // CUDA lambdas get implicit host and device attributes.
1509 if (getLangOpts().CUDA)
1511
1512 // OpenMP lambdas might get assumumption attributes.
1513 if (LangOpts.OpenMP)
1515
1517
1518 for (auto &&C : LSI->Captures) {
1519 if (!C.isVariableCapture())
1520 continue;
1521 ValueDecl *Var = C.getVariable();
1522 if (Var && Var->isInitCapture()) {
1523 PushOnScopeChains(Var, CurScope, false);
1524 }
1525 }
1526
1527 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1528 for (const auto &Capture : Intro.Captures) {
1529 if (Capture.Id == Param->getIdentifier()) {
1530 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1531 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1532 << Capture.Id << true;
1533 return false;
1534 }
1535 }
1536 return true;
1537 };
1538
1539 for (ParmVarDecl *P : Params) {
1540 if (!P->getIdentifier())
1541 continue;
1542 if (CheckRedefinition(P))
1543 CheckShadow(CurScope, P);
1544 PushOnScopeChains(P, CurScope);
1545 }
1546
1547 // C++23 [expr.prim.lambda.capture]p5:
1548 // If an identifier in a capture appears as the declarator-id of a parameter
1549 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1550 // template parameter of the lambda-expression's template-parameter-list, the
1551 // program is ill-formed.
1552 TemplateParameterList *TemplateParams =
1554 if (TemplateParams) {
1555 for (const auto *TP : TemplateParams->asArray()) {
1556 if (!TP->getIdentifier())
1557 continue;
1558 for (const auto &Capture : Intro.Captures) {
1559 if (Capture.Id == TP->getIdentifier()) {
1560 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1562 }
1563 }
1564 }
1565 }
1566
1567 // C++20: dcl.decl.general p4:
1568 // The optional requires-clause ([temp.pre]) in an init-declarator or
1569 // member-declarator shall be present only if the declarator declares a
1570 // templated function ([dcl.fct]).
1571 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause()) {
1572 // [temp.pre]/8:
1573 // An entity is templated if it is
1574 // - a template,
1575 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1576 // templated entity,
1577 // - a member of a templated entity,
1578 // - an enumerator for an enumeration that is a templated entity, or
1579 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1580 // appearing in the declaration of a templated entity. [Note 6: A local
1581 // class, a local or block variable, or a friend function defined in a
1582 // templated entity is a templated entity. — end note]
1583 //
1584 // A templated function is a function template or a function that is
1585 // templated. A templated class is a class template or a class that is
1586 // templated. A templated variable is a variable template or a variable
1587 // that is templated.
1588
1589 // Note: we only have to check if this is defined in a template entity, OR
1590 // if we are a template, since the rest don't apply. The requires clause
1591 // applies to the call operator, which we already know is a member function,
1592 // AND defined.
1593 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1594 Diag(TRC.ConstraintExpr->getBeginLoc(),
1595 diag::err_constrained_non_templated_function);
1596 }
1597 }
1598
1599 // Enter a new evaluation context to insulate the lambda from any
1600 // cleanups from the enclosing full-expression.
1603}
1604
1606 bool IsInstantiation) {
1608
1609 // Leave the expression-evaluation context.
1612
1613 // Leave the context of the lambda.
1614 if (!IsInstantiation)
1616
1617 // Finalize the lambda.
1618 CXXRecordDecl *Class = LSI->Lambda;
1619 Class->setInvalidDecl();
1620 SmallVector<Decl*, 4> Fields(Class->fields());
1621 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1623 CheckCompletedCXXClass(nullptr, Class);
1624
1626}
1627
1628template <typename Func>
1630 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1632 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1634 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1635 CallingConv CallOpCC = CallOpProto.getCallConv();
1636
1637 /// Implement emitting a version of the operator for many of the calling
1638 /// conventions for MSVC, as described here:
1639 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1640 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1641 /// vectorcall are generated by MSVC when it is supported by the target.
1642 /// Additionally, we are ensuring that the default-free/default-member and
1643 /// call-operator calling convention are generated as well.
1644 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1645 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1646 /// that someone who intentionally places 'thiscall' on the lambda call
1647 /// operator will still get that overload, since we don't have the a way of
1648 /// detecting the attribute by the time we get here.
1649 if (S.getLangOpts().MSVCCompat) {
1650 CallingConv Convs[] = {
1652 DefaultFree, DefaultMember, CallOpCC};
1653 llvm::sort(Convs);
1654 llvm::iterator_range<CallingConv *> Range(std::begin(Convs),
1655 llvm::unique(Convs));
1656 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1657
1658 for (CallingConv C : Range) {
1660 F(C);
1661 }
1662 return;
1663 }
1664
1665 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1666 F(DefaultFree);
1667 F(DefaultMember);
1668 } else {
1669 F(CallOpCC);
1670 }
1671}
1672
1673// Returns the 'standard' calling convention to be used for the lambda
1674// conversion function, that is, the 'free' function calling convention unless
1675// it is overridden by a non-default calling convention attribute.
1676static CallingConv
1678 const FunctionProtoType *CallOpProto) {
1680 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1682 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1683 CallingConv CallOpCC = CallOpProto->getCallConv();
1684
1685 // If the call-operator hasn't been changed, return both the 'free' and
1686 // 'member' function calling convention.
1687 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1688 return DefaultFree;
1689 return CallOpCC;
1690}
1691
1693 const FunctionProtoType *CallOpProto, CallingConv CC) {
1694 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1695 CallOpProto->getExtProtoInfo();
1696 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1697 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1698 InvokerExtInfo.TypeQuals = Qualifiers();
1699 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1700 "Lambda's call operator should not have a reference qualifier");
1701 return Context.getFunctionType(CallOpProto->getReturnType(),
1702 CallOpProto->getParamTypes(), InvokerExtInfo);
1703}
1704
1705/// Add a lambda's conversion to function pointer, as described in
1706/// C++11 [expr.prim.lambda]p6.
1707static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1708 CXXRecordDecl *Class,
1709 CXXMethodDecl *CallOperator,
1710 QualType InvokerFunctionTy) {
1711 // This conversion is explicitly disabled if the lambda's function has
1712 // pass_object_size attributes on any of its parameters.
1713 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1714 return P->hasAttr<PassObjectSizeAttr>();
1715 };
1716 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1717 return;
1718
1719 // Add the conversion to function pointer.
1720 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1721
1722 // Create the type of the conversion function.
1725 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1726 // The conversion function is always const and noexcept.
1727 ConvExtInfo.TypeQuals = Qualifiers();
1728 ConvExtInfo.TypeQuals.addConst();
1729 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1730 QualType ConvTy = S.Context.getFunctionType(PtrToFunctionTy, {}, ConvExtInfo);
1731
1732 SourceLocation Loc = IntroducerRange.getBegin();
1733 DeclarationName ConversionName
1735 S.Context.getCanonicalType(PtrToFunctionTy));
1736 // Construct a TypeSourceInfo for the conversion function, and wire
1737 // all the parameters appropriately for the FunctionProtoTypeLoc
1738 // so that everything works during transformation/instantiation of
1739 // generic lambdas.
1740 // The main reason for wiring up the parameters of the conversion
1741 // function with that of the call operator is so that constructs
1742 // like the following work:
1743 // auto L = [](auto b) { <-- 1
1744 // return [](auto a) -> decltype(a) { <-- 2
1745 // return a;
1746 // };
1747 // };
1748 // int (*fp)(int) = L(5);
1749 // Because the trailing return type can contain DeclRefExprs that refer
1750 // to the original call operator's variables, we hijack the call
1751 // operators ParmVarDecls below.
1752 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1753 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1754 DeclarationNameLoc ConvNameLoc =
1755 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1756
1757 // The conversion function is a conversion to a pointer-to-function.
1758 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1759 FunctionProtoTypeLoc ConvTL =
1761 // Get the result of the conversion function which is a pointer-to-function.
1762 PointerTypeLoc PtrToFunctionTL =
1763 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1764 // Do the same for the TypeSourceInfo that is used to name the conversion
1765 // operator.
1766 PointerTypeLoc ConvNamePtrToFunctionTL =
1767 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1768
1769 // Get the underlying function types that the conversion function will
1770 // be converting to (should match the type of the call operator).
1771 FunctionProtoTypeLoc CallOpConvTL =
1772 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1773 FunctionProtoTypeLoc CallOpConvNameTL =
1774 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1775
1776 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1777 // These parameter's are essentially used to transform the name and
1778 // the type of the conversion operator. By using the same parameters
1779 // as the call operator's we don't have to fix any back references that
1780 // the trailing return type of the call operator's uses (such as
1781 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1782 // - we can simply use the return type of the call operator, and
1783 // everything should work.
1784 SmallVector<ParmVarDecl *, 4> InvokerParams;
1785 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1786 ParmVarDecl *From = CallOperator->getParamDecl(I);
1787
1788 InvokerParams.push_back(ParmVarDecl::Create(
1789 S.Context,
1790 // Temporarily add to the TU. This is set to the invoker below.
1792 From->getLocation(), From->getIdentifier(), From->getType(),
1793 From->getTypeSourceInfo(), From->getStorageClass(),
1794 /*DefArg=*/nullptr));
1795 CallOpConvTL.setParam(I, From);
1796 CallOpConvNameTL.setParam(I, From);
1797 }
1798
1800 S.Context, Class, Loc,
1801 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1803 /*isInline=*/true, ExplicitSpecifier(),
1806 CallOperator->getBody()->getEndLoc());
1807 Conversion->setAccess(AS_public);
1808 Conversion->setImplicit(true);
1809
1810 // A non-generic lambda may still be a templated entity. We need to preserve
1811 // constraints when converting the lambda to a function pointer. See GH63181.
1812 if (const AssociatedConstraint &Requires =
1813 CallOperator->getTrailingRequiresClause())
1814 Conversion->setTrailingRequiresClause(Requires);
1815
1816 if (Class->isGenericLambda()) {
1817 // Create a template version of the conversion operator, using the template
1818 // parameter list of the function call operator.
1819 FunctionTemplateDecl *TemplateCallOperator =
1820 CallOperator->getDescribedFunctionTemplate();
1821 FunctionTemplateDecl *ConversionTemplate =
1823 Loc, ConversionName,
1824 TemplateCallOperator->getTemplateParameters(),
1825 Conversion);
1826 ConversionTemplate->setAccess(AS_public);
1827 ConversionTemplate->setImplicit(true);
1828 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1829 Class->addDecl(ConversionTemplate);
1830 } else
1831 Class->addDecl(Conversion);
1832
1833 // If the lambda is not static, we need to add a static member
1834 // function that will be the result of the conversion with a
1835 // certain unique ID.
1836 // When it is static we just return the static call operator instead.
1837 if (CallOperator->isImplicitObjectMemberFunction()) {
1838 DeclarationName InvokerName =
1840 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1841 // we should get a prebuilt TrivialTypeSourceInfo from Context
1842 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1843 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1844 // loop below and then use its Params to set Invoke->setParams(...) below.
1845 // This would avoid the 'const' qualifier of the calloperator from
1846 // contaminating the type of the invoker, which is currently adjusted
1847 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1848 // trailing return type of the invoker would require a visitor to rebuild
1849 // the trailing return type and adjusting all back DeclRefExpr's to refer
1850 // to the new static invoker parameters - not the call operator's.
1852 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1853 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1855 /*isInline=*/true, CallOperator->getConstexprKind(),
1856 CallOperator->getBody()->getEndLoc());
1857 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1858 InvokerParams[I]->setOwningFunction(Invoke);
1859 Invoke->setParams(InvokerParams);
1860 Invoke->setAccess(AS_private);
1861 Invoke->setImplicit(true);
1862 if (Class->isGenericLambda()) {
1863 FunctionTemplateDecl *TemplateCallOperator =
1864 CallOperator->getDescribedFunctionTemplate();
1865 FunctionTemplateDecl *StaticInvokerTemplate =
1867 S.Context, Class, Loc, InvokerName,
1868 TemplateCallOperator->getTemplateParameters(), Invoke);
1869 StaticInvokerTemplate->setAccess(AS_private);
1870 StaticInvokerTemplate->setImplicit(true);
1871 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1872 Class->addDecl(StaticInvokerTemplate);
1873 } else
1874 Class->addDecl(Invoke);
1875 }
1876}
1877
1878/// Add a lambda's conversion to function pointers, as described in
1879/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1880/// single pointer conversion. In the event that the default calling convention
1881/// for free and member functions is different, it will emit both conventions.
1882static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1883 CXXRecordDecl *Class,
1884 CXXMethodDecl *CallOperator) {
1885 const FunctionProtoType *CallOpProto =
1886 CallOperator->getType()->castAs<FunctionProtoType>();
1887
1889 S, *CallOpProto, [&](CallingConv CC) {
1890 QualType InvokerFunctionTy =
1891 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1892 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1893 InvokerFunctionTy);
1894 });
1895}
1896
1897/// Add a lambda's conversion to block pointer.
1899 SourceRange IntroducerRange,
1900 CXXRecordDecl *Class,
1901 CXXMethodDecl *CallOperator) {
1902 const FunctionProtoType *CallOpProto =
1903 CallOperator->getType()->castAs<FunctionProtoType>();
1905 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1906 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1907
1908 FunctionProtoType::ExtProtoInfo ConversionEPI(
1910 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1911 ConversionEPI.TypeQuals = Qualifiers();
1912 ConversionEPI.TypeQuals.addConst();
1913 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, {}, ConversionEPI);
1914
1915 SourceLocation Loc = IntroducerRange.getBegin();
1916 DeclarationName Name
1918 S.Context.getCanonicalType(BlockPtrTy));
1920 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1922 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1923 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1926 CallOperator->getBody()->getEndLoc());
1927 Conversion->setAccess(AS_public);
1928 Conversion->setImplicit(true);
1929 Class->addDecl(Conversion);
1930}
1931
1933 SourceLocation ImplicitCaptureLoc,
1934 bool IsOpenMPMapping) {
1935 // VLA captures don't have a stored initialization expression.
1936 if (Cap.isVLATypeCapture())
1937 return ExprResult();
1938
1939 // An init-capture is initialized directly from its stored initializer.
1940 if (Cap.isInitCapture())
1941 return cast<VarDecl>(Cap.getVariable())->getInit();
1942
1943 // For anything else, build an initialization expression. For an implicit
1944 // capture, the capture notionally happens at the capture-default, so use
1945 // that location here.
1946 SourceLocation Loc =
1947 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1948
1949 // C++11 [expr.prim.lambda]p21:
1950 // When the lambda-expression is evaluated, the entities that
1951 // are captured by copy are used to direct-initialize each
1952 // corresponding non-static data member of the resulting closure
1953 // object. (For array members, the array elements are
1954 // direct-initialized in increasing subscript order.) These
1955 // initializations are performed in the (unspecified) order in
1956 // which the non-static data members are declared.
1957
1958 // C++ [expr.prim.lambda]p12:
1959 // An entity captured by a lambda-expression is odr-used (3.2) in
1960 // the scope containing the lambda-expression.
1962 IdentifierInfo *Name = nullptr;
1963 if (Cap.isThisCapture()) {
1964 QualType ThisTy = getCurrentThisType();
1965 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1966 if (Cap.isCopyCapture())
1967 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1968 else
1969 Init = This;
1970 } else {
1971 assert(Cap.isVariableCapture() && "unknown kind of capture");
1972 ValueDecl *Var = Cap.getVariable();
1973 Name = Var->getIdentifier();
1975 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1976 }
1977
1978 // In OpenMP, the capture kind doesn't actually describe how to capture:
1979 // variables are "mapped" onto the device in a process that does not formally
1980 // make a copy, even for a "copy capture".
1981 if (IsOpenMPMapping)
1982 return Init;
1983
1984 if (Init.isInvalid())
1985 return ExprError();
1986
1987 Expr *InitExpr = Init.get();
1989 Name, Cap.getCaptureType(), Loc);
1990 InitializationKind InitKind =
1991 InitializationKind::CreateDirect(Loc, Loc, Loc);
1992 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1993 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1994}
1995
1998
1999 if (LSI.CallOperator->hasAttr<SYCLKernelEntryPointAttr>())
2001
2002 ActOnFinishFunctionBody(LSI.CallOperator, Body, /*IsInstantiation=*/false,
2003 /*RetainFunctionScopeInfo=*/true);
2004
2005 return BuildLambdaExpr(StartLoc, Body->getEndLoc());
2006}
2007
2010 switch (ICS) {
2012 return LCD_None;
2014 return LCD_ByCopy;
2017 return LCD_ByRef;
2019 llvm_unreachable("block capture in lambda");
2020 }
2021 llvm_unreachable("Unknown implicit capture style");
2022}
2023
2025 if (From.isInitCapture()) {
2026 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
2027 if (Init && Init->HasSideEffects(Context))
2028 return true;
2029 }
2030
2031 if (!From.isCopyCapture())
2032 return false;
2033
2034 const QualType T = From.isThisCapture()
2036 : From.getCaptureType();
2037
2038 if (T.isVolatileQualified())
2039 return true;
2040
2041 const Type *BaseT = T->getBaseElementTypeUnsafe();
2042 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
2043 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
2044 !RD->hasTrivialDestructor();
2045
2046 return false;
2047}
2048
2050 SourceRange FixItRange,
2051 const Capture &From) {
2052 if (CaptureHasSideEffects(From))
2053 return false;
2054
2055 if (From.isVLATypeCapture())
2056 return false;
2057
2058 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2059 // message
2060 if (From.isInitCapture() &&
2062 return false;
2063
2064 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2065 if (From.isThisCapture())
2066 diag << "'this'";
2067 else
2068 diag << From.getVariable();
2069 diag << From.isNonODRUsed();
2070 // If we were able to resolve the fixit range we'll create a fixit,
2071 // otherwise we just use the raw capture range for the diagnostic.
2072 if (FixItRange.isValid())
2073 diag << FixItHint::CreateRemoval(FixItRange);
2074 else
2075 diag << CaptureRange;
2076 return true;
2077}
2078
2079/// Create a field within the lambda class or captured statement record for the
2080/// given capture.
2082 const sema::Capture &Capture) {
2084 QualType FieldType = Capture.getCaptureType();
2085
2086 TypeSourceInfo *TSI = nullptr;
2087 if (Capture.isVariableCapture()) {
2088 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2089 if (Var && Var->isInitCapture())
2090 TSI = Var->getTypeSourceInfo();
2091 }
2092
2093 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2094 // appropriate, at least for an implicit capture.
2095 if (!TSI)
2096 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2097
2098 // Build the non-static data member.
2099 FieldDecl *Field =
2100 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2101 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2102 /*Mutable=*/false, ICIS_NoInit);
2103 // If the variable being captured has an invalid type, mark the class as
2104 // invalid as well.
2105 if (!FieldType->isDependentType()) {
2106 if (RequireCompleteSizedType(Loc, FieldType,
2107 diag::err_field_incomplete_or_sizeless)) {
2108 RD->setInvalidDecl();
2109 Field->setInvalidDecl();
2110 } else {
2111 NamedDecl *Def;
2112 FieldType->isIncompleteType(&Def);
2113 if (Def && Def->isInvalidDecl()) {
2114 RD->setInvalidDecl();
2115 Field->setInvalidDecl();
2116 }
2117 }
2118 }
2119 Field->setImplicit(true);
2120 Field->setAccess(AS_private);
2121 RD->addDecl(Field);
2122
2124 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2125
2126 return Field;
2127}
2128
2129static SourceRange
2131 SourceLocation PrevCaptureLoc,
2132 bool CurHasPreviousCapture, bool IsLast) {
2133 if (!CaptureRange.isValid())
2134 return SourceRange();
2135
2136 auto GetTrailingEndLocation = [&](SourceLocation StartPoint) {
2137 SourceRange NextToken = S.getRangeForNextToken(
2138 StartPoint, /*IncludeMacros=*/false, /*IncludeComments=*/true);
2139 if (!NextToken.isValid())
2140 return SourceLocation();
2141 // Return the last location preceding the next token
2142 return NextToken.getBegin().getLocWithOffset(-1);
2143 };
2144
2145 if (!CurHasPreviousCapture && !IsLast) {
2146 // If there are no captures preceding this capture, remove the
2147 // trailing comma and anything up to the next token
2148 SourceRange CommaRange =
2149 S.getRangeForNextToken(CaptureRange.getEnd(), /*IncludeMacros=*/false,
2150 /*IncludeComments=*/false, tok::comma);
2151 SourceLocation FixItEnd = GetTrailingEndLocation(CommaRange.getBegin());
2152 return SourceRange(CaptureRange.getBegin(), FixItEnd);
2153 }
2154
2155 // Otherwise, remove the comma since the last used capture, and
2156 // anything up to the next token
2157 SourceLocation FixItStart = S.getLocForEndOfToken(PrevCaptureLoc);
2158 SourceLocation FixItEnd = GetTrailingEndLocation(CaptureRange.getEnd());
2159 return SourceRange(FixItStart, FixItEnd);
2160}
2161
2163 SourceLocation EndLoc) {
2165 // Collect information from the lambda scope.
2167 SmallVector<Expr *, 4> CaptureInits;
2168 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2169 LambdaCaptureDefault CaptureDefault =
2171 CXXRecordDecl *Class = LSI->Lambda;
2172 CXXMethodDecl *CallOperator = LSI->CallOperator;
2173 SourceRange IntroducerRange = LSI->IntroducerRange;
2174 bool ExplicitParams = LSI->ExplicitParams;
2175 bool ExplicitResultType = !LSI->HasImplicitReturnType;
2176 CleanupInfo LambdaCleanup = LSI->Cleanup;
2177 bool ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2178 bool IsGenericLambda = Class->isGenericLambda();
2179
2180 CallOperator->setLexicalDeclContext(Class);
2181 Decl *TemplateOrNonTemplateCallOperatorDecl =
2182 CallOperator->getDescribedFunctionTemplate()
2183 ? CallOperator->getDescribedFunctionTemplate()
2184 : cast<Decl>(CallOperator);
2185
2186 // FIXME: Is this really the best choice? Keeping the lexical decl context
2187 // set as CurContext seems more faithful to the source.
2188 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2189
2190 {
2191 // TreeTransform of immediate functions may call getCurLambda, which
2192 // requires both the paired LSI and the lambda DeclContext.
2193 ContextRAII SavedContext(*this, CallOperator, /*NewThisContext=*/false);
2195 }
2196
2198 AnalysisWarnings.getPolicyInEffectAt(EndLoc);
2199 // We cannot release LSI until we finish computing captures, which
2200 // requires the scope to be popped.
2202
2203 // True if the current capture has a used capture or default before it.
2204 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2205 SourceLocation PrevCaptureLoc =
2206 CurHasPreviousCapture ? CaptureDefaultLoc : IntroducerRange.getBegin();
2207
2208 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2209 const Capture &From = LSI->Captures[I];
2210
2211 if (From.isInvalid())
2212 return ExprError();
2213
2214 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2215 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2216 SourceLocation ImplicitCaptureLoc =
2217 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2218
2219 // Use source ranges of explicit captures for fixits where available.
2220 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2221
2222 // Warn about unused explicit captures.
2223 bool IsCaptureUsed = true;
2224 if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
2225 // Initialized captures that are non-ODR used may not be eliminated.
2226 // FIXME: Where did the IsGenericLambda here come from?
2227 bool NonODRUsedInitCapture =
2228 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2229 if (!NonODRUsedInitCapture) {
2230 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2232 *this, CaptureRange, PrevCaptureLoc, CurHasPreviousCapture, IsLast);
2233 IsCaptureUsed =
2234 !DiagnoseUnusedLambdaCapture(CaptureRange, FixItRange, From);
2235 }
2236 }
2237
2238 if (CaptureRange.isValid()) {
2239 CurHasPreviousCapture |= IsCaptureUsed;
2240 PrevCaptureLoc = CaptureRange.getEnd();
2241 }
2242
2243 // Map the capture to our AST representation.
2244 LambdaCapture Capture = [&] {
2245 if (From.isThisCapture()) {
2246 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2247 // because it results in a reference capture. Don't warn prior to
2248 // C++2a; there's nothing that can be done about it before then.
2249 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2250 CaptureDefault == LCD_ByCopy) {
2251 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2252 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2254 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2255 }
2256 return LambdaCapture(From.getLocation(), IsImplicit,
2258 } else if (From.isVLATypeCapture()) {
2259 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2260 } else {
2261 assert(From.isVariableCapture() && "unknown kind of capture");
2262 ValueDecl *Var = From.getVariable();
2264 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2265 From.getEllipsisLoc());
2266 }
2267 }();
2268
2269 // Form the initializer for the capture field.
2270 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2271
2272 // FIXME: Skip this capture if the capture is not used, the initializer
2273 // has no side-effects, the type of the capture is trivial, and the
2274 // lambda is not externally visible.
2275
2276 // Add a FieldDecl for the capture and form its initializer.
2277 BuildCaptureField(Class, From);
2278 Captures.push_back(Capture);
2279 CaptureInits.push_back(Init.get());
2280
2281 if (LangOpts.CUDA)
2282 CUDA().CheckLambdaCapture(CallOperator, From);
2283 }
2284
2285 Class->setCaptures(Context, Captures);
2286
2287 // C++11 [expr.prim.lambda]p6:
2288 // The closure type for a lambda-expression with no lambda-capture
2289 // has a public non-virtual non-explicit const conversion function
2290 // to pointer to function having the same parameter and return
2291 // types as the closure type's function call operator.
2292 if (Captures.empty() && CaptureDefault == LCD_None)
2293 addFunctionPointerConversions(*this, IntroducerRange, Class, CallOperator);
2294
2295 // Objective-C++:
2296 // The closure type for a lambda-expression has a public non-virtual
2297 // non-explicit const conversion function to a block pointer having the
2298 // same parameter and return types as the closure type's function call
2299 // operator.
2300 // FIXME: Fix generic lambda to block conversions.
2301 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2302 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2303
2304 // Finalize the lambda class.
2305 SmallVector<Decl *, 4> Fields(Class->fields());
2306 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2308 CheckCompletedCXXClass(nullptr, Class);
2309
2310 Cleanup.mergeFrom(LambdaCleanup);
2311
2312 LambdaExpr *Lambda =
2313 LambdaExpr::Create(Context, Class, IntroducerRange, CaptureDefault,
2314 CaptureDefaultLoc, ExplicitParams, ExplicitResultType,
2315 CaptureInits, EndLoc, ContainsUnexpandedParameterPack);
2316
2317 // If the lambda expression's call operator is not explicitly marked constexpr
2318 // and is not dependent, analyze the call operator to infer
2319 // its constexpr-ness, suppressing diagnostics while doing so.
2320 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2321 !CallOperator->isConstexpr() &&
2322 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2323 !Class->isDependentContext()) {
2324 CallOperator->setConstexprKind(
2329 }
2330
2331 // Emit delayed shadowing warnings now that the full capture list is known.
2333
2334 if (!CurContext->isDependentContext()) {
2335 switch (ExprEvalContexts.back().Context) {
2336 // C++11 [expr.prim.lambda]p2:
2337 // A lambda-expression shall not appear in an unevaluated operand
2338 // (Clause 5).
2342 // C++1y [expr.const]p2:
2343 // A conditional-expression e is a core constant expression unless the
2344 // evaluation of e, following the rules of the abstract machine, would
2345 // evaluate [...] a lambda-expression.
2346 //
2347 // This is technically incorrect, there are some constant evaluated contexts
2348 // where this should be allowed. We should probably fix this when DR1607 is
2349 // ratified, it lays out the exact set of conditions where we shouldn't
2350 // allow a lambda-expression.
2353 // We don't actually diagnose this case immediately, because we
2354 // could be within a context where we might find out later that
2355 // the expression is potentially evaluated (e.g., for typeid).
2356 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2357 break;
2358
2362 break;
2363 }
2365 }
2366
2367 return MaybeBindToTemporary(Lambda);
2368}
2369
2371 SourceLocation ConvLocation,
2372 CXXConversionDecl *Conv,
2373 Expr *Src) {
2374 // Make sure that the lambda call operator is marked used.
2375 CXXRecordDecl *Lambda = Conv->getParent();
2376 CXXMethodDecl *CallOperator
2378 Lambda->lookup(
2379 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2380 CallOperator->setReferenced();
2381 CallOperator->markUsed(Context);
2382
2385 CurrentLocation, Src);
2386 if (!Init.isInvalid())
2387 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2388
2389 if (Init.isInvalid())
2390 return ExprError();
2391
2392 // Create the new block to be returned.
2394
2395 // Set the type information.
2396 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2397 Block->setIsVariadic(CallOperator->isVariadic());
2398 Block->setBlockMissingReturnType(false);
2399
2400 // Add parameters.
2402 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2403 ParmVarDecl *From = CallOperator->getParamDecl(I);
2404 BlockParams.push_back(ParmVarDecl::Create(
2405 Context, Block, From->getBeginLoc(), From->getLocation(),
2406 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2407 From->getStorageClass(),
2408 /*DefArg=*/nullptr));
2409 }
2410 Block->setParams(BlockParams);
2411
2412 Block->setIsConversionFromLambda(true);
2413
2414 // Add capture. The capture uses a fake variable, which doesn't correspond
2415 // to any actual memory location. However, the initializer copy-initializes
2416 // the lambda object.
2417 TypeSourceInfo *CapVarTSI =
2418 Context.getTrivialTypeSourceInfo(Src->getType());
2419 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2420 ConvLocation, nullptr,
2421 Src->getType(), CapVarTSI,
2422 SC_None);
2423 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2424 /*nested=*/false, /*copy=*/Init.get());
2425 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2426
2427 // Add a fake function body to the block. IR generation is responsible
2428 // for filling in the actual body, which cannot be expressed as an AST.
2429 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2430
2431 // Create the block literal expression.
2432 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2433 Expr *BuildBlock =
2435 /*ContainsUnexpandedParameterPack=*/false);
2436 ExprCleanupObjects.push_back(Block);
2437 Cleanup.setExprNeedsCleanups(true);
2438
2439 return BuildBlock;
2440}
2441
2446 return FD;
2447 }
2448
2450 return FD->getInstantiatedFromDecl();
2451
2453 if (!FTD)
2454 return nullptr;
2455
2458
2459 return FTD->getTemplatedDecl();
2460}
2461
2462bool Sema::addInstantiatedCapturesToScope(
2463 FunctionDecl *Function, const FunctionDecl *PatternDecl,
2465 const MultiLevelTemplateArgumentList &TemplateArgs) {
2466 const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
2467 const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
2468
2469 unsigned Instantiated = 0;
2470
2471 // FIXME: This is a workaround for not having deferred lambda body
2472 // instantiation.
2473 // When transforming a lambda's body, if we encounter another call to a
2474 // nested lambda that contains a constraint expression, we add all of the
2475 // outer lambda's instantiated captures to the current instantiation scope to
2476 // facilitate constraint evaluation. However, these captures don't appear in
2477 // the CXXRecordDecl until after the lambda expression is rebuilt, so we
2478 // pull them out from the corresponding LSI.
2479 LambdaScopeInfo *InstantiatingScope = nullptr;
2480 if (LambdaPattern->capture_size() && !LambdaClass->capture_size()) {
2481 for (FunctionScopeInfo *Scope : llvm::reverse(FunctionScopes)) {
2482 auto *LSI = dyn_cast<LambdaScopeInfo>(Scope);
2483 if (!LSI || getPatternFunctionDecl(LSI->CallOperator) != PatternDecl)
2484 continue;
2485 InstantiatingScope = LSI;
2486 break;
2487 }
2488 assert(InstantiatingScope);
2489 }
2490
2491 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
2492 unsigned Index) {
2493 ValueDecl *CapturedVar =
2494 InstantiatingScope ? InstantiatingScope->Captures[Index].getVariable()
2495 : LambdaClass->getCapture(Index)->getCapturedVar();
2496 assert(CapturedVar->isInitCapture());
2497 Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
2498 };
2499
2500 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
2501 if (!CapturePattern.capturesVariable()) {
2502 Instantiated++;
2503 continue;
2504 }
2505 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
2506
2507 if (!CapturedPattern->isInitCapture()) {
2508 Instantiated++;
2509 continue;
2510 }
2511
2512 if (!CapturedPattern->isParameterPack()) {
2513 AddSingleCapture(CapturedPattern, Instantiated++);
2514 } else {
2515 Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
2516 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2517 SemaRef.collectUnexpandedParameterPacks(
2518 dyn_cast<VarDecl>(CapturedPattern)->getInit(), Unexpanded);
2519 auto NumArgumentsInExpansion =
2520 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
2521 if (!NumArgumentsInExpansion)
2522 continue;
2523 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
2524 AddSingleCapture(CapturedPattern, Instantiated++);
2525 }
2526 }
2527 return false;
2528}
2529
2533 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2535 if (!isLambdaCallOperator(FD)) {
2537 return;
2538 }
2539
2540 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2541
2542 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2543 if (!FDPattern)
2544 return;
2545
2546 if (!ShouldAddDeclsFromParentScope)
2547 return;
2548
2550 InstantiationAndPatterns;
2551 while (FDPattern && FD) {
2552 InstantiationAndPatterns.emplace_back(FDPattern, FD);
2553
2554 FDPattern =
2555 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));
2556 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));
2557 }
2558
2559 // Add instantiated parameters and local vars to scopes, starting from the
2560 // outermost lambda to the innermost lambda. This ordering ensures that
2561 // the outer instantiations can be found when referenced from within inner
2562 // lambdas.
2563 //
2564 // auto L = [](auto... x) {
2565 // return [](decltype(x)... y) { }; // Instantiating y needs x
2566 // };
2567 //
2568
2569 for (auto [FDPattern, FD] : llvm::reverse(InstantiationAndPatterns)) {
2570 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2571 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2572
2573 if (isLambdaCallOperator(FD))
2574 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2575 }
2576}
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the clang::Expr interface and subclasses for C++ expressions.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static CallingConv getLambdaConversionFunctionCallConv(Sema &S, const FunctionProtoType *CallOpProto)
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise,...
static EnumDecl * findCommonEnumForBlockReturns(ArrayRef< ReturnStmt * > returns)
Attempt to find a common type T for which all of the returned expressions in a block are enumerator-l...
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
static UnsignedOrNone getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, bool ExplicitResultType)
static SourceRange ConstructFixItRangeForUnusedCapture(Sema &S, SourceRange CaptureRange, SourceLocation PrevCaptureLoc, bool CurHasPreviousCapture, bool IsLast)
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointers, as described in C++11 [expr.prim.lambda]p6.
static void repeatForLambdaConversionFunctionCallingConvs(Sema &S, const FunctionProtoType &CallOpProto, Func F)
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator, QualType InvokerFunctionTy)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
This file provides some common utility functions for processing Lambdas.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for SYCL constructs.
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
TranslationUnitDecl * getTranslationUnitDecl() const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:801
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:797
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:916
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType getCanonicalTagType(const TagDecl *TD) const
PtrTy get() const
Definition Ownership.h:171
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
A binding in a decomposition declaration.
Definition DeclCXX.h:4188
A class which contains all the information about a particular captured value.
Definition Decl.h:4680
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4674
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5646
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3241
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2986
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2728
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2506
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition DeclCXX.h:1871
void setLambdaIsGeneric(bool IsGeneric)
Definition DeclCXX.h:1882
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:141
bool isCapturelessLambda() const
Definition DeclCXX.h:1064
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
ConditionalOperator - The ?
Definition Expr.h:4394
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isRequiresExprBody() const
Definition DeclBase.h:2194
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2185
void addDecl(Decl *D)
Add the declaration D into this context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
bool SetTypeQual(TQ T, SourceLocation Loc)
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:837
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:590
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
void setReferenced(bool R=true)
Definition DeclBase.h:623
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTrailingRequiresClause(const AssociatedConstraint &AC)
Definition Decl.cpp:2031
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2419
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2654
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2415
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2508
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4013
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3662
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4701
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition Expr.h:1070
const Expr * getSubExpr() const
Definition Expr.h:1065
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3280
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4199
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3134
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
FunctionDecl * getInstantiatedFromDecl() const
Definition Decl.cpp:4218
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4166
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2805
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4734
CallingConv getCallConv() const
Definition TypeBase.h:4866
QualType getReturnType() const
Definition TypeBase.h:4851
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
Describes the capture of a variable or of this, or of a C++1y init-capture.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1969
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition ExprCXX.cpp:1312
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:372
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *)
Retrieve the mangling number of a new lambda expression with the given call operator within the devic...
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
PtrTy get() const
Definition Ownership.h:81
Expr ** getExprs()
Definition Expr.h:6124
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6113
Represents a parameter to a function.
Definition Decl.h:1790
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2958
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
Represents a struct/union/class.
Definition Decl.h:4327
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3152
void setRetValue(Expr *E)
Definition Stmt.h:3181
SourceLocation getBeginLoc() const
Definition Stmt.h:3204
Expr * getRetValue()
Definition Stmt.h:3179
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
decl_range decls() const
Definition Scope.h:356
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:493
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1532
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:297
A RAII object to temporarily push a declaration context.
Definition Sema.h:3518
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8295
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9382
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
SemaOpenMP & OpenMP()
Definition Sema.h:1525
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
SemaCUDA & CUDA()
Definition Sema.h:1465
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1236
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
void AddTemplateParametersToLambdaCallOperator(CXXMethodDecl *CallOperator, CXXRecordDecl *Class, TemplateParameterList *TemplateParams)
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
SemaSYCL & SYCL()
Definition Sema.h:1550
ASTContext & Context
Definition Sema.h:1300
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:225
SemaObjC & ObjC()
Definition Sema.h:1510
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1073
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void PopExpressionEvaluationContext()
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition Sema.cpp:2603
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1693
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
@ UPPC_Initializer
An initializer.
Definition Sema.h:14507
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14480
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
const LangOptions & getLangOpts() const
Definition Sema.h:932
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2463
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & LangOpts
Definition Sema.h:1298
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2578
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, const AssociatedConstraint &TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15758
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7012
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14026
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, SourceRange FixItRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7016
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1338
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6775
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6765
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6780
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6770
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6790
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6759
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6785
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6800
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8368
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
friend class InitializationSequence
Definition Sema.h:1580
void PopDeclContext()
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc)
Complete a lambda-expression having processed and attached the lambda body.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:88
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6470
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaARM & ARM()
Definition Sema.h:1445
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8710
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4598
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3950
Exposes information about the current target.
Definition TargetInfo.h:226
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
ArrayRef< NamedDecl * > asArray()
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
A container of type source information.
Definition TypeBase.h:8359
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8370
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isVoidType() const
Definition TypeBase.h:8991
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2137
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9171
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2479
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5094
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5594
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3653
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5588
Represents a variable declaration or definition.
Definition Decl.h:926
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2163
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
void setInitCapture(bool IC)
Definition Decl.h:1581
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
InitializationStyle
Initialization styles.
Definition Decl.h:929
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ CInit
C-style initialization with assignment.
Definition Decl.h:931
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
void setInit(Expr *I)
Definition Decl.cpp:2489
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isVariableCapture() const
Definition ScopeInfo.h:654
bool isBlockCapture() const
Definition ScopeInfo.h:660
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
bool isNonODRUsed() const
Definition ScopeInfo.h:671
bool isODRUsed() const
Definition ScopeInfo.h:670
bool isInitCapture() const
Determine whether this capture is an init-capture.
bool isInvalid() const
Definition ScopeInfo.h:665
bool isVLATypeCapture() const
Definition ScopeInfo.h:661
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition ScopeInfo.h:694
bool isThisCapture() const
Definition ScopeInfo.h:653
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:699
bool isCopyCapture() const
Definition ScopeInfo.h:658
const VariableArrayType * getCapturedVLAType() const
Definition ScopeInfo.h:684
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:736
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition ScopeInfo.h:768
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:725
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:762
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this, if any.
Definition ScopeInfo.h:739
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:741
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Definition ScopeInfo.h:214
SourceLocation PotentialThisCaptureLocation
Definition ScopeInfo.h:954
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition ScopeInfo.h:965
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition ScopeInfo.h:906
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:888
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition ScopeInfo.h:903
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:919
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition ScopeInfo.h:914
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition ScopeInfo.h:909
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:896
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition ScopeInfo.h:892
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition ScopeInfo.h:943
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:900
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
@ CPlusPlus17
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
TryCaptureKind
Definition Sema.h:653
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
UnsignedOrNone getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
LambdaCaptureKind
The different capture forms in a lambda introducer.
Definition Lambda.h:33
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
Definition Lambda.h:36
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_VLAType
Capturing variable-length array type.
Definition Lambda.h:38
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
@ LCK_This
Capturing the *this object by reference.
Definition Lambda.h:34
@ AS_public
Definition Specifiers.h:124
@ AS_private
Definition Specifiers.h:126
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2847
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition Specifiers.h:369
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
StringRef getLambdaStaticInvokerName()
Definition ASTLambda.h:23
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5925
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_BasicNoexcept
noexcept
Information about how a lambda is numbered within its context.
Definition DeclCXX.h:1805
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1608
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1599
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1602
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1571
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition DeclSpec.h:1346
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5374
Extra information about a function prototype.
Definition TypeBase.h:5400
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition DeclSpec.h:2904
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2917
Represents a complete lambda introducer.
Definition DeclSpec.h:2853
SmallVector< LambdaCapture, 4 > Captures
Definition DeclSpec.h:2878
SourceLocation DefaultLoc
Definition DeclSpec.h:2876
LambdaCaptureDefault Default
Definition DeclSpec.h:2877