clang 19.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"
18#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
23#include "clang/Sema/SemaCUDA.h"
26#include "clang/Sema/Template.h"
27#include "llvm/ADT/STLExtras.h"
28#include <optional>
29using namespace clang;
30using namespace sema;
31
32/// Examines the FunctionScopeInfo stack to determine the nearest
33/// enclosing lambda (to the current lambda) that is 'capture-ready' for
34/// the variable referenced in the current lambda (i.e. \p VarToCapture).
35/// If successful, returns the index into Sema's FunctionScopeInfo stack
36/// of the capture-ready lambda's LambdaScopeInfo.
37///
38/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
39/// lambda - is on top) to determine the index of the nearest enclosing/outer
40/// lambda that is ready to capture the \p VarToCapture being referenced in
41/// the current lambda.
42/// As we climb down the stack, we want the index of the first such lambda -
43/// that is the lambda with the highest index that is 'capture-ready'.
44///
45/// A lambda 'L' is capture-ready for 'V' (var or this) if:
46/// - its enclosing context is non-dependent
47/// - and if the chain of lambdas between L and the lambda in which
48/// V is potentially used (i.e. the lambda at the top of the scope info
49/// stack), can all capture or have already captured V.
50/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
51///
52/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
53/// for whether it is 'capture-capable' (see
54/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
55/// capture.
56///
57/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
58/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
59/// is at the top of the stack and has the highest index.
60/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
61///
62/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
63/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
64/// lambda which is capture-ready. If the return value evaluates to 'false'
65/// then no lambda is capture-ready for \p VarToCapture.
66
67static inline std::optional<unsigned>
70 ValueDecl *VarToCapture) {
71 // Label failure to capture.
72 const std::optional<unsigned> NoLambdaIsCaptureReady;
73
74 // Ignore all inner captured regions.
75 unsigned CurScopeIndex = FunctionScopes.size() - 1;
76 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
77 FunctionScopes[CurScopeIndex]))
78 --CurScopeIndex;
79 assert(
80 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
81 "The function on the top of sema's function-info stack must be a lambda");
82
83 // If VarToCapture is null, we are attempting to capture 'this'.
84 const bool IsCapturingThis = !VarToCapture;
85 const bool IsCapturingVariable = !IsCapturingThis;
86
87 // Start with the current lambda at the top of the stack (highest index).
88 DeclContext *EnclosingDC =
89 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
90
91 do {
93 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
94 // IF we have climbed down to an intervening enclosing lambda that contains
95 // the variable declaration - it obviously can/must not capture the
96 // variable.
97 // Since its enclosing DC is dependent, all the lambdas between it and the
98 // innermost nested lambda are dependent (otherwise we wouldn't have
99 // arrived here) - so we don't yet have a lambda that can capture the
100 // variable.
101 if (IsCapturingVariable &&
102 VarToCapture->getDeclContext()->Equals(EnclosingDC))
103 return NoLambdaIsCaptureReady;
104
105 // For an enclosing lambda to be capture ready for an entity, all
106 // intervening lambda's have to be able to capture that entity. If even
107 // one of the intervening lambda's is not capable of capturing the entity
108 // then no enclosing lambda can ever capture that entity.
109 // For e.g.
110 // const int x = 10;
111 // [=](auto a) { #1
112 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
113 // [=](auto c) { #3
114 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
115 // }; }; };
116 // If they do not have a default implicit capture, check to see
117 // if the entity has already been explicitly captured.
118 // If even a single dependent enclosing lambda lacks the capability
119 // to ever capture this variable, there is no further enclosing
120 // non-dependent lambda that can capture this variable.
121 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
122 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
123 return NoLambdaIsCaptureReady;
124 if (IsCapturingThis && !LSI->isCXXThisCaptured())
125 return NoLambdaIsCaptureReady;
126 }
127 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
128
129 assert(CurScopeIndex);
130 --CurScopeIndex;
131 } while (!EnclosingDC->isTranslationUnit() &&
132 EnclosingDC->isDependentContext() &&
133 isLambdaCallOperator(EnclosingDC));
134
135 assert(CurScopeIndex < (FunctionScopes.size() - 1));
136 // If the enclosingDC is not dependent, then the immediately nested lambda
137 // (one index above) is capture-ready.
138 if (!EnclosingDC->isDependentContext())
139 return CurScopeIndex + 1;
140 return NoLambdaIsCaptureReady;
141}
142
143/// Examines the FunctionScopeInfo stack to determine the nearest
144/// enclosing lambda (to the current lambda) that is 'capture-capable' for
145/// the variable referenced in the current lambda (i.e. \p VarToCapture).
146/// If successful, returns the index into Sema's FunctionScopeInfo stack
147/// of the capture-capable lambda's LambdaScopeInfo.
148///
149/// Given the current stack of lambdas being processed by Sema and
150/// the variable of interest, to identify the nearest enclosing lambda (to the
151/// current lambda at the top of the stack) that can truly capture
152/// a variable, it has to have the following two properties:
153/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
154/// - climb down the stack (i.e. starting from the innermost and examining
155/// each outer lambda step by step) checking if each enclosing
156/// lambda can either implicitly or explicitly capture the variable.
157/// Record the first such lambda that is enclosed in a non-dependent
158/// context. If no such lambda currently exists return failure.
159/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
160/// capture the variable by checking all its enclosing lambdas:
161/// - check if all outer lambdas enclosing the 'capture-ready' lambda
162/// identified above in 'a' can also capture the variable (this is done
163/// via tryCaptureVariable for variables and CheckCXXThisCapture for
164/// 'this' by passing in the index of the Lambda identified in step 'a')
165///
166/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
167/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
168/// is at the top of the stack.
169///
170/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
171///
172///
173/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
174/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
175/// lambda which is capture-capable. If the return value evaluates to 'false'
176/// then no lambda is capture-capable for \p VarToCapture.
177
178std::optional<unsigned>
181 ValueDecl *VarToCapture, Sema &S) {
182
183 const std::optional<unsigned> NoLambdaIsCaptureCapable;
184
185 const std::optional<unsigned> OptionalStackIndex =
187 VarToCapture);
188 if (!OptionalStackIndex)
189 return NoLambdaIsCaptureCapable;
190
191 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
192 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
193 S.getCurGenericLambda()) &&
194 "The capture ready lambda for a potential capture can only be the "
195 "current lambda if it is a generic lambda");
196
197 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
198 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
199
200 // If VarToCapture is null, we are attempting to capture 'this'
201 const bool IsCapturingThis = !VarToCapture;
202 const bool IsCapturingVariable = !IsCapturingThis;
203
204 if (IsCapturingVariable) {
205 // Check if the capture-ready lambda can truly capture the variable, by
206 // checking whether all enclosing lambdas of the capture-ready lambda allow
207 // the capture - i.e. make sure it is capture-capable.
208 QualType CaptureType, DeclRefType;
209 const bool CanCaptureVariable =
210 !S.tryCaptureVariable(VarToCapture,
211 /*ExprVarIsUsedInLoc*/ SourceLocation(),
213 /*EllipsisLoc*/ SourceLocation(),
214 /*BuildAndDiagnose*/ false, CaptureType,
215 DeclRefType, &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()) {
236 LSI->GLTemplateParameterList = TemplateParameterList::Create(
237 SemaRef.Context,
238 /*Template kw loc*/ SourceLocation(),
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 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
253 DC = DC->getParent();
254
255 bool IsGenericLambda =
257 // Start constructing the lambda class.
259 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
260 IsGenericLambda, CaptureDefault);
261 DC->addDecl(Class);
262
263 return Class;
264}
265
266/// Determine whether the given context is or is enclosed in an inline
267/// function.
268static bool isInInlineFunction(const DeclContext *DC) {
269 while (!DC->isFileContext()) {
270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
271 if (FD->isInlined())
272 return true;
273
274 DC = DC->getLexicalParent();
275 }
276
277 return false;
278}
279
280std::tuple<MangleNumberingContext *, Decl *>
282 // Compute the context for allocating mangling numbers in the current
283 // expression, if the ABI requires them.
284 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
285
286 enum ContextKind {
287 Normal,
289 DataMember,
290 InlineVariable,
291 TemplatedVariable,
292 Concept
293 } Kind = Normal;
294
295 bool IsInNonspecializedTemplate =
297
298 // Default arguments of member function parameters that appear in a class
299 // definition, as well as the initializers of data members, receive special
300 // treatment. Identify them.
301 if (ManglingContextDecl) {
302 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
303 if (const DeclContext *LexicalDC
304 = Param->getDeclContext()->getLexicalParent())
305 if (LexicalDC->isRecord())
306 Kind = DefaultArgument;
307 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
308 if (Var->getMostRecentDecl()->isInline())
309 Kind = InlineVariable;
310 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
311 Kind = TemplatedVariable;
312 else if (Var->getDescribedVarTemplate())
313 Kind = TemplatedVariable;
314 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
315 if (!VTS->isExplicitSpecialization())
316 Kind = TemplatedVariable;
317 }
318 } else if (isa<FieldDecl>(ManglingContextDecl)) {
319 Kind = DataMember;
320 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
321 Kind = Concept;
322 }
323 }
324
325 // Itanium ABI [5.1.7]:
326 // In the following contexts [...] the one-definition rule requires closure
327 // types in different translation units to "correspond":
328 switch (Kind) {
329 case Normal: {
330 // -- the bodies of inline or templated functions
331 if ((IsInNonspecializedTemplate &&
332 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
334 while (auto *CD = dyn_cast<CapturedDecl>(DC))
335 DC = CD->getParent();
336 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
337 }
338
339 return std::make_tuple(nullptr, nullptr);
340 }
341
342 case Concept:
343 // Concept definitions aren't code generated and thus aren't mangled,
344 // however the ManglingContextDecl is important for the purposes of
345 // re-forming the template argument list of the lambda for constraint
346 // evaluation.
347 case DataMember:
348 // -- default member initializers
349 case DefaultArgument:
350 // -- default arguments appearing in class definitions
351 case InlineVariable:
352 case TemplatedVariable:
353 // -- the initializers of inline or templated variables
354 return std::make_tuple(
356 ManglingContextDecl),
357 ManglingContextDecl);
358 }
359
360 llvm_unreachable("unexpected context");
361}
362
363static QualType
365 TemplateParameterList *TemplateParams,
366 TypeSourceInfo *MethodTypeInfo) {
367 assert(MethodTypeInfo && "expected a non null type");
368
369 QualType MethodType = MethodTypeInfo->getType();
370 // If a lambda appears in a dependent context or is a generic lambda (has
371 // template parameters) and has an 'auto' return type, deduce it to a
372 // dependent type.
373 if (Class->isDependentContext() || TemplateParams) {
374 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
376 if (Result->isUndeducedType()) {
378 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
379 FPT->getExtProtoInfo());
380 }
381 }
382 return MethodType;
383}
384
385// [C++2b] [expr.prim.lambda.closure] p4
386// Given a lambda with a lambda-capture, the type of the explicit object
387// parameter, if any, of the lambda's function call operator (possibly
388// instantiated from a function call operator template) shall be either:
389// - the closure type,
390// - class type publicly and unambiguously derived from the closure type, or
391// - a reference to a possibly cv-qualified such type.
393 CXXMethodDecl *Method, SourceLocation CallLoc) {
395 return false;
396 CXXRecordDecl *RD = Method->getParent();
397 if (Method->getType()->isDependentType())
398 return false;
399 if (RD->isCapturelessLambda())
400 return false;
401
402 ParmVarDecl *Param = Method->getParamDecl(0);
403 QualType ExplicitObjectParameterType = Param->getType()
407 QualType LambdaType = getASTContext().getRecordType(RD);
408 if (LambdaType == ExplicitObjectParameterType)
409 return false;
410
411 // Don't check the same instantiation twice.
412 //
413 // If this call operator is ill-formed, there is no point in issuing
414 // a diagnostic every time it is called because the problem is in the
415 // definition of the derived type, not at the call site.
416 //
417 // FIXME: Move this check to where we instantiate the method? This should
418 // be possible, but the naive approach of just marking the method as invalid
419 // leads to us emitting more diagnostics than we should have to for this case
420 // (1 error here *and* 1 error about there being no matching overload at the
421 // call site). It might be possible to avoid that by also checking if there
422 // is an empty cast path for the method stored in the context (signalling that
423 // we've already diagnosed it) and then just not building the call, but that
424 // doesn't really seem any simpler than diagnosing it at the call site...
425 if (auto It = Context.LambdaCastPaths.find(Method);
426 It != Context.LambdaCastPaths.end())
427 return It->second.empty();
428
430 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
431 /*DetectVirtual=*/false);
432 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
433 Paths)) {
434 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
435 << ExplicitObjectParameterType;
436 return true;
437 }
438
439 if (Paths.isAmbiguous(LambdaType->getCanonicalTypeUnqualified())) {
440 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
441 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
442 << LambdaType << PathsDisplay;
443 return true;
444 }
445
446 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
447 Paths.front(),
448 diag::err_explicit_object_lambda_inaccessible_base))
449 return true;
450
451 BuildBasePathArray(Paths, Path);
452 return false;
453}
454
457 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
458 if (NumberingOverride) {
459 Class->setLambdaNumbering(*NumberingOverride);
460 return;
461 }
462
463 ContextRAII ManglingContext(*this, Class->getDeclContext());
464
465 auto getMangleNumberingContext =
466 [this](CXXRecordDecl *Class,
467 Decl *ManglingContextDecl) -> MangleNumberingContext * {
468 // Get mangle numbering context if there's any extra decl context.
469 if (ManglingContextDecl)
471 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
472 // Otherwise, from that lambda's decl context.
473 auto DC = Class->getDeclContext();
474 while (auto *CD = dyn_cast<CapturedDecl>(DC))
475 DC = CD->getParent();
477 };
478
481 std::tie(MCtx, Numbering.ContextDecl) =
482 getCurrentMangleNumberContext(Class->getDeclContext());
483 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
484 getLangOpts().SYCLIsHost)) {
485 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
486 // ODR. Both device- and host-compilation need to have a consistent naming
487 // on kernel functions. As lambdas are potential part of these `__global__`
488 // function names, they needs numbering following ODR.
489 // Also force for SYCL, since we need this for the
490 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
491 // mangling.
492 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
493 assert(MCtx && "Retrieving mangle numbering context failed!");
494 Numbering.HasKnownInternalLinkage = true;
495 }
496 if (MCtx) {
497 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
498 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
499 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
500 Class->setLambdaNumbering(Numbering);
501
502 if (auto *Source =
503 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
504 Source->AssignedLambdaNumbering(Class);
505 }
506}
507
509 CXXMethodDecl *CallOperator,
510 bool ExplicitResultType) {
511 if (ExplicitResultType) {
512 LSI->HasImplicitReturnType = false;
513 LSI->ReturnType = CallOperator->getReturnType();
514 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
515 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
516 diag::err_lambda_incomplete_result);
517 } else {
518 LSI->HasImplicitReturnType = true;
519 }
520}
521
523 SourceRange IntroducerRange,
524 LambdaCaptureDefault CaptureDefault,
525 SourceLocation CaptureDefaultLoc,
526 bool ExplicitParams, bool Mutable) {
527 LSI->CallOperator = CallOperator;
528 CXXRecordDecl *LambdaClass = CallOperator->getParent();
529 LSI->Lambda = LambdaClass;
530 if (CaptureDefault == LCD_ByCopy)
531 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
532 else if (CaptureDefault == LCD_ByRef)
533 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
534 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
535 LSI->IntroducerRange = IntroducerRange;
536 LSI->ExplicitParams = ExplicitParams;
537 LSI->Mutable = Mutable;
538}
539
542}
543
545 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
546 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
547 ExprResult RequiresClause) {
549 assert(LSI && "Expected a lambda scope");
550 assert(LSI->NumExplicitTemplateParams == 0 &&
551 "Already acted on explicit template parameters");
552 assert(LSI->TemplateParams.empty() &&
553 "Explicit template parameters should come "
554 "before invented (auto) ones");
555 assert(!TParams.empty() &&
556 "No template parameters to act on");
557 LSI->TemplateParams.append(TParams.begin(), TParams.end());
558 LSI->NumExplicitTemplateParams = TParams.size();
559 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
560 LSI->RequiresClause = RequiresClause;
561}
562
563/// If this expression is an enumerator-like expression of some type
564/// T, return the type T; otherwise, return null.
565///
566/// Pointer comparisons on the result here should always work because
567/// it's derived from either the parent of an EnumConstantDecl
568/// (i.e. the definition) or the declaration returned by
569/// EnumType::getDecl() (i.e. the definition).
571 // An expression is an enumerator-like expression of type T if,
572 // ignoring parens and parens-like expressions:
573 E = E->IgnoreParens();
574
575 // - it is an enumerator whose enum type is T or
576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
578 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
579 return cast<EnumDecl>(D->getDeclContext());
580 }
581 return nullptr;
582 }
583
584 // - it is a comma expression whose RHS is an enumerator-like
585 // expression of type T or
586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
587 if (BO->getOpcode() == BO_Comma)
588 return findEnumForBlockReturn(BO->getRHS());
589 return nullptr;
590 }
591
592 // - it is a statement-expression whose value expression is an
593 // enumerator-like expression of type T or
594 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
595 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
596 return findEnumForBlockReturn(last);
597 return nullptr;
598 }
599
600 // - it is a ternary conditional operator (not the GNU ?:
601 // extension) whose second and third operands are
602 // enumerator-like expressions of type T or
603 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
604 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
605 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
606 return ED;
607 return nullptr;
608 }
609
610 // (implicitly:)
611 // - it is an implicit integral conversion applied to an
612 // enumerator-like expression of type T or
613 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
614 // We can sometimes see integral conversions in valid
615 // enumerator-like expressions.
616 if (ICE->getCastKind() == CK_IntegralCast)
617 return findEnumForBlockReturn(ICE->getSubExpr());
618
619 // Otherwise, just rely on the type.
620 }
621
622 // - it is an expression of that formal enum type.
623 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
624 return ET->getDecl();
625 }
626
627 // Otherwise, nope.
628 return nullptr;
629}
630
631/// Attempt to find a type T for which the returned expression of the
632/// given statement is an enumerator-like expression of that type.
634 if (Expr *retValue = ret->getRetValue())
635 return findEnumForBlockReturn(retValue);
636 return nullptr;
637}
638
639/// Attempt to find a common type T for which all of the returned
640/// expressions in a block are enumerator-like expressions of that
641/// type.
643 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
644
645 // Try to find one for the first return.
647 if (!ED) return nullptr;
648
649 // Check that the rest of the returns have the same enum.
650 for (++i; i != e; ++i) {
651 if (findEnumForBlockReturn(*i) != ED)
652 return nullptr;
653 }
654
655 // Never infer an anonymous enum type.
656 if (!ED->hasNameForLinkage()) return nullptr;
657
658 return ED;
659}
660
661/// Adjust the given return statements so that they formally return
662/// the given type. It should require, at most, an IntegralCast.
664 QualType returnType) {
666 i = returns.begin(), e = returns.end(); i != e; ++i) {
667 ReturnStmt *ret = *i;
668 Expr *retValue = ret->getRetValue();
669 if (S.Context.hasSameType(retValue->getType(), returnType))
670 continue;
671
672 // Right now we only support integral fixup casts.
673 assert(returnType->isIntegralOrUnscopedEnumerationType());
674 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
675
676 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
677
678 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
679 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
680 /*base path*/ nullptr, VK_PRValue,
682 if (cleanups) {
683 cleanups->setSubExpr(E);
684 } else {
685 ret->setRetValue(E);
686 }
687 }
688}
689
691 assert(CSI.HasImplicitReturnType);
692 // If it was ever a placeholder, it had to been deduced to DependentTy.
693 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
694 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
695 "lambda expressions use auto deduction in C++14 onwards");
696
697 // C++ core issue 975:
698 // If a lambda-expression does not include a trailing-return-type,
699 // it is as if the trailing-return-type denotes the following type:
700 // - if there are no return statements in the compound-statement,
701 // or all return statements return either an expression of type
702 // void or no expression or braced-init-list, the type void;
703 // - otherwise, if all return statements return an expression
704 // and the types of the returned expressions after
705 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
706 // array-to-pointer conversion (4.2 [conv.array]), and
707 // function-to-pointer conversion (4.3 [conv.func]) are the
708 // same, that common type;
709 // - otherwise, the program is ill-formed.
710 //
711 // C++ core issue 1048 additionally removes top-level cv-qualifiers
712 // from the types of returned expressions to match the C++14 auto
713 // deduction rules.
714 //
715 // In addition, in blocks in non-C++ modes, if all of the return
716 // statements are enumerator-like expressions of some type T, where
717 // T has a name for linkage, then we infer the return type of the
718 // block to be that type.
719
720 // First case: no return statements, implicit void return type.
721 ASTContext &Ctx = getASTContext();
722 if (CSI.Returns.empty()) {
723 // It's possible there were simply no /valid/ return statements.
724 // In this case, the first one we found may have at least given us a type.
725 if (CSI.ReturnType.isNull())
726 CSI.ReturnType = Ctx.VoidTy;
727 return;
728 }
729
730 // Second case: at least one return statement has dependent type.
731 // Delay type checking until instantiation.
732 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
733 if (CSI.ReturnType->isDependentType())
734 return;
735
736 // Try to apply the enum-fuzz rule.
737 if (!getLangOpts().CPlusPlus) {
738 assert(isa<BlockScopeInfo>(CSI));
740 if (ED) {
743 return;
744 }
745 }
746
747 // Third case: only one return statement. Don't bother doing extra work!
748 if (CSI.Returns.size() == 1)
749 return;
750
751 // General case: many return statements.
752 // Check that they all have compatible return types.
753
754 // We require the return types to strictly match here.
755 // Note that we've already done the required promotions as part of
756 // processing the return statement.
757 for (const ReturnStmt *RS : CSI.Returns) {
758 const Expr *RetE = RS->getRetValue();
759
760 QualType ReturnType =
761 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
762 if (Context.getCanonicalFunctionResultType(ReturnType) ==
764 // Use the return type with the strictest possible nullability annotation.
765 auto RetTyNullability = ReturnType->getNullability();
766 auto BlockNullability = CSI.ReturnType->getNullability();
767 if (BlockNullability &&
768 (!RetTyNullability ||
769 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
770 CSI.ReturnType = ReturnType;
771 continue;
772 }
773
774 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
775 // TODO: It's possible that the *first* return is the divergent one.
776 Diag(RS->getBeginLoc(),
777 diag::err_typecheck_missing_return_type_incompatible)
778 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
779 // Continue iterating so that we keep emitting diagnostics.
780 }
781}
782
784 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
785 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
786 bool IsDirectInit, Expr *&Init) {
787 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
788 // deduce against.
789 QualType DeductType = Context.getAutoDeductType();
790 TypeLocBuilder TLB;
791 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
792 TL.setNameLoc(Loc);
793 if (ByRef) {
794 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
795 assert(!DeductType.isNull() && "can't build reference to auto");
796 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
797 }
798 if (EllipsisLoc.isValid()) {
799 if (Init->containsUnexpandedParameterPack()) {
800 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
801 ? diag::warn_cxx17_compat_init_capture_pack
802 : diag::ext_init_capture_pack);
803 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
804 /*ExpectPackInType=*/false);
805 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
806 } else {
807 // Just ignore the ellipsis for now and form a non-pack variable. We'll
808 // diagnose this later when we try to capture it.
809 }
810 }
811 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
812
813 // Deduce the type of the init capture.
815 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
816 SourceRange(Loc, Loc), IsDirectInit, Init);
817 if (DeducedType.isNull())
818 return QualType();
819
820 // Are we a non-list direct initialization?
821 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
822
823 // Perform initialization analysis and ensure any implicit conversions
824 // (such as lvalue-to-rvalue) are enforced.
825 InitializedEntity Entity =
827 InitializationKind Kind =
828 IsDirectInit
829 ? (CXXDirectInit ? InitializationKind::CreateDirect(
830 Loc, Init->getBeginLoc(), Init->getEndLoc())
832 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
833
834 MultiExprArg Args = Init;
835 if (CXXDirectInit)
836 Args =
837 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
838 QualType DclT;
839 InitializationSequence InitSeq(*this, Entity, Kind, Args);
840 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
841
842 if (Result.isInvalid())
843 return QualType();
844
845 Init = Result.getAs<Expr>();
846 return DeducedType;
847}
848
850 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
851 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
852 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
853 // rather than reconstructing it here.
854 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
855 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
856 PETL.setEllipsisLoc(EllipsisLoc);
857
858 // Create a dummy variable representing the init-capture. This is not actually
859 // used as a variable, and only exists as a way to name and refer to the
860 // init-capture.
861 // FIXME: Pass in separate source locations for '&' and identifier.
862 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
863 InitCaptureType, TSI, SC_Auto);
864 NewVD->setInitCapture(true);
865 NewVD->setReferenced(true);
866 // FIXME: Pass in a VarDecl::InitializationStyle.
867 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
868 NewVD->markUsed(Context);
869 NewVD->setInit(Init);
870 if (NewVD->isParameterPack())
871 getCurLambda()->LocalPacks.push_back(NewVD);
872 return NewVD;
873}
874
875void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
876 assert(Var->isInitCapture() && "init capture flag should be set");
877 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
878 /*isNested=*/false, Var->getLocation(), SourceLocation(),
879 Var->getType(), /*Invalid=*/false);
880}
881
882// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
883// check that the current lambda is in a consistent or fully constructed state.
885 assert(!S.FunctionScopes.empty());
886 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
887}
888
889static TypeSourceInfo *
891 // C++11 [expr.prim.lambda]p4:
892 // If a lambda-expression does not include a lambda-declarator, it is as
893 // if the lambda-declarator were ().
895 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
896 EPI.HasTrailingReturn = true;
897 EPI.TypeQuals.addConst();
899 if (AS != LangAS::Default)
901
902 // C++1y [expr.prim.lambda]:
903 // The lambda return type is 'auto', which is replaced by the
904 // trailing-return type if provided and/or deduced from 'return'
905 // statements
906 // We don't do this before C++1y, because we don't support deduced return
907 // types there.
908 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
911 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
912 std::nullopt, EPI);
913 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
914}
915
917 Declarator &ParamInfo, Scope *CurScope,
919 bool &ExplicitResultType) {
920
921 ExplicitResultType = false;
922
923 assert(
924 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
927 "Unexpected storage specifier");
928 bool IsLambdaStatic =
930
931 TypeSourceInfo *MethodTyInfo;
932
933 if (ParamInfo.getNumTypeObjects() == 0) {
934 MethodTyInfo = getDummyLambdaType(S, Loc);
935 } else {
936 // Check explicit parameters
937 S.CheckExplicitObjectLambda(ParamInfo);
938
940
941 bool HasExplicitObjectParameter =
943
944 ExplicitResultType = FTI.hasTrailingReturnType();
945 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
946 !HasExplicitObjectParameter)
948
949 if (ExplicitResultType && S.getLangOpts().HLSL) {
950 QualType RetTy = FTI.getTrailingReturnType().get();
951 if (!RetTy.isNull()) {
952 // HLSL does not support specifying an address space on a lambda return
953 // type.
954 LangAS AddressSpace = RetTy.getAddressSpace();
955 if (AddressSpace != LangAS::Default)
957 diag::err_return_value_with_address_space);
958 }
959 }
960
961 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
962 assert(MethodTyInfo && "no type from lambda-declarator");
963
964 // Check for unexpanded parameter packs in the method type.
965 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
966 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
968 }
969 return MethodTyInfo;
970}
971
974
975 // C++20 [expr.prim.lambda.closure]p3:
976 // The closure type for a lambda-expression has a public inline function
977 // call operator (for a non-generic lambda) or function call operator
978 // template (for a generic lambda) whose parameters and return type are
979 // described by the lambda-expression's parameter-declaration-clause
980 // and trailing-return-type respectively.
981 DeclarationName MethodName =
983 DeclarationNameLoc MethodNameLoc =
987 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
988 MethodNameLoc),
989 QualType(), /*Tinfo=*/nullptr, SC_None,
990 getCurFPFeatures().isFPConstrained(),
992 /*TrailingRequiresClause=*/nullptr);
993 Method->setAccess(AS_public);
994 return Method;
995}
996
998 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
999 TemplateParameterList *TemplateParams) {
1000 assert(TemplateParams && "no template parameters");
1002 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1003 TemplateParams, CallOperator);
1004 TemplateMethod->setAccess(AS_public);
1005 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1006}
1007
1009 CXXMethodDecl *Method, SourceLocation LambdaLoc,
1010 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
1011 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1013 bool HasExplicitResultType) {
1014
1016
1017 if (TrailingRequiresClause)
1018 Method->setTrailingRequiresClause(TrailingRequiresClause);
1019
1020 TemplateParameterList *TemplateParams =
1022
1023 DeclContext *DC = Method->getLexicalDeclContext();
1024 Method->setLexicalDeclContext(LSI->Lambda);
1025 if (TemplateParams) {
1026 FunctionTemplateDecl *TemplateMethod =
1028 assert(TemplateMethod &&
1029 "AddTemplateParametersToLambdaCallOperator should have been called");
1030
1031 LSI->Lambda->addDecl(TemplateMethod);
1032 TemplateMethod->setLexicalDeclContext(DC);
1033 } else {
1034 LSI->Lambda->addDecl(Method);
1035 }
1036 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1037 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1038
1039 Method->setLexicalDeclContext(DC);
1040 Method->setLocation(LambdaLoc);
1041 Method->setInnerLocStart(CallOperatorLoc);
1042 Method->setTypeSourceInfo(MethodTyInfo);
1043 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1044 TemplateParams, MethodTyInfo));
1045 Method->setConstexprKind(ConstexprKind);
1046 Method->setStorageClass(SC);
1047 if (!Params.empty()) {
1048 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1049 Method->setParams(Params);
1050 for (auto P : Method->parameters()) {
1051 assert(P && "null in a parameter list");
1052 P->setOwningFunction(Method);
1053 }
1054 }
1055
1056 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1057}
1058
1060 Scope *CurrentScope) {
1061
1063 assert(LSI && "LambdaScopeInfo should be on stack!");
1064
1065 if (Intro.Default == LCD_ByCopy)
1066 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1067 else if (Intro.Default == LCD_ByRef)
1068 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1069 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1070 LSI->IntroducerRange = Intro.Range;
1071 LSI->AfterParameterList = false;
1072
1073 assert(LSI->NumExplicitTemplateParams == 0);
1074
1075 // Determine if we're within a context where we know that the lambda will
1076 // be dependent, because there are template parameters in scope.
1077 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1079 if (CurScope->getTemplateParamParent() != nullptr) {
1080 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1081 } else if (Scope *P = CurScope->getParent()) {
1082 // Given a lambda defined inside a requires expression,
1083 //
1084 // struct S {
1085 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1086 // {}
1087 // };
1088 //
1089 // The parameter var is not injected into the function Decl at the point of
1090 // parsing lambda. In such scenarios, perceiving it as dependent could
1091 // result in the constraint being evaluated, which matches what GCC does.
1092 while (P->getEntity() && P->getEntity()->isRequiresExprBody())
1093 P = P->getParent();
1094 if (P->isFunctionDeclarationScope() &&
1095 llvm::any_of(P->decls(), [](Decl *D) {
1096 return isa<ParmVarDecl>(D) &&
1097 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1098 }))
1099 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1100 }
1101
1103 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1104 LSI->Lambda = Class;
1105
1107 LSI->CallOperator = Method;
1109
1110 PushDeclContext(CurScope, Method);
1111
1112 bool ContainsUnexpandedParameterPack = false;
1113
1114 // Distinct capture names, for diagnostics.
1115 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1116
1117 // Handle explicit captures.
1118 SourceLocation PrevCaptureLoc =
1119 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1120 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1121 PrevCaptureLoc = C->Loc, ++C) {
1122 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1123 if (C->Kind == LCK_StarThis)
1124 Diag(C->Loc, !getLangOpts().CPlusPlus17
1125 ? diag::ext_star_this_lambda_capture_cxx17
1126 : diag::warn_cxx14_compat_star_this_lambda_capture);
1127
1128 // C++11 [expr.prim.lambda]p8:
1129 // An identifier or this shall not appear more than once in a
1130 // lambda-capture.
1131 if (LSI->isCXXThisCaptured()) {
1132 Diag(C->Loc, diag::err_capture_more_than_once)
1133 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1135 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1136 continue;
1137 }
1138
1139 // C++20 [expr.prim.lambda]p8:
1140 // If a lambda-capture includes a capture-default that is =,
1141 // each simple-capture of that lambda-capture shall be of the form
1142 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1143 // redundant but accepted for compatibility with ISO C++14. --end note ]
1144 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1145 Diag(C->Loc, !getLangOpts().CPlusPlus20
1146 ? diag::ext_equals_this_lambda_capture_cxx20
1147 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1148
1149 // C++11 [expr.prim.lambda]p12:
1150 // If this is captured by a local lambda expression, its nearest
1151 // enclosing function shall be a non-static member function.
1152 QualType ThisCaptureType = getCurrentThisType();
1153 if (ThisCaptureType.isNull()) {
1154 Diag(C->Loc, diag::err_this_capture) << true;
1155 continue;
1156 }
1157
1158 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1159 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1160 C->Kind == LCK_StarThis);
1161 if (!LSI->Captures.empty())
1162 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1163 continue;
1164 }
1165
1166 assert(C->Id && "missing identifier for capture");
1167
1168 if (C->Init.isInvalid())
1169 continue;
1170
1171 ValueDecl *Var = nullptr;
1172 if (C->Init.isUsable()) {
1174 ? diag::warn_cxx11_compat_init_capture
1175 : diag::ext_init_capture);
1176
1177 // If the initializer expression is usable, but the InitCaptureType
1178 // is not, then an error has occurred - so ignore the capture for now.
1179 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1180 // FIXME: we should create the init capture variable and mark it invalid
1181 // in this case.
1182 if (C->InitCaptureType.get().isNull())
1183 continue;
1184
1185 if (C->Init.get()->containsUnexpandedParameterPack() &&
1186 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1188
1189 unsigned InitStyle;
1190 switch (C->InitKind) {
1192 llvm_unreachable("not an init-capture?");
1194 InitStyle = VarDecl::CInit;
1195 break;
1197 InitStyle = VarDecl::CallInit;
1198 break;
1200 InitStyle = VarDecl::ListInit;
1201 break;
1202 }
1203 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1204 C->EllipsisLoc, C->Id, InitStyle,
1205 C->Init.get(), Method);
1206 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1207 if (auto *V = dyn_cast<VarDecl>(Var))
1208 CheckShadow(CurrentScope, V);
1209 PushOnScopeChains(Var, CurrentScope, false);
1210 } else {
1211 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1212 "init capture has valid but null init?");
1213
1214 // C++11 [expr.prim.lambda]p8:
1215 // If a lambda-capture includes a capture-default that is &, the
1216 // identifiers in the lambda-capture shall not be preceded by &.
1217 // If a lambda-capture includes a capture-default that is =, [...]
1218 // each identifier it contains shall be preceded by &.
1219 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1220 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1222 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1223 continue;
1224 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1225 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1227 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1228 continue;
1229 }
1230
1231 // C++11 [expr.prim.lambda]p10:
1232 // The identifiers in a capture-list are looked up using the usual
1233 // rules for unqualified name lookup (3.4.1)
1234 DeclarationNameInfo Name(C->Id, C->Loc);
1235 LookupResult R(*this, Name, LookupOrdinaryName);
1236 LookupName(R, CurScope);
1237 if (R.isAmbiguous())
1238 continue;
1239 if (R.empty()) {
1240 // FIXME: Disable corrections that would add qualification?
1241 CXXScopeSpec ScopeSpec;
1242 DeclFilterCCC<VarDecl> Validator{};
1243 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1244 continue;
1245 }
1246
1247 if (auto *BD = R.getAsSingle<BindingDecl>())
1248 Var = BD;
1249 else if (R.getAsSingle<FieldDecl>()) {
1250 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1251 << C->Id;
1252 continue;
1253 } else
1254 Var = R.getAsSingle<VarDecl>();
1255 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1256 continue;
1257 }
1258
1259 // C++11 [expr.prim.lambda]p10:
1260 // [...] each such lookup shall find a variable with automatic storage
1261 // duration declared in the reaching scope of the local lambda expression.
1262 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1263 if (!Var) {
1264 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1265 continue;
1266 }
1267
1268 // C++11 [expr.prim.lambda]p8:
1269 // An identifier or this shall not appear more than once in a
1270 // lambda-capture.
1271 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1272 !Inserted) {
1273 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1274 !Var->isInitCapture()) {
1275 Diag(C->Loc, diag::err_capture_more_than_once)
1276 << C->Id << It->second->getBeginLoc()
1278 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1279 Var->setInvalidDecl();
1280 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1282 } else {
1283 // Previous capture captured something different (one or both was
1284 // an init-capture): no fixit.
1285 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1286 continue;
1287 }
1288 }
1289
1290 // Ignore invalid decls; they'll just confuse the code later.
1291 if (Var->isInvalidDecl())
1292 continue;
1293
1294 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1295
1296 if (!Underlying->hasLocalStorage()) {
1297 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1298 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1299 continue;
1300 }
1301
1302 // C++11 [expr.prim.lambda]p23:
1303 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1304 SourceLocation EllipsisLoc;
1305 if (C->EllipsisLoc.isValid()) {
1306 if (Var->isParameterPack()) {
1307 EllipsisLoc = C->EllipsisLoc;
1308 } else {
1309 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1310 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1311 : SourceRange(C->Loc));
1312
1313 // Just ignore the ellipsis.
1314 }
1315 } else if (Var->isParameterPack()) {
1316 ContainsUnexpandedParameterPack = true;
1317 }
1318
1319 if (C->Init.isUsable()) {
1320 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1321 PushOnScopeChains(Var, CurScope, false);
1322 } else {
1325 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1326 }
1327 if (!LSI->Captures.empty())
1328 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1329 }
1331 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1333}
1334
1336 SourceLocation MutableLoc) {
1337
1339 LSI->Mutable = MutableLoc.isValid();
1340 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1341
1342 // C++11 [expr.prim.lambda]p9:
1343 // A lambda-expression whose smallest enclosing scope is a block scope is a
1344 // local lambda expression; any other lambda expression shall not have a
1345 // capture-default or simple-capture in its lambda-introducer.
1346 //
1347 // For simple-captures, this is covered by the check below that any named
1348 // entity is a variable that can be captured.
1349 //
1350 // For DR1632, we also allow a capture-default in any context where we can
1351 // odr-use 'this' (in particular, in a default initializer for a non-static
1352 // data member).
1353 if (Intro.Default != LCD_None &&
1354 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1355 (getCurrentThisType().isNull() ||
1356 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1357 /*BuildAndDiagnose=*/false)))
1358 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1359}
1360
1364 PushDeclContext(LambdaScope, LSI->CallOperator);
1365
1366 for (const DeclaratorChunk::ParamInfo &P : Params) {
1367 auto *Param = cast<ParmVarDecl>(P.Param);
1368 Param->setOwningFunction(LSI->CallOperator);
1369 if (Param->getIdentifier())
1370 PushOnScopeChains(Param, LambdaScope, false);
1371 }
1372
1373 // After the parameter list, we may parse a noexcept/requires/trailing return
1374 // type which need to know whether the call operator constiture a dependent
1375 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1376 // now.
1377 TemplateParameterList *TemplateParams =
1379 if (TemplateParams) {
1381 TemplateParams);
1382 LSI->Lambda->setLambdaIsGeneric(true);
1384 TemplateParams->containsUnexpandedParameterPack();
1385 }
1386 LSI->AfterParameterList = true;
1387}
1388
1390 Declarator &ParamInfo,
1391 const DeclSpec &DS) {
1392
1395
1397 bool ExplicitResultType;
1398
1399 SourceLocation TypeLoc, CallOperatorLoc;
1400 if (ParamInfo.getNumTypeObjects() == 0) {
1401 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1402 } else {
1403 unsigned Index;
1404 ParamInfo.isFunctionDeclarator(Index);
1405 const auto &Object = ParamInfo.getTypeObject(Index);
1406 TypeLoc =
1407 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1408 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1409 }
1410
1411 CXXRecordDecl *Class = LSI->Lambda;
1412 CXXMethodDecl *Method = LSI->CallOperator;
1413
1414 TypeSourceInfo *MethodTyInfo = getLambdaType(
1415 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1416
1417 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1418
1419 if (ParamInfo.isFunctionDeclarator() != 0 &&
1421 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1422 Params.reserve(Params.size());
1423 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1424 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1425 Param->setScopeInfo(0, Params.size());
1426 Params.push_back(Param);
1427 }
1428 }
1429
1430 bool IsLambdaStatic =
1432
1434 Method, Intro.Range.getBegin(), CallOperatorLoc,
1435 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1436 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1437 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1438
1440
1441 // This represents the function body for the lambda function, check if we
1442 // have to apply optnone due to a pragma.
1443 AddRangeBasedOptnone(Method);
1444
1445 // code_seg attribute on lambda apply to the method.
1447 Method, /*IsDefinition=*/true))
1448 Method->addAttr(A);
1449
1450 // Attributes on the lambda apply to the method.
1451 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1452
1453 // CUDA lambdas get implicit host and device attributes.
1454 if (getLangOpts().CUDA)
1455 CUDA().SetLambdaAttrs(Method);
1456
1457 // OpenMP lambdas might get assumumption attributes.
1458 if (LangOpts.OpenMP)
1460
1462
1463 for (auto &&C : LSI->Captures) {
1464 if (!C.isVariableCapture())
1465 continue;
1466 ValueDecl *Var = C.getVariable();
1467 if (Var && Var->isInitCapture()) {
1468 PushOnScopeChains(Var, CurScope, false);
1469 }
1470 }
1471
1472 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1473 for (const auto &Capture : Intro.Captures) {
1474 if (Capture.Id == Param->getIdentifier()) {
1475 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1476 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1477 << Capture.Id << true;
1478 return false;
1479 }
1480 }
1481 return true;
1482 };
1483
1484 for (ParmVarDecl *P : Params) {
1485 if (!P->getIdentifier())
1486 continue;
1487 if (CheckRedefinition(P))
1488 CheckShadow(CurScope, P);
1489 PushOnScopeChains(P, CurScope);
1490 }
1491
1492 // C++23 [expr.prim.lambda.capture]p5:
1493 // If an identifier in a capture appears as the declarator-id of a parameter
1494 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1495 // template parameter of the lambda-expression's template-parameter-list, the
1496 // program is ill-formed.
1497 TemplateParameterList *TemplateParams =
1499 if (TemplateParams) {
1500 for (const auto *TP : TemplateParams->asArray()) {
1501 if (!TP->getIdentifier())
1502 continue;
1503 for (const auto &Capture : Intro.Captures) {
1504 if (Capture.Id == TP->getIdentifier()) {
1505 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1507 }
1508 }
1509 }
1510 }
1511
1512 // C++20: dcl.decl.general p4:
1513 // The optional requires-clause ([temp.pre]) in an init-declarator or
1514 // member-declarator shall be present only if the declarator declares a
1515 // templated function ([dcl.fct]).
1516 if (Expr *TRC = Method->getTrailingRequiresClause()) {
1517 // [temp.pre]/8:
1518 // An entity is templated if it is
1519 // - a template,
1520 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1521 // templated entity,
1522 // - a member of a templated entity,
1523 // - an enumerator for an enumeration that is a templated entity, or
1524 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1525 // appearing in the declaration of a templated entity. [Note 6: A local
1526 // class, a local or block variable, or a friend function defined in a
1527 // templated entity is a templated entity. — end note]
1528 //
1529 // A templated function is a function template or a function that is
1530 // templated. A templated class is a class template or a class that is
1531 // templated. A templated variable is a variable template or a variable
1532 // that is templated.
1533
1534 // Note: we only have to check if this is defined in a template entity, OR
1535 // if we are a template, since the rest don't apply. The requires clause
1536 // applies to the call operator, which we already know is a member function,
1537 // AND defined.
1538 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1539 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1540 }
1541 }
1542
1543 // Enter a new evaluation context to insulate the lambda from any
1544 // cleanups from the enclosing full-expression.
1549 ExprEvalContexts.back().InImmediateFunctionContext =
1550 LSI->CallOperator->isConsteval();
1551 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1552 getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1553}
1554
1556 bool IsInstantiation) {
1557 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1558
1559 // Leave the expression-evaluation context.
1562
1563 // Leave the context of the lambda.
1564 if (!IsInstantiation)
1566
1567 // Finalize the lambda.
1568 CXXRecordDecl *Class = LSI->Lambda;
1569 Class->setInvalidDecl();
1570 SmallVector<Decl*, 4> Fields(Class->fields());
1571 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1573 CheckCompletedCXXClass(nullptr, Class);
1574
1576}
1577
1578template <typename Func>
1580 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1582 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1584 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1585 CallingConv CallOpCC = CallOpProto.getCallConv();
1586
1587 /// Implement emitting a version of the operator for many of the calling
1588 /// conventions for MSVC, as described here:
1589 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1590 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1591 /// vectorcall are generated by MSVC when it is supported by the target.
1592 /// Additionally, we are ensuring that the default-free/default-member and
1593 /// call-operator calling convention are generated as well.
1594 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1595 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1596 /// that someone who intentionally places 'thiscall' on the lambda call
1597 /// operator will still get that overload, since we don't have the a way of
1598 /// detecting the attribute by the time we get here.
1599 if (S.getLangOpts().MSVCCompat) {
1600 CallingConv Convs[] = {
1602 DefaultFree, DefaultMember, CallOpCC};
1603 llvm::sort(Convs);
1604 llvm::iterator_range<CallingConv *> Range(
1605 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1606 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1607
1608 for (CallingConv C : Range) {
1610 F(C);
1611 }
1612 return;
1613 }
1614
1615 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1616 F(DefaultFree);
1617 F(DefaultMember);
1618 } else {
1619 F(CallOpCC);
1620 }
1621}
1622
1623// Returns the 'standard' calling convention to be used for the lambda
1624// conversion function, that is, the 'free' function calling convention unless
1625// it is overridden by a non-default calling convention attribute.
1626static CallingConv
1628 const FunctionProtoType *CallOpProto) {
1630 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1632 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1633 CallingConv CallOpCC = CallOpProto->getCallConv();
1634
1635 // If the call-operator hasn't been changed, return both the 'free' and
1636 // 'member' function calling convention.
1637 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1638 return DefaultFree;
1639 return CallOpCC;
1640}
1641
1643 const FunctionProtoType *CallOpProto, CallingConv CC) {
1644 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1645 CallOpProto->getExtProtoInfo();
1646 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1647 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1648 InvokerExtInfo.TypeQuals = Qualifiers();
1649 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1650 "Lambda's call operator should not have a reference qualifier");
1651 return Context.getFunctionType(CallOpProto->getReturnType(),
1652 CallOpProto->getParamTypes(), InvokerExtInfo);
1653}
1654
1655/// Add a lambda's conversion to function pointer, as described in
1656/// C++11 [expr.prim.lambda]p6.
1657static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1659 CXXMethodDecl *CallOperator,
1660 QualType InvokerFunctionTy) {
1661 // This conversion is explicitly disabled if the lambda's function has
1662 // pass_object_size attributes on any of its parameters.
1663 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1664 return P->hasAttr<PassObjectSizeAttr>();
1665 };
1666 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1667 return;
1668
1669 // Add the conversion to function pointer.
1670 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1671
1672 // Create the type of the conversion function.
1675 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1676 // The conversion function is always const and noexcept.
1677 ConvExtInfo.TypeQuals = Qualifiers();
1678 ConvExtInfo.TypeQuals.addConst();
1679 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1680 QualType ConvTy =
1681 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1682
1683 SourceLocation Loc = IntroducerRange.getBegin();
1684 DeclarationName ConversionName
1686 S.Context.getCanonicalType(PtrToFunctionTy));
1687 // Construct a TypeSourceInfo for the conversion function, and wire
1688 // all the parameters appropriately for the FunctionProtoTypeLoc
1689 // so that everything works during transformation/instantiation of
1690 // generic lambdas.
1691 // The main reason for wiring up the parameters of the conversion
1692 // function with that of the call operator is so that constructs
1693 // like the following work:
1694 // auto L = [](auto b) { <-- 1
1695 // return [](auto a) -> decltype(a) { <-- 2
1696 // return a;
1697 // };
1698 // };
1699 // int (*fp)(int) = L(5);
1700 // Because the trailing return type can contain DeclRefExprs that refer
1701 // to the original call operator's variables, we hijack the call
1702 // operators ParmVarDecls below.
1703 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1704 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1705 DeclarationNameLoc ConvNameLoc =
1706 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1707
1708 // The conversion function is a conversion to a pointer-to-function.
1709 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1710 FunctionProtoTypeLoc ConvTL =
1712 // Get the result of the conversion function which is a pointer-to-function.
1713 PointerTypeLoc PtrToFunctionTL =
1714 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1715 // Do the same for the TypeSourceInfo that is used to name the conversion
1716 // operator.
1717 PointerTypeLoc ConvNamePtrToFunctionTL =
1718 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1719
1720 // Get the underlying function types that the conversion function will
1721 // be converting to (should match the type of the call operator).
1722 FunctionProtoTypeLoc CallOpConvTL =
1723 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1724 FunctionProtoTypeLoc CallOpConvNameTL =
1725 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1726
1727 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1728 // These parameter's are essentially used to transform the name and
1729 // the type of the conversion operator. By using the same parameters
1730 // as the call operator's we don't have to fix any back references that
1731 // the trailing return type of the call operator's uses (such as
1732 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1733 // - we can simply use the return type of the call operator, and
1734 // everything should work.
1735 SmallVector<ParmVarDecl *, 4> InvokerParams;
1736 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1737 ParmVarDecl *From = CallOperator->getParamDecl(I);
1738
1739 InvokerParams.push_back(ParmVarDecl::Create(
1740 S.Context,
1741 // Temporarily add to the TU. This is set to the invoker below.
1743 From->getLocation(), From->getIdentifier(), From->getType(),
1744 From->getTypeSourceInfo(), From->getStorageClass(),
1745 /*DefArg=*/nullptr));
1746 CallOpConvTL.setParam(I, From);
1747 CallOpConvNameTL.setParam(I, From);
1748 }
1749
1751 S.Context, Class, Loc,
1752 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1754 /*isInline=*/true, ExplicitSpecifier(),
1757 CallOperator->getBody()->getEndLoc());
1758 Conversion->setAccess(AS_public);
1759 Conversion->setImplicit(true);
1760
1761 // A non-generic lambda may still be a templated entity. We need to preserve
1762 // constraints when converting the lambda to a function pointer. See GH63181.
1763 if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1764 Conversion->setTrailingRequiresClause(Requires);
1765
1766 if (Class->isGenericLambda()) {
1767 // Create a template version of the conversion operator, using the template
1768 // parameter list of the function call operator.
1769 FunctionTemplateDecl *TemplateCallOperator =
1770 CallOperator->getDescribedFunctionTemplate();
1771 FunctionTemplateDecl *ConversionTemplate =
1773 Loc, ConversionName,
1774 TemplateCallOperator->getTemplateParameters(),
1775 Conversion);
1776 ConversionTemplate->setAccess(AS_public);
1777 ConversionTemplate->setImplicit(true);
1778 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1779 Class->addDecl(ConversionTemplate);
1780 } else
1781 Class->addDecl(Conversion);
1782
1783 // If the lambda is not static, we need to add a static member
1784 // function that will be the result of the conversion with a
1785 // certain unique ID.
1786 // When it is static we just return the static call operator instead.
1787 if (CallOperator->isImplicitObjectMemberFunction()) {
1788 DeclarationName InvokerName =
1790 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1791 // we should get a prebuilt TrivialTypeSourceInfo from Context
1792 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1793 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1794 // loop below and then use its Params to set Invoke->setParams(...) below.
1795 // This would avoid the 'const' qualifier of the calloperator from
1796 // contaminating the type of the invoker, which is currently adjusted
1797 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1798 // trailing return type of the invoker would require a visitor to rebuild
1799 // the trailing return type and adjusting all back DeclRefExpr's to refer
1800 // to the new static invoker parameters - not the call operator's.
1802 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1803 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1805 /*isInline=*/true, CallOperator->getConstexprKind(),
1806 CallOperator->getBody()->getEndLoc());
1807 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1808 InvokerParams[I]->setOwningFunction(Invoke);
1809 Invoke->setParams(InvokerParams);
1810 Invoke->setAccess(AS_private);
1811 Invoke->setImplicit(true);
1812 if (Class->isGenericLambda()) {
1813 FunctionTemplateDecl *TemplateCallOperator =
1814 CallOperator->getDescribedFunctionTemplate();
1815 FunctionTemplateDecl *StaticInvokerTemplate =
1817 S.Context, Class, Loc, InvokerName,
1818 TemplateCallOperator->getTemplateParameters(), Invoke);
1819 StaticInvokerTemplate->setAccess(AS_private);
1820 StaticInvokerTemplate->setImplicit(true);
1821 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1822 Class->addDecl(StaticInvokerTemplate);
1823 } else
1824 Class->addDecl(Invoke);
1825 }
1826}
1827
1828/// Add a lambda's conversion to function pointers, as described in
1829/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1830/// single pointer conversion. In the event that the default calling convention
1831/// for free and member functions is different, it will emit both conventions.
1832static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1834 CXXMethodDecl *CallOperator) {
1835 const FunctionProtoType *CallOpProto =
1836 CallOperator->getType()->castAs<FunctionProtoType>();
1837
1839 S, *CallOpProto, [&](CallingConv CC) {
1840 QualType InvokerFunctionTy =
1841 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1842 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1843 InvokerFunctionTy);
1844 });
1845}
1846
1847/// Add a lambda's conversion to block pointer.
1849 SourceRange IntroducerRange,
1851 CXXMethodDecl *CallOperator) {
1852 const FunctionProtoType *CallOpProto =
1853 CallOperator->getType()->castAs<FunctionProtoType>();
1855 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1856 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1857
1858 FunctionProtoType::ExtProtoInfo ConversionEPI(
1860 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1861 ConversionEPI.TypeQuals = Qualifiers();
1862 ConversionEPI.TypeQuals.addConst();
1863 QualType ConvTy =
1864 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1865
1866 SourceLocation Loc = IntroducerRange.getBegin();
1867 DeclarationName Name
1869 S.Context.getCanonicalType(BlockPtrTy));
1871 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1873 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1877 CallOperator->getBody()->getEndLoc());
1878 Conversion->setAccess(AS_public);
1879 Conversion->setImplicit(true);
1880 Class->addDecl(Conversion);
1881}
1882
1884 SourceLocation ImplicitCaptureLoc,
1885 bool IsOpenMPMapping) {
1886 // VLA captures don't have a stored initialization expression.
1887 if (Cap.isVLATypeCapture())
1888 return ExprResult();
1889
1890 // An init-capture is initialized directly from its stored initializer.
1891 if (Cap.isInitCapture())
1892 return cast<VarDecl>(Cap.getVariable())->getInit();
1893
1894 // For anything else, build an initialization expression. For an implicit
1895 // capture, the capture notionally happens at the capture-default, so use
1896 // that location here.
1898 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1899
1900 // C++11 [expr.prim.lambda]p21:
1901 // When the lambda-expression is evaluated, the entities that
1902 // are captured by copy are used to direct-initialize each
1903 // corresponding non-static data member of the resulting closure
1904 // object. (For array members, the array elements are
1905 // direct-initialized in increasing subscript order.) These
1906 // initializations are performed in the (unspecified) order in
1907 // which the non-static data members are declared.
1908
1909 // C++ [expr.prim.lambda]p12:
1910 // An entity captured by a lambda-expression is odr-used (3.2) in
1911 // the scope containing the lambda-expression.
1913 IdentifierInfo *Name = nullptr;
1914 if (Cap.isThisCapture()) {
1915 QualType ThisTy = getCurrentThisType();
1916 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1917 if (Cap.isCopyCapture())
1918 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1919 else
1920 Init = This;
1921 } else {
1922 assert(Cap.isVariableCapture() && "unknown kind of capture");
1923 ValueDecl *Var = Cap.getVariable();
1924 Name = Var->getIdentifier();
1927 }
1928
1929 // In OpenMP, the capture kind doesn't actually describe how to capture:
1930 // variables are "mapped" onto the device in a process that does not formally
1931 // make a copy, even for a "copy capture".
1932 if (IsOpenMPMapping)
1933 return Init;
1934
1935 if (Init.isInvalid())
1936 return ExprError();
1937
1938 Expr *InitExpr = Init.get();
1940 Name, Cap.getCaptureType(), Loc);
1941 InitializationKind InitKind =
1943 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1944 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1945}
1946
1948 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1950 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1951}
1952
1955 switch (ICS) {
1957 return LCD_None;
1959 return LCD_ByCopy;
1962 return LCD_ByRef;
1964 llvm_unreachable("block capture in lambda");
1965 }
1966 llvm_unreachable("Unknown implicit capture style");
1967}
1968
1970 if (From.isInitCapture()) {
1971 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1972 if (Init && Init->HasSideEffects(Context))
1973 return true;
1974 }
1975
1976 if (!From.isCopyCapture())
1977 return false;
1978
1979 const QualType T = From.isThisCapture()
1981 : From.getCaptureType();
1982
1983 if (T.isVolatileQualified())
1984 return true;
1985
1986 const Type *BaseT = T->getBaseElementTypeUnsafe();
1987 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1988 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1989 !RD->hasTrivialDestructor();
1990
1991 return false;
1992}
1993
1995 const Capture &From) {
1996 if (CaptureHasSideEffects(From))
1997 return false;
1998
1999 if (From.isVLATypeCapture())
2000 return false;
2001
2002 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2003 // message
2004 if (From.isInitCapture() &&
2006 return false;
2007
2008 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2009 if (From.isThisCapture())
2010 diag << "'this'";
2011 else
2012 diag << From.getVariable();
2013 diag << From.isNonODRUsed();
2014 diag << FixItHint::CreateRemoval(CaptureRange);
2015 return true;
2016}
2017
2018/// Create a field within the lambda class or captured statement record for the
2019/// given capture.
2021 const sema::Capture &Capture) {
2023 QualType FieldType = Capture.getCaptureType();
2024
2025 TypeSourceInfo *TSI = nullptr;
2026 if (Capture.isVariableCapture()) {
2027 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2028 if (Var && Var->isInitCapture())
2029 TSI = Var->getTypeSourceInfo();
2030 }
2031
2032 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2033 // appropriate, at least for an implicit capture.
2034 if (!TSI)
2035 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2036
2037 // Build the non-static data member.
2038 FieldDecl *Field =
2039 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2040 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2041 /*Mutable=*/false, ICIS_NoInit);
2042 // If the variable being captured has an invalid type, mark the class as
2043 // invalid as well.
2044 if (!FieldType->isDependentType()) {
2045 if (RequireCompleteSizedType(Loc, FieldType,
2046 diag::err_field_incomplete_or_sizeless)) {
2047 RD->setInvalidDecl();
2048 Field->setInvalidDecl();
2049 } else {
2050 NamedDecl *Def;
2051 FieldType->isIncompleteType(&Def);
2052 if (Def && Def->isInvalidDecl()) {
2053 RD->setInvalidDecl();
2054 Field->setInvalidDecl();
2055 }
2056 }
2057 }
2058 Field->setImplicit(true);
2059 Field->setAccess(AS_private);
2060 RD->addDecl(Field);
2061
2063 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2064
2065 return Field;
2066}
2067
2069 LambdaScopeInfo *LSI) {
2070 // Collect information from the lambda scope.
2072 SmallVector<Expr *, 4> CaptureInits;
2073 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2074 LambdaCaptureDefault CaptureDefault =
2077 CXXMethodDecl *CallOperator;
2078 SourceRange IntroducerRange;
2079 bool ExplicitParams;
2080 bool ExplicitResultType;
2081 CleanupInfo LambdaCleanup;
2082 bool ContainsUnexpandedParameterPack;
2083 bool IsGenericLambda;
2084 {
2085 CallOperator = LSI->CallOperator;
2086 Class = LSI->Lambda;
2087 IntroducerRange = LSI->IntroducerRange;
2088 ExplicitParams = LSI->ExplicitParams;
2089 ExplicitResultType = !LSI->HasImplicitReturnType;
2090 LambdaCleanup = LSI->Cleanup;
2091 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2092 IsGenericLambda = Class->isGenericLambda();
2093
2094 CallOperator->setLexicalDeclContext(Class);
2095 Decl *TemplateOrNonTemplateCallOperatorDecl =
2096 CallOperator->getDescribedFunctionTemplate()
2097 ? CallOperator->getDescribedFunctionTemplate()
2098 : cast<Decl>(CallOperator);
2099
2100 // FIXME: Is this really the best choice? Keeping the lexical decl context
2101 // set as CurContext seems more faithful to the source.
2102 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2103
2105
2106 // True if the current capture has a used capture or default before it.
2107 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2108 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2109 CaptureDefaultLoc : IntroducerRange.getBegin();
2110
2111 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2112 const Capture &From = LSI->Captures[I];
2113
2114 if (From.isInvalid())
2115 return ExprError();
2116
2117 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2118 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2119 SourceLocation ImplicitCaptureLoc =
2120 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2121
2122 // Use source ranges of explicit captures for fixits where available.
2123 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2124
2125 // Warn about unused explicit captures.
2126 bool IsCaptureUsed = true;
2127 if (!CurContext->isDependentContext() && !IsImplicit &&
2128 !From.isODRUsed()) {
2129 // Initialized captures that are non-ODR used may not be eliminated.
2130 // FIXME: Where did the IsGenericLambda here come from?
2131 bool NonODRUsedInitCapture =
2132 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2133 if (!NonODRUsedInitCapture) {
2134 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2135 SourceRange FixItRange;
2136 if (CaptureRange.isValid()) {
2137 if (!CurHasPreviousCapture && !IsLast) {
2138 // If there are no captures preceding this capture, remove the
2139 // following comma.
2140 FixItRange = SourceRange(CaptureRange.getBegin(),
2141 getLocForEndOfToken(CaptureRange.getEnd()));
2142 } else {
2143 // Otherwise, remove the comma since the last used capture.
2144 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2145 CaptureRange.getEnd());
2146 }
2147 }
2148
2149 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2150 }
2151 }
2152
2153 if (CaptureRange.isValid()) {
2154 CurHasPreviousCapture |= IsCaptureUsed;
2155 PrevCaptureLoc = CaptureRange.getEnd();
2156 }
2157
2158 // Map the capture to our AST representation.
2159 LambdaCapture Capture = [&] {
2160 if (From.isThisCapture()) {
2161 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2162 // because it results in a reference capture. Don't warn prior to
2163 // C++2a; there's nothing that can be done about it before then.
2164 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2165 CaptureDefault == LCD_ByCopy) {
2166 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2167 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2169 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2170 }
2171 return LambdaCapture(From.getLocation(), IsImplicit,
2173 } else if (From.isVLATypeCapture()) {
2174 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2175 } else {
2176 assert(From.isVariableCapture() && "unknown kind of capture");
2177 ValueDecl *Var = From.getVariable();
2178 LambdaCaptureKind Kind =
2180 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2181 From.getEllipsisLoc());
2182 }
2183 }();
2184
2185 // Form the initializer for the capture field.
2186 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2187
2188 // FIXME: Skip this capture if the capture is not used, the initializer
2189 // has no side-effects, the type of the capture is trivial, and the
2190 // lambda is not externally visible.
2191
2192 // Add a FieldDecl for the capture and form its initializer.
2193 BuildCaptureField(Class, From);
2194 Captures.push_back(Capture);
2195 CaptureInits.push_back(Init.get());
2196
2197 if (LangOpts.CUDA)
2198 CUDA().CheckLambdaCapture(CallOperator, From);
2199 }
2200
2201 Class->setCaptures(Context, Captures);
2202
2203 // C++11 [expr.prim.lambda]p6:
2204 // The closure type for a lambda-expression with no lambda-capture
2205 // has a public non-virtual non-explicit const conversion function
2206 // to pointer to function having the same parameter and return
2207 // types as the closure type's function call operator.
2208 if (Captures.empty() && CaptureDefault == LCD_None)
2209 addFunctionPointerConversions(*this, IntroducerRange, Class,
2210 CallOperator);
2211
2212 // Objective-C++:
2213 // The closure type for a lambda-expression has a public non-virtual
2214 // non-explicit const conversion function to a block pointer having the
2215 // same parameter and return types as the closure type's function call
2216 // operator.
2217 // FIXME: Fix generic lambda to block conversions.
2218 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2219 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2220
2221 // Finalize the lambda class.
2222 SmallVector<Decl*, 4> Fields(Class->fields());
2223 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2225 CheckCompletedCXXClass(nullptr, Class);
2226 }
2227
2228 Cleanup.mergeFrom(LambdaCleanup);
2229
2230 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2231 CaptureDefault, CaptureDefaultLoc,
2232 ExplicitParams, ExplicitResultType,
2233 CaptureInits, EndLoc,
2234 ContainsUnexpandedParameterPack);
2235 // If the lambda expression's call operator is not explicitly marked constexpr
2236 // and we are not in a dependent context, analyze the call operator to infer
2237 // its constexpr-ness, suppressing diagnostics while doing so.
2238 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2239 !CallOperator->isConstexpr() &&
2240 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2241 !Class->getDeclContext()->isDependentContext()) {
2242 CallOperator->setConstexprKind(
2247 }
2248
2249 // Emit delayed shadowing warnings now that the full capture list is known.
2251
2253 switch (ExprEvalContexts.back().Context) {
2254 // C++11 [expr.prim.lambda]p2:
2255 // A lambda-expression shall not appear in an unevaluated operand
2256 // (Clause 5).
2260 // C++1y [expr.const]p2:
2261 // A conditional-expression e is a core constant expression unless the
2262 // evaluation of e, following the rules of the abstract machine, would
2263 // evaluate [...] a lambda-expression.
2264 //
2265 // This is technically incorrect, there are some constant evaluated contexts
2266 // where this should be allowed. We should probably fix this when DR1607 is
2267 // ratified, it lays out the exact set of conditions where we shouldn't
2268 // allow a lambda-expression.
2271 // We don't actually diagnose this case immediately, because we
2272 // could be within a context where we might find out later that
2273 // the expression is potentially evaluated (e.g., for typeid).
2274 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2275 break;
2276
2280 break;
2281 }
2282 }
2283
2284 return MaybeBindToTemporary(Lambda);
2285}
2286
2288 SourceLocation ConvLocation,
2289 CXXConversionDecl *Conv,
2290 Expr *Src) {
2291 // Make sure that the lambda call operator is marked used.
2292 CXXRecordDecl *Lambda = Conv->getParent();
2293 CXXMethodDecl *CallOperator
2294 = cast<CXXMethodDecl>(
2295 Lambda->lookup(
2297 CallOperator->setReferenced();
2298 CallOperator->markUsed(Context);
2299
2302 CurrentLocation, Src);
2303 if (!Init.isInvalid())
2304 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2305
2306 if (Init.isInvalid())
2307 return ExprError();
2308
2309 // Create the new block to be returned.
2311
2312 // Set the type information.
2313 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2314 Block->setIsVariadic(CallOperator->isVariadic());
2315 Block->setBlockMissingReturnType(false);
2316
2317 // Add parameters.
2319 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2320 ParmVarDecl *From = CallOperator->getParamDecl(I);
2321 BlockParams.push_back(ParmVarDecl::Create(
2322 Context, Block, From->getBeginLoc(), From->getLocation(),
2323 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2324 From->getStorageClass(),
2325 /*DefArg=*/nullptr));
2326 }
2327 Block->setParams(BlockParams);
2328
2329 Block->setIsConversionFromLambda(true);
2330
2331 // Add capture. The capture uses a fake variable, which doesn't correspond
2332 // to any actual memory location. However, the initializer copy-initializes
2333 // the lambda object.
2334 TypeSourceInfo *CapVarTSI =
2336 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2337 ConvLocation, nullptr,
2338 Src->getType(), CapVarTSI,
2339 SC_None);
2340 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2341 /*nested=*/false, /*copy=*/Init.get());
2342 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2343
2344 // Add a fake function body to the block. IR generation is responsible
2345 // for filling in the actual body, which cannot be expressed as an AST.
2346 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2347
2348 // Create the block literal expression.
2349 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2350 ExprCleanupObjects.push_back(Block);
2352
2353 return BuildBlock;
2354}
2355
2360 return FD;
2361 }
2362
2364 return FD->getInstantiatedFromDecl();
2365
2367 if (!FTD)
2368 return nullptr;
2369
2372
2373 return FTD->getTemplatedDecl();
2374}
2375
2379 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2380 : FunctionScopeRAII(SemaRef) {
2381 if (!isLambdaCallOperator(FD)) {
2383 return;
2384 }
2385
2386 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2387
2388 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2389 if (!FDPattern)
2390 return;
2391
2392 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2393
2394 if (!ShouldAddDeclsFromParentScope)
2395 return;
2396
2398 ParentInstantiations;
2399 while (true) {
2400 FDPattern =
2401 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));
2402 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));
2403
2404 if (!FDPattern || !FD)
2405 break;
2406
2407 ParentInstantiations.emplace_back(FDPattern, FD);
2408 }
2409
2410 // Add instantiated parameters and local vars to scopes, starting from the
2411 // outermost lambda to the innermost lambda. This ordering ensures that
2412 // parameters in inner lambdas can correctly depend on those defined
2413 // in outer lambdas, e.g. auto L = [](auto... x) {
2414 // return [](decltype(x)... y) { }; // `y` depends on `x`
2415 // };
2416
2417 for (const auto &[FDPattern, FD] : llvm::reverse(ParentInstantiations)) {
2418 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2419 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2420 }
2421}
#define V(N, I)
Definition: ASTContext.h:3323
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::Expr interface and subclasses for C++ expressions.
uint32_t Id
Definition: SemaARM.cpp:1143
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,...
Definition: SemaLambda.cpp:570
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...
Definition: SemaLambda.cpp:642
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:916
static std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:68
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:884
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Definition: SemaLambda.cpp:663
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:234
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)
Definition: SemaLambda.cpp:508
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:890
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:364
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:268
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.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
This file declares semantic analysis for OpenMP constructs and clauses.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1091
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:660
QualType getRecordType(const RecordDecl *Decl) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2616
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2632
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1137
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1625
IdentifierTable & Idents
Definition: ASTContext.h:656
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
Definition: ASTContext.h:1197
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1109
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1603
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:769
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1215
PtrTy get() const
Definition: Ownership.h:170
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3845
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
A class which contains all the information about a particular captured value.
Definition: Decl.h:4512
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4506
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5404
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6336
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2889
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2461
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2273
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition: DeclCXX.h:1866
void setLambdaIsGeneric(bool IsGeneric)
Definition: DeclCXX.h:1877
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
bool isCapturelessLambda() const
Definition: DeclCXX.h:1068
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1607
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4184
reference front() const
Definition: DeclBase.h:1381
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2055
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2184
bool isFileContext() const
Definition: DeclBase.h:2126
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2071
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1829
bool isTranslationUnit() const
Definition: DeclBase.h:2131
bool isRecord() const
Definition: DeclBase.h:2135
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1743
bool isFunctionOrMethod() const
Definition: DeclBase.h:2107
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:1265
Captures information about "declaration specifiers".
Definition: DeclSpec.h:255
SCS getStorageClassSpec() const
Definition: DeclSpec.h:506
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1014
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:837
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setReferenced(bool R=true)
Definition: DeclBase.h:629
void setLocation(SourceLocation L)
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
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.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:814
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2001
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1908
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2464
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2406
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2055
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2641
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2402
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:425
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2090
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2495
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6335
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3309
Represents an enum.
Definition: Decl.h:3879
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5963
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3472
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
bool isFPConstrained() const
Definition: LangOptions.h:847
Represents a member of a struct/union/class.
Definition: Decl.h:3069
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:4533
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
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:1062
const Expr * getSubExpr() const
Definition: Expr.h:1057
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2708
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2440
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4035
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
QualType getReturnType() const
Definition: Decl.h:2756
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2685
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4150
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
@ TK_MemberSpecialization
Definition: Decl.h:1983
@ TK_DependentNonTemplate
Definition: Decl.h:1992
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3981
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2434
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4054
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2437
bool isConsteval() const
Definition: Decl.h:2446
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2804
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2716
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4971
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5344
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5231
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5227
Declaration of a template function.
Definition: DeclTemplate.h:957
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:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4501
CallingConv getCallConv() const
Definition: Type.h:4608
QualType getReturnType() const
Definition: Type.h:4597
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:3660
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
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)
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7473
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.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
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:1291
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
Represents the results of name lookup.
Definition: Lookup.h:46
DeclClass * getAsSingle() const
Definition: Lookup.h:562
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
bool isAmbiguous() const
Definition: Lookup.h:324
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:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
PtrTy get() const
Definition: Ownership.h:80
Represents a pack expansion of types.
Definition: Type.h:6954
Expr ** getExprs()
Definition: Expr.h:5827
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5816
Represents a parameter to a function.
Definition: Decl.h:1761
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:2903
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
A (possibly-)qualified type.
Definition: Type.h:942
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1304
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1009
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7870
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7945
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7838
The collection of all-type qualifiers we support.
Definition: Type.h:320
void addAddressSpace(LangAS space)
Definition: Type.h:585
void addConst()
Definition: Type.h:448
Represents a struct/union/class.
Definition: Decl.h:4180
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3020
void setRetValue(Expr *E)
Definition: Stmt.h:3053
SourceLocation getBeginLoc() const
Definition: Stmt.h:3077
Expr * getRetValue()
Definition: Stmt.h:3051
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
Scope * getTemplateParamParent()
Definition: Scope.h:315
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:952
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:997
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3001
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:535
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10877
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:802
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2426
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15227
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7846
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8988
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12758
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...
Definition: SemaLambda.cpp:849
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:1218
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Definition: SemaLambda.cpp:248
SemaCUDA & CUDA()
Definition: Sema.h:1163
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17120
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:939
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2274
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)
Definition: SemaLambda.cpp:997
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...
Definition: SemaAttr.cpp:1161
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
Definition: SemaLambda.cpp:875
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15325
ASTContext & Context
Definition: Sema.h:1001
SemaObjC & ObjC()
Definition: Sema.h:1203
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
ASTContext & getASTContext() const
Definition: Sema.h:599
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.
Definition: SemaExpr.cpp:18635
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17541
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:2412
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
Definition: SemaLambda.cpp:455
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1564
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition: Sema.h:594
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13875
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13848
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.
Definition: SemaLambda.cpp:522
const LangOptions & getLangOpts() const
Definition: Sema.h:592
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
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 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:999
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2387
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
Definition: SemaLambda.cpp:783
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6460
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8275
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.
Definition: SemaType.cpp:1836
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3155
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1136
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13442
TryCaptureKind
Definition: Sema.h:6586
@ TryCapture_Implicit
Definition: Sema.h:6587
@ TryCapture_ExplicitByVal
Definition: Sema.h:6588
@ TryCapture_ExplicitByRef
Definition: Sema.h:6589
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...
Definition: SemaLambda.cpp:544
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15681
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:215
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.
Definition: SemaDecl.cpp:8159
@ Normal
A normal translation unit fragment.
Definition: Sema.h:689
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6464
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5590
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8831
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18784
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()
Definition: SemaExpr.cpp:17619
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7919
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
Definition: SemaLambda.cpp:972
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:690
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9607
void PopDeclContext()
Definition: SemaDecl.cpp:1313
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)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:281
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
Definition: SemaLambda.cpp:540
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:392
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void NoteTemplateParameterLocation(const NamedDecl &Decl)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8266
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4388
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3820
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1694
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
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: Type.h:7715
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7726
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1826
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1881
bool isVoidType() const
Definition: Type.h:8296
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2070
CanQualType getCanonicalTypeUnqualified() const
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8584
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2669
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2333
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8467
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8430
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2361
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8517
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4655
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3323
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5359
Represents a variable declaration or definition.
Definition: Decl.h:918
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1432
void setInitCapture(bool IC)
Definition: Decl.h:1561
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
InitializationStyle
Initialization styles.
Definition: Decl.h:921
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:929
@ CInit
C-style initialization with assignment.
Definition: Decl.h:923
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:926
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
void setInit(Expr *I)
Definition: Decl.cpp:2442
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
bool isNonODRUsed() const
Definition: ScopeInfo.h:667
bool isODRUsed() const
Definition: ScopeInfo.h:666
bool isInitCapture() const
Determine whether this capture is an init-capture.
Definition: ScopeInfo.cpp:223
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isVLATypeCapture() const
Definition: ScopeInfo.h:657
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition: ScopeInfo.h:690
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
const VariableArrayType * getCapturedVLAType() const
Definition: ScopeInfo.h:680
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition: ScopeInfo.h:758
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
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:950
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition: ScopeInfo.h:958
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
Definition: ScopeInfo.h:899
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this lambda, if any.
Definition: ScopeInfo.h:902
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition: ScopeInfo.h:896
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition: ScopeInfo.h:893
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition: ScopeInfo.h:910
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition: ScopeInfo.h:905
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition: ScopeInfo.h:882
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition: ScopeInfo.h:939
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:179
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1775
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
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:25
@ CopyInit
[a = b], [a = {b}]
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition: Specifiers.h:354
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
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:132
StringRef getLambdaStaticInvokerName()
Definition: ASTLambda.h:22
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ EST_BasicNoexcept
noexcept
@ AS_public
Definition: Specifiers.h:121
@ AS_private
Definition: Specifiers.h:123
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
Information about how a lambda is numbered within its context.
Definition: DeclCXX.h:1798
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:1600
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1591
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1594
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1563
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1338
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5030
Extra information about a function prototype.
Definition: Type.h:5056
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5063
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5057
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2891
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2904
Represents a complete lambda introducer.
Definition: DeclSpec.h:2840
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2865
SourceLocation DefaultLoc
Definition: DeclSpec.h:2863
LambdaCaptureDefault Default
Definition: DeclSpec.h:2864
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:1021