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 //===----------------------------------------------------------------------===//
12 #include "clang/Sema/SemaLambda.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "clang/Sema/SemaCUDA.h"
25 #include "clang/Sema/SemaOpenMP.h"
26 #include "clang/Sema/Template.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include <optional>
29 using namespace clang;
30 using 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 
67 static 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 {
92  const clang::sema::LambdaScopeInfo *LSI =
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.
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 
178 std::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 
233 static inline TemplateParameterList *
235  if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
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) {
251  DeclContext *DC = CurContext;
252  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
253  DC = DC->getParent();
254 
255  bool IsGenericLambda =
256  Info && getGenericLambdaTemplateParameterList(getCurLambda(), *this);
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.
268 static 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 
280 std::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,
288  DefaultArgument,
289  DataMember,
290  InlineVariable,
291  TemplatedVariable,
292  Concept
293  } Kind = Normal;
294 
295  bool IsInNonspecializedTemplate =
296  inTemplateInstantiation() || CurContext->isDependentContext();
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))) ||
333  isInInlineFunction(CurContext)) {
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 
363 static 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>();
375  QualType Result = FPT->getReturnType();
376  if (Result->isUndeducedType()) {
377  Result = S.SubstAutoTypeDependent(Result);
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()
406  .getDesugaredType(getASTContext());
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 
429  CXXCastPath &Path = Context.LambdaCastPaths[Method];
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 
456  CXXRecordDecl *Class, CXXMethodDecl *Method,
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)
470  return &Context.getManglingNumberContext(
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();
476  return &Context.getManglingNumberContext(DC);
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)
532  else if (CaptureDefault == LCD_ByRef)
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) {
548  LambdaScopeInfo *LSI = getCurLambda();
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)) {
577  if (EnumConstantDecl *D
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) {
741  CSI.ReturnType = Context.getTypeDeclType(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.
814  QualType DeducedType = deduceVarTypeFromInitializer(
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 =
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 
875 void 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 
889 static 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)
900  EPI.TypeQuals.addAddressSpace(AS);
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
910  : S.Context.DependentTy;
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 =
942  ParamInfo.isExplicitObjectMemberFunction();
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 
973  CXXRecordDecl *Class) {
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 =
982  Context.DeclarationNames.getCXXOperatorName(OO_Call);
983  DeclarationNameLoc MethodNameLoc =
986  Context, Class, SourceLocation(),
987  DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
988  MethodNameLoc),
989  QualType(), /*Tinfo=*/nullptr, SC_None,
990  getCurFPFeatures().isFPConstrained(),
991  /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
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 =
1027  Method->getDescribedFunctionTemplate();
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 
1062  LambdaScopeInfo *LSI = getCurLambda();
1063  assert(LSI && "LambdaScopeInfo should be on stack!");
1064 
1065  if (Intro.Default == LCD_ByCopy)
1067  else if (Intro.Default == LCD_ByRef)
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 (LSI->NumExplicitTemplateParams > 0) {
1080  Scope *TemplateParamScope = CurScope->getTemplateParamParent();
1081  assert(TemplateParamScope &&
1082  "Lambda with explicit template param list should establish a "
1083  "template param scope");
1084  assert(TemplateParamScope->getParent());
1085  if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
1086  LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1087  } else if (CurScope->getTemplateParamParent() != nullptr) {
1088  LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1089  }
1090 
1091  CXXRecordDecl *Class = createLambdaClosureType(
1092  Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1093  LSI->Lambda = Class;
1094 
1095  CXXMethodDecl *Method = CreateLambdaCallOperator(Intro.Range, Class);
1096  LSI->CallOperator = Method;
1097  Method->setLexicalDeclContext(CurContext);
1098 
1099  PushDeclContext(CurScope, Method);
1100 
1101  bool ContainsUnexpandedParameterPack = false;
1102 
1103  // Distinct capture names, for diagnostics.
1104  llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1105 
1106  // Handle explicit captures.
1107  SourceLocation PrevCaptureLoc =
1108  Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1109  for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1110  PrevCaptureLoc = C->Loc, ++C) {
1111  if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1112  if (C->Kind == LCK_StarThis)
1113  Diag(C->Loc, !getLangOpts().CPlusPlus17
1114  ? diag::ext_star_this_lambda_capture_cxx17
1115  : diag::warn_cxx14_compat_star_this_lambda_capture);
1116 
1117  // C++11 [expr.prim.lambda]p8:
1118  // An identifier or this shall not appear more than once in a
1119  // lambda-capture.
1120  if (LSI->isCXXThisCaptured()) {
1121  Diag(C->Loc, diag::err_capture_more_than_once)
1122  << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1124  SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1125  continue;
1126  }
1127 
1128  // C++20 [expr.prim.lambda]p8:
1129  // If a lambda-capture includes a capture-default that is =,
1130  // each simple-capture of that lambda-capture shall be of the form
1131  // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1132  // redundant but accepted for compatibility with ISO C++14. --end note ]
1133  if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1134  Diag(C->Loc, !getLangOpts().CPlusPlus20
1135  ? diag::ext_equals_this_lambda_capture_cxx20
1136  : diag::warn_cxx17_compat_equals_this_lambda_capture);
1137 
1138  // C++11 [expr.prim.lambda]p12:
1139  // If this is captured by a local lambda expression, its nearest
1140  // enclosing function shall be a non-static member function.
1141  QualType ThisCaptureType = getCurrentThisType();
1142  if (ThisCaptureType.isNull()) {
1143  Diag(C->Loc, diag::err_this_capture) << true;
1144  continue;
1145  }
1146 
1147  CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1148  /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1149  C->Kind == LCK_StarThis);
1150  if (!LSI->Captures.empty())
1151  LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1152  continue;
1153  }
1154 
1155  assert(C->Id && "missing identifier for capture");
1156 
1157  if (C->Init.isInvalid())
1158  continue;
1159 
1160  ValueDecl *Var = nullptr;
1161  if (C->Init.isUsable()) {
1162  Diag(C->Loc, getLangOpts().CPlusPlus14
1163  ? diag::warn_cxx11_compat_init_capture
1164  : diag::ext_init_capture);
1165 
1166  // If the initializer expression is usable, but the InitCaptureType
1167  // is not, then an error has occurred - so ignore the capture for now.
1168  // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1169  // FIXME: we should create the init capture variable and mark it invalid
1170  // in this case.
1171  if (C->InitCaptureType.get().isNull())
1172  continue;
1173 
1174  if (C->Init.get()->containsUnexpandedParameterPack() &&
1175  !C->InitCaptureType.get()->getAs<PackExpansionType>())
1176  DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1177 
1178  unsigned InitStyle;
1179  switch (C->InitKind) {
1181  llvm_unreachable("not an init-capture?");
1183  InitStyle = VarDecl::CInit;
1184  break;
1186  InitStyle = VarDecl::CallInit;
1187  break;
1189  InitStyle = VarDecl::ListInit;
1190  break;
1191  }
1192  Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1193  C->EllipsisLoc, C->Id, InitStyle,
1194  C->Init.get(), Method);
1195  assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1196  if (auto *V = dyn_cast<VarDecl>(Var))
1197  CheckShadow(CurrentScope, V);
1198  PushOnScopeChains(Var, CurrentScope, false);
1199  } else {
1200  assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1201  "init capture has valid but null init?");
1202 
1203  // C++11 [expr.prim.lambda]p8:
1204  // If a lambda-capture includes a capture-default that is &, the
1205  // identifiers in the lambda-capture shall not be preceded by &.
1206  // If a lambda-capture includes a capture-default that is =, [...]
1207  // each identifier it contains shall be preceded by &.
1208  if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1209  Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1211  SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1212  continue;
1213  } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1214  Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1216  SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1217  continue;
1218  }
1219 
1220  // C++11 [expr.prim.lambda]p10:
1221  // The identifiers in a capture-list are looked up using the usual
1222  // rules for unqualified name lookup (3.4.1)
1223  DeclarationNameInfo Name(C->Id, C->Loc);
1224  LookupResult R(*this, Name, LookupOrdinaryName);
1225  LookupName(R, CurScope);
1226  if (R.isAmbiguous())
1227  continue;
1228  if (R.empty()) {
1229  // FIXME: Disable corrections that would add qualification?
1230  CXXScopeSpec ScopeSpec;
1231  DeclFilterCCC<VarDecl> Validator{};
1232  if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1233  continue;
1234  }
1235 
1236  if (auto *BD = R.getAsSingle<BindingDecl>())
1237  Var = BD;
1238  else
1239  Var = R.getAsSingle<VarDecl>();
1240  if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1241  continue;
1242  }
1243 
1244  // C++11 [expr.prim.lambda]p10:
1245  // [...] each such lookup shall find a variable with automatic storage
1246  // duration declared in the reaching scope of the local lambda expression.
1247  // Note that the 'reaching scope' check happens in tryCaptureVariable().
1248  if (!Var) {
1249  Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1250  continue;
1251  }
1252 
1253  // C++11 [expr.prim.lambda]p8:
1254  // An identifier or this shall not appear more than once in a
1255  // lambda-capture.
1256  if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1257  !Inserted) {
1258  if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1259  !Var->isInitCapture()) {
1260  Diag(C->Loc, diag::err_capture_more_than_once)
1261  << C->Id << It->second->getBeginLoc()
1263  SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1264  Var->setInvalidDecl();
1265  } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1266  DiagPlaceholderVariableDefinition(C->Loc);
1267  } else {
1268  // Previous capture captured something different (one or both was
1269  // an init-capture): no fixit.
1270  Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1271  continue;
1272  }
1273  }
1274 
1275  // Ignore invalid decls; they'll just confuse the code later.
1276  if (Var->isInvalidDecl())
1277  continue;
1278 
1279  VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1280 
1281  if (!Underlying->hasLocalStorage()) {
1282  Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1283  Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1284  continue;
1285  }
1286 
1287  // C++11 [expr.prim.lambda]p23:
1288  // A capture followed by an ellipsis is a pack expansion (14.5.3).
1289  SourceLocation EllipsisLoc;
1290  if (C->EllipsisLoc.isValid()) {
1291  if (Var->isParameterPack()) {
1292  EllipsisLoc = C->EllipsisLoc;
1293  } else {
1294  Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1295  << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1296  : SourceRange(C->Loc));
1297 
1298  // Just ignore the ellipsis.
1299  }
1300  } else if (Var->isParameterPack()) {
1301  ContainsUnexpandedParameterPack = true;
1302  }
1303 
1304  if (C->Init.isUsable()) {
1305  addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1306  PushOnScopeChains(Var, CurScope, false);
1307  } else {
1308  TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef
1309  : TryCapture_ExplicitByVal;
1310  tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1311  }
1312  if (!LSI->Captures.empty())
1313  LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1314  }
1315  finishLambdaExplicitCaptures(LSI);
1316  LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1317  PopDeclContext();
1318 }
1319 
1321  SourceLocation MutableLoc) {
1322 
1324  LSI->Mutable = MutableLoc.isValid();
1325  ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1326 
1327  // C++11 [expr.prim.lambda]p9:
1328  // A lambda-expression whose smallest enclosing scope is a block scope is a
1329  // local lambda expression; any other lambda expression shall not have a
1330  // capture-default or simple-capture in its lambda-introducer.
1331  //
1332  // For simple-captures, this is covered by the check below that any named
1333  // entity is a variable that can be captured.
1334  //
1335  // For DR1632, we also allow a capture-default in any context where we can
1336  // odr-use 'this' (in particular, in a default initializer for a non-static
1337  // data member).
1338  if (Intro.Default != LCD_None &&
1339  !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1340  (getCurrentThisType().isNull() ||
1341  CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1342  /*BuildAndDiagnose=*/false)))
1343  Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1344 }
1345 
1347  Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {
1349  PushDeclContext(LambdaScope, LSI->CallOperator);
1350 
1351  for (const DeclaratorChunk::ParamInfo &P : Params) {
1352  auto *Param = cast<ParmVarDecl>(P.Param);
1353  Param->setOwningFunction(LSI->CallOperator);
1354  if (Param->getIdentifier())
1355  PushOnScopeChains(Param, LambdaScope, false);
1356  }
1357 
1358  // After the parameter list, we may parse a noexcept/requires/trailing return
1359  // type which need to know whether the call operator constiture a dependent
1360  // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1361  // now.
1362  TemplateParameterList *TemplateParams =
1364  if (TemplateParams) {
1365  AddTemplateParametersToLambdaCallOperator(LSI->CallOperator, LSI->Lambda,
1366  TemplateParams);
1367  LSI->Lambda->setLambdaIsGeneric(true);
1368  }
1369  LSI->AfterParameterList = true;
1370 }
1371 
1373  Declarator &ParamInfo,
1374  const DeclSpec &DS) {
1375 
1378 
1380  bool ExplicitResultType;
1381 
1382  SourceLocation TypeLoc, CallOperatorLoc;
1383  if (ParamInfo.getNumTypeObjects() == 0) {
1384  CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1385  } else {
1386  unsigned Index;
1387  ParamInfo.isFunctionDeclarator(Index);
1388  const auto &Object = ParamInfo.getTypeObject(Index);
1389  TypeLoc =
1390  Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1391  CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1392  }
1393 
1394  CXXRecordDecl *Class = LSI->Lambda;
1395  CXXMethodDecl *Method = LSI->CallOperator;
1396 
1397  TypeSourceInfo *MethodTyInfo = getLambdaType(
1398  *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1399 
1400  LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1401 
1402  if (ParamInfo.isFunctionDeclarator() != 0 &&
1404  const auto &FTI = ParamInfo.getFunctionTypeInfo();
1405  Params.reserve(Params.size());
1406  for (unsigned I = 0; I < FTI.NumParams; ++I) {
1407  auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1408  Param->setScopeInfo(0, Params.size());
1409  Params.push_back(Param);
1410  }
1411  }
1412 
1413  bool IsLambdaStatic =
1415 
1416  CompleteLambdaCallOperator(
1417  Method, Intro.Range.getBegin(), CallOperatorLoc,
1418  ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1419  ParamInfo.getDeclSpec().getConstexprSpecifier(),
1420  IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1421 
1422  CheckCXXDefaultArguments(Method);
1423 
1424  // This represents the function body for the lambda function, check if we
1425  // have to apply optnone due to a pragma.
1426  AddRangeBasedOptnone(Method);
1427 
1428  // code_seg attribute on lambda apply to the method.
1429  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(
1430  Method, /*IsDefinition=*/true))
1431  Method->addAttr(A);
1432 
1433  // Attributes on the lambda apply to the method.
1434  ProcessDeclAttributes(CurScope, Method, ParamInfo);
1435 
1436  // CUDA lambdas get implicit host and device attributes.
1437  if (getLangOpts().CUDA)
1438  CUDA().SetLambdaAttrs(Method);
1439 
1440  // OpenMP lambdas might get assumumption attributes.
1441  if (LangOpts.OpenMP)
1442  OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1443 
1444  handleLambdaNumbering(Class, Method);
1445 
1446  for (auto &&C : LSI->Captures) {
1447  if (!C.isVariableCapture())
1448  continue;
1449  ValueDecl *Var = C.getVariable();
1450  if (Var && Var->isInitCapture()) {
1451  PushOnScopeChains(Var, CurScope, false);
1452  }
1453  }
1454 
1455  auto CheckRedefinition = [&](ParmVarDecl *Param) {
1456  for (const auto &Capture : Intro.Captures) {
1457  if (Capture.Id == Param->getIdentifier()) {
1458  Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1459  Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1460  << Capture.Id << true;
1461  return false;
1462  }
1463  }
1464  return true;
1465  };
1466 
1467  for (ParmVarDecl *P : Params) {
1468  if (!P->getIdentifier())
1469  continue;
1470  if (CheckRedefinition(P))
1471  CheckShadow(CurScope, P);
1472  PushOnScopeChains(P, CurScope);
1473  }
1474 
1475  // C++23 [expr.prim.lambda.capture]p5:
1476  // If an identifier in a capture appears as the declarator-id of a parameter
1477  // of the lambda-declarator's parameter-declaration-clause or as the name of a
1478  // template parameter of the lambda-expression's template-parameter-list, the
1479  // program is ill-formed.
1480  TemplateParameterList *TemplateParams =
1482  if (TemplateParams) {
1483  for (const auto *TP : TemplateParams->asArray()) {
1484  if (!TP->getIdentifier())
1485  continue;
1486  for (const auto &Capture : Intro.Captures) {
1487  if (Capture.Id == TP->getIdentifier()) {
1488  Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1489  NoteTemplateParameterLocation(*TP);
1490  }
1491  }
1492  }
1493  }
1494 
1495  // C++20: dcl.decl.general p4:
1496  // The optional requires-clause ([temp.pre]) in an init-declarator or
1497  // member-declarator shall be present only if the declarator declares a
1498  // templated function ([dcl.fct]).
1499  if (Expr *TRC = Method->getTrailingRequiresClause()) {
1500  // [temp.pre]/8:
1501  // An entity is templated if it is
1502  // - a template,
1503  // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1504  // templated entity,
1505  // - a member of a templated entity,
1506  // - an enumerator for an enumeration that is a templated entity, or
1507  // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1508  // appearing in the declaration of a templated entity. [Note 6: A local
1509  // class, a local or block variable, or a friend function defined in a
1510  // templated entity is a templated entity. — end note]
1511  //
1512  // A templated function is a function template or a function that is
1513  // templated. A templated class is a class template or a class that is
1514  // templated. A templated variable is a variable template or a variable
1515  // that is templated.
1516 
1517  // Note: we only have to check if this is defined in a template entity, OR
1518  // if we are a template, since the rest don't apply. The requires clause
1519  // applies to the call operator, which we already know is a member function,
1520  // AND defined.
1521  if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1522  Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1523  }
1524  }
1525 
1526  // Enter a new evaluation context to insulate the lambda from any
1527  // cleanups from the enclosing full-expression.
1528  PushExpressionEvaluationContext(
1529  LSI->CallOperator->isConsteval()
1530  ? ExpressionEvaluationContext::ImmediateFunctionContext
1531  : ExpressionEvaluationContext::PotentiallyEvaluated);
1532  ExprEvalContexts.back().InImmediateFunctionContext =
1533  LSI->CallOperator->isConsteval();
1534  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1535  getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1536 }
1537 
1539  bool IsInstantiation) {
1540  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1541 
1542  // Leave the expression-evaluation context.
1543  DiscardCleanupsInEvaluationContext();
1544  PopExpressionEvaluationContext();
1545 
1546  // Leave the context of the lambda.
1547  if (!IsInstantiation)
1548  PopDeclContext();
1549 
1550  // Finalize the lambda.
1551  CXXRecordDecl *Class = LSI->Lambda;
1552  Class->setInvalidDecl();
1553  SmallVector<Decl*, 4> Fields(Class->fields());
1554  ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1556  CheckCompletedCXXClass(nullptr, Class);
1557 
1558  PopFunctionScopeInfo();
1559 }
1560 
1561 template <typename Func>
1563  Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1565  CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1567  CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1568  CallingConv CallOpCC = CallOpProto.getCallConv();
1569 
1570  /// Implement emitting a version of the operator for many of the calling
1571  /// conventions for MSVC, as described here:
1572  /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1573  /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1574  /// vectorcall are generated by MSVC when it is supported by the target.
1575  /// Additionally, we are ensuring that the default-free/default-member and
1576  /// call-operator calling convention are generated as well.
1577  /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1578  /// 'member default', despite MSVC not doing so. We do this in order to ensure
1579  /// that someone who intentionally places 'thiscall' on the lambda call
1580  /// operator will still get that overload, since we don't have the a way of
1581  /// detecting the attribute by the time we get here.
1582  if (S.getLangOpts().MSVCCompat) {
1583  CallingConv Convs[] = {
1585  DefaultFree, DefaultMember, CallOpCC};
1586  llvm::sort(Convs);
1587  llvm::iterator_range<CallingConv *> Range(
1588  std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1589  const TargetInfo &TI = S.getASTContext().getTargetInfo();
1590 
1591  for (CallingConv C : Range) {
1593  F(C);
1594  }
1595  return;
1596  }
1597 
1598  if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1599  F(DefaultFree);
1600  F(DefaultMember);
1601  } else {
1602  F(CallOpCC);
1603  }
1604 }
1605 
1606 // Returns the 'standard' calling convention to be used for the lambda
1607 // conversion function, that is, the 'free' function calling convention unless
1608 // it is overridden by a non-default calling convention attribute.
1609 static CallingConv
1611  const FunctionProtoType *CallOpProto) {
1613  CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1615  CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1616  CallingConv CallOpCC = CallOpProto->getCallConv();
1617 
1618  // If the call-operator hasn't been changed, return both the 'free' and
1619  // 'member' function calling convention.
1620  if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1621  return DefaultFree;
1622  return CallOpCC;
1623 }
1624 
1626  const FunctionProtoType *CallOpProto, CallingConv CC) {
1627  const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1628  CallOpProto->getExtProtoInfo();
1629  FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1630  InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1631  InvokerExtInfo.TypeQuals = Qualifiers();
1632  assert(InvokerExtInfo.RefQualifier == RQ_None &&
1633  "Lambda's call operator should not have a reference qualifier");
1634  return Context.getFunctionType(CallOpProto->getReturnType(),
1635  CallOpProto->getParamTypes(), InvokerExtInfo);
1636 }
1637 
1638 /// Add a lambda's conversion to function pointer, as described in
1639 /// C++11 [expr.prim.lambda]p6.
1640 static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1641  CXXRecordDecl *Class,
1642  CXXMethodDecl *CallOperator,
1643  QualType InvokerFunctionTy) {
1644  // This conversion is explicitly disabled if the lambda's function has
1645  // pass_object_size attributes on any of its parameters.
1646  auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1647  return P->hasAttr<PassObjectSizeAttr>();
1648  };
1649  if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1650  return;
1651 
1652  // Add the conversion to function pointer.
1653  QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1654 
1655  // Create the type of the conversion function.
1656  FunctionProtoType::ExtProtoInfo ConvExtInfo(
1658  /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1659  // The conversion function is always const and noexcept.
1660  ConvExtInfo.TypeQuals = Qualifiers();
1661  ConvExtInfo.TypeQuals.addConst();
1662  ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1663  QualType ConvTy =
1664  S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1665 
1666  SourceLocation Loc = IntroducerRange.getBegin();
1667  DeclarationName ConversionName
1669  S.Context.getCanonicalType(PtrToFunctionTy));
1670  // Construct a TypeSourceInfo for the conversion function, and wire
1671  // all the parameters appropriately for the FunctionProtoTypeLoc
1672  // so that everything works during transformation/instantiation of
1673  // generic lambdas.
1674  // The main reason for wiring up the parameters of the conversion
1675  // function with that of the call operator is so that constructs
1676  // like the following work:
1677  // auto L = [](auto b) { <-- 1
1678  // return [](auto a) -> decltype(a) { <-- 2
1679  // return a;
1680  // };
1681  // };
1682  // int (*fp)(int) = L(5);
1683  // Because the trailing return type can contain DeclRefExprs that refer
1684  // to the original call operator's variables, we hijack the call
1685  // operators ParmVarDecls below.
1686  TypeSourceInfo *ConvNamePtrToFunctionTSI =
1687  S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1688  DeclarationNameLoc ConvNameLoc =
1689  DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1690 
1691  // The conversion function is a conversion to a pointer-to-function.
1692  TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1693  FunctionProtoTypeLoc ConvTL =
1694  ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1695  // Get the result of the conversion function which is a pointer-to-function.
1696  PointerTypeLoc PtrToFunctionTL =
1697  ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1698  // Do the same for the TypeSourceInfo that is used to name the conversion
1699  // operator.
1700  PointerTypeLoc ConvNamePtrToFunctionTL =
1701  ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1702 
1703  // Get the underlying function types that the conversion function will
1704  // be converting to (should match the type of the call operator).
1705  FunctionProtoTypeLoc CallOpConvTL =
1706  PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1707  FunctionProtoTypeLoc CallOpConvNameTL =
1708  ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1709 
1710  // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1711  // These parameter's are essentially used to transform the name and
1712  // the type of the conversion operator. By using the same parameters
1713  // as the call operator's we don't have to fix any back references that
1714  // the trailing return type of the call operator's uses (such as
1715  // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1716  // - we can simply use the return type of the call operator, and
1717  // everything should work.
1718  SmallVector<ParmVarDecl *, 4> InvokerParams;
1719  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1720  ParmVarDecl *From = CallOperator->getParamDecl(I);
1721 
1722  InvokerParams.push_back(ParmVarDecl::Create(
1723  S.Context,
1724  // Temporarily add to the TU. This is set to the invoker below.
1726  From->getLocation(), From->getIdentifier(), From->getType(),
1727  From->getTypeSourceInfo(), From->getStorageClass(),
1728  /*DefArg=*/nullptr));
1729  CallOpConvTL.setParam(I, From);
1730  CallOpConvNameTL.setParam(I, From);
1731  }
1732 
1734  S.Context, Class, Loc,
1735  DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1737  /*isInline=*/true, ExplicitSpecifier(),
1738  S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1740  CallOperator->getBody()->getEndLoc());
1741  Conversion->setAccess(AS_public);
1742  Conversion->setImplicit(true);
1743 
1744  // A non-generic lambda may still be a templated entity. We need to preserve
1745  // constraints when converting the lambda to a function pointer. See GH63181.
1746  if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1747  Conversion->setTrailingRequiresClause(Requires);
1748 
1749  if (Class->isGenericLambda()) {
1750  // Create a template version of the conversion operator, using the template
1751  // parameter list of the function call operator.
1752  FunctionTemplateDecl *TemplateCallOperator =
1753  CallOperator->getDescribedFunctionTemplate();
1754  FunctionTemplateDecl *ConversionTemplate =
1756  Loc, ConversionName,
1757  TemplateCallOperator->getTemplateParameters(),
1758  Conversion);
1759  ConversionTemplate->setAccess(AS_public);
1760  ConversionTemplate->setImplicit(true);
1761  Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1762  Class->addDecl(ConversionTemplate);
1763  } else
1764  Class->addDecl(Conversion);
1765 
1766  // If the lambda is not static, we need to add a static member
1767  // function that will be the result of the conversion with a
1768  // certain unique ID.
1769  // When it is static we just return the static call operator instead.
1770  if (CallOperator->isImplicitObjectMemberFunction()) {
1771  DeclarationName InvokerName =
1773  // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1774  // we should get a prebuilt TrivialTypeSourceInfo from Context
1775  // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1776  // then rewire the parameters accordingly, by hoisting up the InvokeParams
1777  // loop below and then use its Params to set Invoke->setParams(...) below.
1778  // This would avoid the 'const' qualifier of the calloperator from
1779  // contaminating the type of the invoker, which is currently adjusted
1780  // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1781  // trailing return type of the invoker would require a visitor to rebuild
1782  // the trailing return type and adjusting all back DeclRefExpr's to refer
1783  // to the new static invoker parameters - not the call operator's.
1785  S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1786  InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1788  /*isInline=*/true, CallOperator->getConstexprKind(),
1789  CallOperator->getBody()->getEndLoc());
1790  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1791  InvokerParams[I]->setOwningFunction(Invoke);
1792  Invoke->setParams(InvokerParams);
1793  Invoke->setAccess(AS_private);
1794  Invoke->setImplicit(true);
1795  if (Class->isGenericLambda()) {
1796  FunctionTemplateDecl *TemplateCallOperator =
1797  CallOperator->getDescribedFunctionTemplate();
1798  FunctionTemplateDecl *StaticInvokerTemplate =
1800  S.Context, Class, Loc, InvokerName,
1801  TemplateCallOperator->getTemplateParameters(), Invoke);
1802  StaticInvokerTemplate->setAccess(AS_private);
1803  StaticInvokerTemplate->setImplicit(true);
1804  Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1805  Class->addDecl(StaticInvokerTemplate);
1806  } else
1807  Class->addDecl(Invoke);
1808  }
1809 }
1810 
1811 /// Add a lambda's conversion to function pointers, as described in
1812 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1813 /// single pointer conversion. In the event that the default calling convention
1814 /// for free and member functions is different, it will emit both conventions.
1815 static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1816  CXXRecordDecl *Class,
1817  CXXMethodDecl *CallOperator) {
1818  const FunctionProtoType *CallOpProto =
1819  CallOperator->getType()->castAs<FunctionProtoType>();
1820 
1822  S, *CallOpProto, [&](CallingConv CC) {
1823  QualType InvokerFunctionTy =
1824  S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1825  addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1826  InvokerFunctionTy);
1827  });
1828 }
1829 
1830 /// Add a lambda's conversion to block pointer.
1832  SourceRange IntroducerRange,
1833  CXXRecordDecl *Class,
1834  CXXMethodDecl *CallOperator) {
1835  const FunctionProtoType *CallOpProto =
1836  CallOperator->getType()->castAs<FunctionProtoType>();
1838  CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1839  QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1840 
1841  FunctionProtoType::ExtProtoInfo ConversionEPI(
1843  /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1844  ConversionEPI.TypeQuals = Qualifiers();
1845  ConversionEPI.TypeQuals.addConst();
1846  QualType ConvTy =
1847  S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1848 
1849  SourceLocation Loc = IntroducerRange.getBegin();
1850  DeclarationName Name
1852  S.Context.getCanonicalType(BlockPtrTy));
1854  S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1856  S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1859  /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1860  CallOperator->getBody()->getEndLoc());
1861  Conversion->setAccess(AS_public);
1862  Conversion->setImplicit(true);
1863  Class->addDecl(Conversion);
1864 }
1865 
1867  SourceLocation ImplicitCaptureLoc,
1868  bool IsOpenMPMapping) {
1869  // VLA captures don't have a stored initialization expression.
1870  if (Cap.isVLATypeCapture())
1871  return ExprResult();
1872 
1873  // An init-capture is initialized directly from its stored initializer.
1874  if (Cap.isInitCapture())
1875  return cast<VarDecl>(Cap.getVariable())->getInit();
1876 
1877  // For anything else, build an initialization expression. For an implicit
1878  // capture, the capture notionally happens at the capture-default, so use
1879  // that location here.
1881  ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1882 
1883  // C++11 [expr.prim.lambda]p21:
1884  // When the lambda-expression is evaluated, the entities that
1885  // are captured by copy are used to direct-initialize each
1886  // corresponding non-static data member of the resulting closure
1887  // object. (For array members, the array elements are
1888  // direct-initialized in increasing subscript order.) These
1889  // initializations are performed in the (unspecified) order in
1890  // which the non-static data members are declared.
1891 
1892  // C++ [expr.prim.lambda]p12:
1893  // An entity captured by a lambda-expression is odr-used (3.2) in
1894  // the scope containing the lambda-expression.
1895  ExprResult Init;
1896  IdentifierInfo *Name = nullptr;
1897  if (Cap.isThisCapture()) {
1898  QualType ThisTy = getCurrentThisType();
1899  Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1900  if (Cap.isCopyCapture())
1901  Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1902  else
1903  Init = This;
1904  } else {
1905  assert(Cap.isVariableCapture() && "unknown kind of capture");
1906  ValueDecl *Var = Cap.getVariable();
1907  Name = Var->getIdentifier();
1908  Init = BuildDeclarationNameExpr(
1909  CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1910  }
1911 
1912  // In OpenMP, the capture kind doesn't actually describe how to capture:
1913  // variables are "mapped" onto the device in a process that does not formally
1914  // make a copy, even for a "copy capture".
1915  if (IsOpenMPMapping)
1916  return Init;
1917 
1918  if (Init.isInvalid())
1919  return ExprError();
1920 
1921  Expr *InitExpr = Init.get();
1923  Name, Cap.getCaptureType(), Loc);
1924  InitializationKind InitKind =
1926  InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1927  return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1928 }
1929 
1931  LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1932  ActOnFinishFunctionBody(LSI.CallOperator, Body);
1933  return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1934 }
1935 
1936 static LambdaCaptureDefault
1938  switch (ICS) {
1940  return LCD_None;
1942  return LCD_ByCopy;
1945  return LCD_ByRef;
1947  llvm_unreachable("block capture in lambda");
1948  }
1949  llvm_unreachable("Unknown implicit capture style");
1950 }
1951 
1953  if (From.isInitCapture()) {
1954  Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1955  if (Init && Init->HasSideEffects(Context))
1956  return true;
1957  }
1958 
1959  if (!From.isCopyCapture())
1960  return false;
1961 
1962  const QualType T = From.isThisCapture()
1963  ? getCurrentThisType()->getPointeeType()
1964  : From.getCaptureType();
1965 
1966  if (T.isVolatileQualified())
1967  return true;
1968 
1969  const Type *BaseT = T->getBaseElementTypeUnsafe();
1970  if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1971  return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1972  !RD->hasTrivialDestructor();
1973 
1974  return false;
1975 }
1976 
1978  const Capture &From) {
1979  if (CaptureHasSideEffects(From))
1980  return false;
1981 
1982  if (From.isVLATypeCapture())
1983  return false;
1984 
1985  // FIXME: maybe we should warn on these if we can find a sensible diagnostic
1986  // message
1987  if (From.isInitCapture() &&
1988  From.getVariable()->isPlaceholderVar(getLangOpts()))
1989  return false;
1990 
1991  auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1992  if (From.isThisCapture())
1993  diag << "'this'";
1994  else
1995  diag << From.getVariable();
1996  diag << From.isNonODRUsed();
1997  diag << FixItHint::CreateRemoval(CaptureRange);
1998  return true;
1999 }
2000 
2001 /// Create a field within the lambda class or captured statement record for the
2002 /// given capture.
2004  const sema::Capture &Capture) {
2006  QualType FieldType = Capture.getCaptureType();
2007  IdentifierInfo *Id = nullptr;
2008 
2009  TypeSourceInfo *TSI = nullptr;
2010  if (Capture.isVariableCapture()) {
2011  ValueDecl *Val = Capture.getVariable();
2012  const auto *Var = dyn_cast_or_null<VarDecl>(Val);
2013 
2014  if (Var && Var->isInitCapture())
2015  TSI = Var->getTypeSourceInfo();
2016 
2017  // TODO: Upstream this behavior to LLVM project to save
2018  // user speciifed names for all lambdas.
2019  // For SYCL compilations, save user specified names for
2020  // lambda capture.
2021  if (getLangOpts().SYCLIsDevice || getLangOpts().SYCLIsHost) {
2022  StringRef CaptureName = Val ? Val->getName() : "";
2023  if (!CaptureName.empty())
2024  Id = &Context.Idents.get(CaptureName.str());
2025  }
2026  }
2027 
2028  // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2029  // appropriate, at least for an implicit capture.
2030  if (!TSI)
2031  TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2032 
2033  // Build the non-static data member.
2034  FieldDecl *Field =
2035  FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc, Id,
2036  FieldType, TSI, /*BW=*/nullptr,
2037  /*Mutable=*/false, ICIS_NoInit);
2038  // If the variable being captured has an invalid type, mark the class as
2039  // invalid as well.
2040  if (!FieldType->isDependentType()) {
2041  if (RequireCompleteSizedType(Loc, FieldType,
2042  diag::err_field_incomplete_or_sizeless)) {
2043  RD->setInvalidDecl();
2044  Field->setInvalidDecl();
2045  } else {
2046  NamedDecl *Def;
2047  FieldType->isIncompleteType(&Def);
2048  if (Def && Def->isInvalidDecl()) {
2049  RD->setInvalidDecl();
2050  Field->setInvalidDecl();
2051  }
2052  }
2053  }
2054  Field->setImplicit(true);
2055  Field->setAccess(AS_private);
2056  RD->addDecl(Field);
2057 
2058  if (Capture.isVLATypeCapture())
2059  Field->setCapturedVLAType(Capture.getCapturedVLAType());
2060 
2061  return Field;
2062 }
2063 
2065  LambdaScopeInfo *LSI) {
2066  // Collect information from the lambda scope.
2068  SmallVector<Expr *, 4> CaptureInits;
2069  SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2070  LambdaCaptureDefault CaptureDefault =
2073  CXXMethodDecl *CallOperator;
2074  SourceRange IntroducerRange;
2075  bool ExplicitParams;
2076  bool ExplicitResultType;
2077  CleanupInfo LambdaCleanup;
2078  bool ContainsUnexpandedParameterPack;
2079  bool IsGenericLambda;
2080  {
2081  CallOperator = LSI->CallOperator;
2082  Class = LSI->Lambda;
2083  IntroducerRange = LSI->IntroducerRange;
2084  ExplicitParams = LSI->ExplicitParams;
2085  ExplicitResultType = !LSI->HasImplicitReturnType;
2086  LambdaCleanup = LSI->Cleanup;
2087  ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2088  IsGenericLambda = Class->isGenericLambda();
2089 
2090  CallOperator->setLexicalDeclContext(Class);
2091  Decl *TemplateOrNonTemplateCallOperatorDecl =
2092  CallOperator->getDescribedFunctionTemplate()
2093  ? CallOperator->getDescribedFunctionTemplate()
2094  : cast<Decl>(CallOperator);
2095 
2096  // FIXME: Is this really the best choice? Keeping the lexical decl context
2097  // set as CurContext seems more faithful to the source.
2098  TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2099 
2100  PopExpressionEvaluationContext();
2101 
2102  // True if the current capture has a used capture or default before it.
2103  bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2104  SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2105  CaptureDefaultLoc : IntroducerRange.getBegin();
2106 
2107  for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2108  const Capture &From = LSI->Captures[I];
2109 
2110  if (From.isInvalid())
2111  return ExprError();
2112 
2113  assert(!From.isBlockCapture() && "Cannot capture __block variables");
2114  bool IsImplicit = I >= LSI->NumExplicitCaptures;
2115  SourceLocation ImplicitCaptureLoc =
2116  IsImplicit ? CaptureDefaultLoc : SourceLocation();
2117 
2118  // Use source ranges of explicit captures for fixits where available.
2119  SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2120 
2121  // Warn about unused explicit captures.
2122  bool IsCaptureUsed = true;
2123  if (!CurContext->isDependentContext() && !IsImplicit &&
2124  !From.isODRUsed()) {
2125  // Initialized captures that are non-ODR used may not be eliminated.
2126  // FIXME: Where did the IsGenericLambda here come from?
2127  bool NonODRUsedInitCapture =
2128  IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2129  if (!NonODRUsedInitCapture) {
2130  bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2131  SourceRange FixItRange;
2132  if (CaptureRange.isValid()) {
2133  if (!CurHasPreviousCapture && !IsLast) {
2134  // If there are no captures preceding this capture, remove the
2135  // following comma.
2136  FixItRange = SourceRange(CaptureRange.getBegin(),
2137  getLocForEndOfToken(CaptureRange.getEnd()));
2138  } else {
2139  // Otherwise, remove the comma since the last used capture.
2140  FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2141  CaptureRange.getEnd());
2142  }
2143  }
2144 
2145  IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2146  }
2147  }
2148 
2149  if (CaptureRange.isValid()) {
2150  CurHasPreviousCapture |= IsCaptureUsed;
2151  PrevCaptureLoc = CaptureRange.getEnd();
2152  }
2153 
2154  // Map the capture to our AST representation.
2155  LambdaCapture Capture = [&] {
2156  if (From.isThisCapture()) {
2157  // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2158  // because it results in a reference capture. Don't warn prior to
2159  // C++2a; there's nothing that can be done about it before then.
2160  if (getLangOpts().CPlusPlus20 && IsImplicit &&
2161  CaptureDefault == LCD_ByCopy) {
2162  Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2163  Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2165  getLocForEndOfToken(CaptureDefaultLoc), ", this");
2166  }
2167  return LambdaCapture(From.getLocation(), IsImplicit,
2168  From.isCopyCapture() ? LCK_StarThis : LCK_This);
2169  } else if (From.isVLATypeCapture()) {
2170  return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2171  } else {
2172  assert(From.isVariableCapture() && "unknown kind of capture");
2173  ValueDecl *Var = From.getVariable();
2175  From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
2176  return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2177  From.getEllipsisLoc());
2178  }
2179  }();
2180 
2181  // Form the initializer for the capture field.
2182  ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2183 
2184  // FIXME: Skip this capture if the capture is not used, the initializer
2185  // has no side-effects, the type of the capture is trivial, and the
2186  // lambda is not externally visible.
2187 
2188  // Add a FieldDecl for the capture and form its initializer.
2189  BuildCaptureField(Class, From);
2190  Captures.push_back(Capture);
2191  CaptureInits.push_back(Init.get());
2192 
2193  if (LangOpts.CUDA)
2194  CUDA().CheckLambdaCapture(CallOperator, From);
2195  }
2196 
2197  Class->setCaptures(Context, Captures);
2198 
2199  // C++11 [expr.prim.lambda]p6:
2200  // The closure type for a lambda-expression with no lambda-capture
2201  // has a public non-virtual non-explicit const conversion function
2202  // to pointer to function having the same parameter and return
2203  // types as the closure type's function call operator.
2204  if (Captures.empty() && CaptureDefault == LCD_None)
2205  addFunctionPointerConversions(*this, IntroducerRange, Class,
2206  CallOperator);
2207 
2208  // Objective-C++:
2209  // The closure type for a lambda-expression has a public non-virtual
2210  // non-explicit const conversion function to a block pointer having the
2211  // same parameter and return types as the closure type's function call
2212  // operator.
2213  // FIXME: Fix generic lambda to block conversions.
2214  if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2215  addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2216 
2217  // Finalize the lambda class.
2218  SmallVector<Decl*, 4> Fields(Class->fields());
2219  ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2221  CheckCompletedCXXClass(nullptr, Class);
2222  }
2223 
2224  Cleanup.mergeFrom(LambdaCleanup);
2225 
2226  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2227  CaptureDefault, CaptureDefaultLoc,
2228  ExplicitParams, ExplicitResultType,
2229  CaptureInits, EndLoc,
2230  ContainsUnexpandedParameterPack);
2231  // If the lambda expression's call operator is not explicitly marked constexpr
2232  // and we are not in a dependent context, analyze the call operator to infer
2233  // its constexpr-ness, suppressing diagnostics while doing so.
2234  if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2235  !CallOperator->isConstexpr() &&
2236  !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2237  !Class->getDeclContext()->isDependentContext()) {
2238  CallOperator->setConstexprKind(
2239  CheckConstexprFunctionDefinition(CallOperator,
2240  CheckConstexprKind::CheckValid)
2243  }
2244 
2245  // Emit delayed shadowing warnings now that the full capture list is known.
2246  DiagnoseShadowingLambdaDecls(LSI);
2247 
2248  if (!CurContext->isDependentContext()) {
2249  switch (ExprEvalContexts.back().Context) {
2250  // C++11 [expr.prim.lambda]p2:
2251  // A lambda-expression shall not appear in an unevaluated operand
2252  // (Clause 5).
2253  case ExpressionEvaluationContext::Unevaluated:
2254  case ExpressionEvaluationContext::UnevaluatedList:
2255  case ExpressionEvaluationContext::UnevaluatedAbstract:
2256  // C++1y [expr.const]p2:
2257  // A conditional-expression e is a core constant expression unless the
2258  // evaluation of e, following the rules of the abstract machine, would
2259  // evaluate [...] a lambda-expression.
2260  //
2261  // This is technically incorrect, there are some constant evaluated contexts
2262  // where this should be allowed. We should probably fix this when DR1607 is
2263  // ratified, it lays out the exact set of conditions where we shouldn't
2264  // allow a lambda-expression.
2265  case ExpressionEvaluationContext::ConstantEvaluated:
2266  case ExpressionEvaluationContext::ImmediateFunctionContext:
2267  // We don't actually diagnose this case immediately, because we
2268  // could be within a context where we might find out later that
2269  // the expression is potentially evaluated (e.g., for typeid).
2270  ExprEvalContexts.back().Lambdas.push_back(Lambda);
2271  break;
2272 
2273  case ExpressionEvaluationContext::DiscardedStatement:
2274  case ExpressionEvaluationContext::PotentiallyEvaluated:
2275  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
2276  break;
2277  }
2278  }
2279 
2280  return MaybeBindToTemporary(Lambda);
2281 }
2282 
2284  SourceLocation ConvLocation,
2285  CXXConversionDecl *Conv,
2286  Expr *Src) {
2287  // Make sure that the lambda call operator is marked used.
2288  CXXRecordDecl *Lambda = Conv->getParent();
2289  CXXMethodDecl *CallOperator
2290  = cast<CXXMethodDecl>(
2291  Lambda->lookup(
2292  Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2293  CallOperator->setReferenced();
2294  CallOperator->markUsed(Context);
2295 
2296  ExprResult Init = PerformCopyInitialization(
2298  CurrentLocation, Src);
2299  if (!Init.isInvalid())
2300  Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2301 
2302  if (Init.isInvalid())
2303  return ExprError();
2304 
2305  // Create the new block to be returned.
2306  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
2307 
2308  // Set the type information.
2309  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2310  Block->setIsVariadic(CallOperator->isVariadic());
2311  Block->setBlockMissingReturnType(false);
2312 
2313  // Add parameters.
2314  SmallVector<ParmVarDecl *, 4> BlockParams;
2315  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2316  ParmVarDecl *From = CallOperator->getParamDecl(I);
2317  BlockParams.push_back(ParmVarDecl::Create(
2318  Context, Block, From->getBeginLoc(), From->getLocation(),
2319  From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2320  From->getStorageClass(),
2321  /*DefArg=*/nullptr));
2322  }
2323  Block->setParams(BlockParams);
2324 
2325  Block->setIsConversionFromLambda(true);
2326 
2327  // Add capture. The capture uses a fake variable, which doesn't correspond
2328  // to any actual memory location. However, the initializer copy-initializes
2329  // the lambda object.
2330  TypeSourceInfo *CapVarTSI =
2331  Context.getTrivialTypeSourceInfo(Src->getType());
2332  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2333  ConvLocation, nullptr,
2334  Src->getType(), CapVarTSI,
2335  SC_None);
2336  BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2337  /*nested=*/false, /*copy=*/Init.get());
2338  Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2339 
2340  // Add a fake function body to the block. IR generation is responsible
2341  // for filling in the actual body, which cannot be expressed as an AST.
2342  Block->setBody(new (Context) CompoundStmt(ConvLocation));
2343 
2344  // Create the block literal expression.
2345  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2346  ExprCleanupObjects.push_back(Block);
2347  Cleanup.setExprNeedsCleanups(true);
2348 
2349  return BuildBlock;
2350 }
2351 
2354  while (FD->getInstantiatedFromMemberFunction())
2356  return FD;
2357  }
2358 
2360  return FD->getInstantiatedFromDecl();
2361 
2363  if (!FTD)
2364  return nullptr;
2365 
2366  while (FTD->getInstantiatedFromMemberTemplate())
2367  FTD = FTD->getInstantiatedFromMemberTemplate();
2368 
2369  return FTD->getTemplatedDecl();
2370 }
2371 
2374  Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
2375  LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2376  : FunctionScopeRAII(SemaRef) {
2377  if (!isLambdaCallOperator(FD)) {
2379  return;
2380  }
2381 
2382  SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2383 
2384  FunctionDecl *Pattern = getPatternFunctionDecl(FD);
2385  if (Pattern) {
2386  SemaRef.addInstantiatedCapturesToScope(FD, Pattern, Scope, MLTAL);
2387 
2388  FunctionDecl *ParentFD = FD;
2389  while (ShouldAddDeclsFromParentScope) {
2390 
2391  ParentFD =
2392  dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(ParentFD));
2393  Pattern =
2394  dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(Pattern));
2395 
2396  if (!FD || !Pattern)
2397  break;
2398 
2399  SemaRef.addInstantiatedParametersToScope(ParentFD, Pattern, Scope, MLTAL);
2400  SemaRef.addInstantiatedLocalVarsToScope(ParentFD, Pattern, Scope);
2401  }
2402  }
2403 }
#define V(N, I)
Definition: ASTContext.h:3299
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the clang::Expr interface and subclasses for C++ expressions.
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static CallingConv getLambdaConversionFunctionCallConv(Sema &S, const FunctionProtoType *CallOpProto)
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:234
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 LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:884
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 FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
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 QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:364
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 bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:268
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:916
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.
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:890
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for OpenMP constructs and clauses.
tok::TokenKind ContextKind
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
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:651
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:2589
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2605
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:1122
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:1605
IdentifierTable & Idents
Definition: ASTContext.h:647
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:1185
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1094
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:1583
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1203
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
PtrTy get() const
Definition: Ownership.h:170
Attr - This represents one attribute.
Definition: Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
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:4503
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4497
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5420
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6214
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:2890
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:2462
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:2274
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
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4231
reference front() const
Definition: DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
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:1260
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:829
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
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
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
DeclContext * getDeclContext()
Definition: DeclBase.h:454
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.
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:815
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:806
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2020
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2456
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2633
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2487
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5959
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3300
Represents an enum.
Definition: Decl.h:3870
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5587
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:3467
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:3107
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
bool isFPConstrained() const
Definition: LangOptions.h:884
Represents a member of a struct/union/class.
Definition: Decl.h:3060
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:4549
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
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:98
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:1057
const Expr * getSubExpr() const
Definition: Expr.h:1052
Represents a function declaration or definition.
Definition: Decl.h:1972
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3240
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2441
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4051
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4046
QualType getReturnType() const
Definition: Decl.h:2757
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4166
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
@ TK_MemberSpecialization
Definition: Decl.h:1984
@ TK_DependentNonTemplate
Definition: Decl.h:1993
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3997
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2435
bool isImmediateEscalating() const
Definition: Decl.cpp:3272
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4070
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2438
bool isConsteval() const
Definition: Decl.h:2447
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2805
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4018
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2717
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4908
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5024
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4912
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4494
CallingConv getCallConv() const
Definition: Type.h:4596
QualType getReturnType() const
Definition: Type.h:4585
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:3707
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2129
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:8585
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:1950
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:1244
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:558
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
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
PtrTy get() const
Definition: Ownership.h:80
Represents a pack expansion of types.
Definition: Type.h:6581
Expr ** getExprs()
Definition: Expr.h:5705
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5694
Represents a parameter to a function.
Definition: Decl.h:1762
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:2919
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
A (possibly-)qualified type.
Definition: Type.h:940
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7497
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:7572
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7465
The collection of all-type qualifiers we support.
Definition: Type.h:318
void addConst()
Definition: Type.h:446
void addAddressSpace(LangAS space, bool AllowDefaultAddrSpace=false)
Definition: Type.h:583
Represents a struct/union/class.
Definition: Decl.h:4171
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setRetValue(Expr *E)
Definition: Stmt.h:3052
SourceLocation getBeginLoc() const
Definition: Stmt.h:3076
Expr * getRetValue()
Definition: Stmt.h:3050
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Scope * getTemplateParamParent()
Definition: Scope.h:315
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
Sema & SemaRef
Definition: SemaBase.h:40
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2558
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:462
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
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.
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
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:806
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
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:15678
ASTContext & Context
Definition: Sema.h:857
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:18835
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2497
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:1566
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10917
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
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 DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & getLangOpts() const
Definition: Sema.h:519
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
TryCaptureKind
Definition: Sema.h:5434
@ TryCapture_Implicit
Definition: Sema.h:5435
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
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...
ASTContext & getASTContext() const
Definition: Sema.h:526
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8923
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,...
FPOptions & getCurFPFeatures()
Definition: Sema.h:521
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
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 DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:392
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:4435
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:3811
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:1679
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
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
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:7342
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:7353
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
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:7939
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:8227
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2661
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8110
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8073
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:8160
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4649
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5375
Represents a variable declaration or definition.
Definition: Decl.h:919
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2152
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1433
void setInitCapture(bool IC)
Definition: Decl.h:1562
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1559
InitializationStyle
Initialization styles.
Definition: Decl.h:922
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:930
@ CInit
C-style initialization with assignment.
Definition: Decl.h:924
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:927
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1172
void setInit(Expr *I)
Definition: Decl.cpp:2458
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1156
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2667
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:222
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
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
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
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.
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1903
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
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:1762
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
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:29
@ CopyInit
[a = b], [a = {b}]
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
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:1592
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1583
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1586
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1555
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1330
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4721
Extra information about a function prototype.
Definition: Type.h:4747
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4754
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4748
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2883
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2896
Represents a complete lambda introducer.
Definition: DeclSpec.h:2832
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2857
SourceLocation DefaultLoc
Definition: DeclSpec.h:2855
LambdaCaptureDefault Default
Definition: DeclSpec.h:2856
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:877