SemaLambda.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076
  1. //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for C++ lambda expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/DeclSpec.h"
  13. #include "TypeLocBuilder.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ExprCXX.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/Scope.h"
  20. #include "clang/Sema/ScopeInfo.h"
  21. #include "clang/Sema/SemaInternal.h"
  22. #include "clang/Sema/SemaLambda.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include <optional>
  25. using namespace clang;
  26. using namespace sema;
  27. /// Examines the FunctionScopeInfo stack to determine the nearest
  28. /// enclosing lambda (to the current lambda) that is 'capture-ready' for
  29. /// the variable referenced in the current lambda (i.e. \p VarToCapture).
  30. /// If successful, returns the index into Sema's FunctionScopeInfo stack
  31. /// of the capture-ready lambda's LambdaScopeInfo.
  32. ///
  33. /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
  34. /// lambda - is on top) to determine the index of the nearest enclosing/outer
  35. /// lambda that is ready to capture the \p VarToCapture being referenced in
  36. /// the current lambda.
  37. /// As we climb down the stack, we want the index of the first such lambda -
  38. /// that is the lambda with the highest index that is 'capture-ready'.
  39. ///
  40. /// A lambda 'L' is capture-ready for 'V' (var or this) if:
  41. /// - its enclosing context is non-dependent
  42. /// - and if the chain of lambdas between L and the lambda in which
  43. /// V is potentially used (i.e. the lambda at the top of the scope info
  44. /// stack), can all capture or have already captured V.
  45. /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
  46. ///
  47. /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
  48. /// for whether it is 'capture-capable' (see
  49. /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
  50. /// capture.
  51. ///
  52. /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
  53. /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
  54. /// is at the top of the stack and has the highest index.
  55. /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
  56. ///
  57. /// \returns An std::optional<unsigned> Index that if evaluates to 'true'
  58. /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
  59. /// lambda which is capture-ready. If the return value evaluates to 'false'
  60. /// then no lambda is capture-ready for \p VarToCapture.
  61. static inline std::optional<unsigned>
  62. getStackIndexOfNearestEnclosingCaptureReadyLambda(
  63. ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
  64. ValueDecl *VarToCapture) {
  65. // Label failure to capture.
  66. const std::optional<unsigned> NoLambdaIsCaptureReady;
  67. // Ignore all inner captured regions.
  68. unsigned CurScopeIndex = FunctionScopes.size() - 1;
  69. while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
  70. FunctionScopes[CurScopeIndex]))
  71. --CurScopeIndex;
  72. assert(
  73. isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
  74. "The function on the top of sema's function-info stack must be a lambda");
  75. // If VarToCapture is null, we are attempting to capture 'this'.
  76. const bool IsCapturingThis = !VarToCapture;
  77. const bool IsCapturingVariable = !IsCapturingThis;
  78. // Start with the current lambda at the top of the stack (highest index).
  79. DeclContext *EnclosingDC =
  80. cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
  81. do {
  82. const clang::sema::LambdaScopeInfo *LSI =
  83. cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
  84. // IF we have climbed down to an intervening enclosing lambda that contains
  85. // the variable declaration - it obviously can/must not capture the
  86. // variable.
  87. // Since its enclosing DC is dependent, all the lambdas between it and the
  88. // innermost nested lambda are dependent (otherwise we wouldn't have
  89. // arrived here) - so we don't yet have a lambda that can capture the
  90. // variable.
  91. if (IsCapturingVariable &&
  92. VarToCapture->getDeclContext()->Equals(EnclosingDC))
  93. return NoLambdaIsCaptureReady;
  94. // For an enclosing lambda to be capture ready for an entity, all
  95. // intervening lambda's have to be able to capture that entity. If even
  96. // one of the intervening lambda's is not capable of capturing the entity
  97. // then no enclosing lambda can ever capture that entity.
  98. // For e.g.
  99. // const int x = 10;
  100. // [=](auto a) { #1
  101. // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
  102. // [=](auto c) { #3
  103. // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
  104. // }; }; };
  105. // If they do not have a default implicit capture, check to see
  106. // if the entity has already been explicitly captured.
  107. // If even a single dependent enclosing lambda lacks the capability
  108. // to ever capture this variable, there is no further enclosing
  109. // non-dependent lambda that can capture this variable.
  110. if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
  111. if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
  112. return NoLambdaIsCaptureReady;
  113. if (IsCapturingThis && !LSI->isCXXThisCaptured())
  114. return NoLambdaIsCaptureReady;
  115. }
  116. EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
  117. assert(CurScopeIndex);
  118. --CurScopeIndex;
  119. } while (!EnclosingDC->isTranslationUnit() &&
  120. EnclosingDC->isDependentContext() &&
  121. isLambdaCallOperator(EnclosingDC));
  122. assert(CurScopeIndex < (FunctionScopes.size() - 1));
  123. // If the enclosingDC is not dependent, then the immediately nested lambda
  124. // (one index above) is capture-ready.
  125. if (!EnclosingDC->isDependentContext())
  126. return CurScopeIndex + 1;
  127. return NoLambdaIsCaptureReady;
  128. }
  129. /// Examines the FunctionScopeInfo stack to determine the nearest
  130. /// enclosing lambda (to the current lambda) that is 'capture-capable' for
  131. /// the variable referenced in the current lambda (i.e. \p VarToCapture).
  132. /// If successful, returns the index into Sema's FunctionScopeInfo stack
  133. /// of the capture-capable lambda's LambdaScopeInfo.
  134. ///
  135. /// Given the current stack of lambdas being processed by Sema and
  136. /// the variable of interest, to identify the nearest enclosing lambda (to the
  137. /// current lambda at the top of the stack) that can truly capture
  138. /// a variable, it has to have the following two properties:
  139. /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
  140. /// - climb down the stack (i.e. starting from the innermost and examining
  141. /// each outer lambda step by step) checking if each enclosing
  142. /// lambda can either implicitly or explicitly capture the variable.
  143. /// Record the first such lambda that is enclosed in a non-dependent
  144. /// context. If no such lambda currently exists return failure.
  145. /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
  146. /// capture the variable by checking all its enclosing lambdas:
  147. /// - check if all outer lambdas enclosing the 'capture-ready' lambda
  148. /// identified above in 'a' can also capture the variable (this is done
  149. /// via tryCaptureVariable for variables and CheckCXXThisCapture for
  150. /// 'this' by passing in the index of the Lambda identified in step 'a')
  151. ///
  152. /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
  153. /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
  154. /// is at the top of the stack.
  155. ///
  156. /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
  157. ///
  158. ///
  159. /// \returns An std::optional<unsigned> Index that if evaluates to 'true'
  160. /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
  161. /// lambda which is capture-capable. If the return value evaluates to 'false'
  162. /// then no lambda is capture-capable for \p VarToCapture.
  163. std::optional<unsigned>
  164. clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
  165. ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
  166. ValueDecl *VarToCapture, Sema &S) {
  167. const std::optional<unsigned> NoLambdaIsCaptureCapable;
  168. const std::optional<unsigned> OptionalStackIndex =
  169. getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
  170. VarToCapture);
  171. if (!OptionalStackIndex)
  172. return NoLambdaIsCaptureCapable;
  173. const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
  174. assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
  175. S.getCurGenericLambda()) &&
  176. "The capture ready lambda for a potential capture can only be the "
  177. "current lambda if it is a generic lambda");
  178. const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
  179. cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
  180. // If VarToCapture is null, we are attempting to capture 'this'
  181. const bool IsCapturingThis = !VarToCapture;
  182. const bool IsCapturingVariable = !IsCapturingThis;
  183. if (IsCapturingVariable) {
  184. // Check if the capture-ready lambda can truly capture the variable, by
  185. // checking whether all enclosing lambdas of the capture-ready lambda allow
  186. // the capture - i.e. make sure it is capture-capable.
  187. QualType CaptureType, DeclRefType;
  188. const bool CanCaptureVariable =
  189. !S.tryCaptureVariable(VarToCapture,
  190. /*ExprVarIsUsedInLoc*/ SourceLocation(),
  191. clang::Sema::TryCapture_Implicit,
  192. /*EllipsisLoc*/ SourceLocation(),
  193. /*BuildAndDiagnose*/ false, CaptureType,
  194. DeclRefType, &IndexOfCaptureReadyLambda);
  195. if (!CanCaptureVariable)
  196. return NoLambdaIsCaptureCapable;
  197. } else {
  198. // Check if the capture-ready lambda can truly capture 'this' by checking
  199. // whether all enclosing lambdas of the capture-ready lambda can capture
  200. // 'this'.
  201. const bool CanCaptureThis =
  202. !S.CheckCXXThisCapture(
  203. CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
  204. /*Explicit*/ false, /*BuildAndDiagnose*/ false,
  205. &IndexOfCaptureReadyLambda);
  206. if (!CanCaptureThis)
  207. return NoLambdaIsCaptureCapable;
  208. }
  209. return IndexOfCaptureReadyLambda;
  210. }
  211. static inline TemplateParameterList *
  212. getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
  213. if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
  214. LSI->GLTemplateParameterList = TemplateParameterList::Create(
  215. SemaRef.Context,
  216. /*Template kw loc*/ SourceLocation(),
  217. /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
  218. LSI->TemplateParams,
  219. /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
  220. LSI->RequiresClause.get());
  221. }
  222. return LSI->GLTemplateParameterList;
  223. }
  224. CXXRecordDecl *
  225. Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
  226. unsigned LambdaDependencyKind,
  227. LambdaCaptureDefault CaptureDefault) {
  228. DeclContext *DC = CurContext;
  229. while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
  230. DC = DC->getParent();
  231. bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
  232. *this);
  233. // Start constructing the lambda class.
  234. CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
  235. Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
  236. IsGenericLambda, CaptureDefault);
  237. DC->addDecl(Class);
  238. return Class;
  239. }
  240. /// Determine whether the given context is or is enclosed in an inline
  241. /// function.
  242. static bool isInInlineFunction(const DeclContext *DC) {
  243. while (!DC->isFileContext()) {
  244. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  245. if (FD->isInlined())
  246. return true;
  247. DC = DC->getLexicalParent();
  248. }
  249. return false;
  250. }
  251. std::tuple<MangleNumberingContext *, Decl *>
  252. Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
  253. // Compute the context for allocating mangling numbers in the current
  254. // expression, if the ABI requires them.
  255. Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  256. enum ContextKind {
  257. Normal,
  258. DefaultArgument,
  259. DataMember,
  260. StaticDataMember,
  261. InlineVariable,
  262. VariableTemplate,
  263. Concept
  264. } Kind = Normal;
  265. // Default arguments of member function parameters that appear in a class
  266. // definition, as well as the initializers of data members, receive special
  267. // treatment. Identify them.
  268. if (ManglingContextDecl) {
  269. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
  270. if (const DeclContext *LexicalDC
  271. = Param->getDeclContext()->getLexicalParent())
  272. if (LexicalDC->isRecord())
  273. Kind = DefaultArgument;
  274. } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
  275. if (Var->getDeclContext()->isRecord())
  276. Kind = StaticDataMember;
  277. else if (Var->getMostRecentDecl()->isInline())
  278. Kind = InlineVariable;
  279. else if (Var->getDescribedVarTemplate())
  280. Kind = VariableTemplate;
  281. else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
  282. if (!VTS->isExplicitSpecialization())
  283. Kind = VariableTemplate;
  284. }
  285. } else if (isa<FieldDecl>(ManglingContextDecl)) {
  286. Kind = DataMember;
  287. } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
  288. Kind = Concept;
  289. }
  290. }
  291. // Itanium ABI [5.1.7]:
  292. // In the following contexts [...] the one-definition rule requires closure
  293. // types in different translation units to "correspond":
  294. bool IsInNonspecializedTemplate =
  295. inTemplateInstantiation() || CurContext->isDependentContext();
  296. switch (Kind) {
  297. case Normal: {
  298. // -- the bodies of non-exported nonspecialized template functions
  299. // -- the bodies of inline functions
  300. if ((IsInNonspecializedTemplate &&
  301. !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
  302. isInInlineFunction(CurContext)) {
  303. while (auto *CD = dyn_cast<CapturedDecl>(DC))
  304. DC = CD->getParent();
  305. return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
  306. }
  307. return std::make_tuple(nullptr, nullptr);
  308. }
  309. case Concept:
  310. // Concept definitions aren't code generated and thus aren't mangled,
  311. // however the ManglingContextDecl is important for the purposes of
  312. // re-forming the template argument list of the lambda for constraint
  313. // evaluation.
  314. case StaticDataMember:
  315. // -- the initializers of nonspecialized static members of template classes
  316. if (!IsInNonspecializedTemplate)
  317. return std::make_tuple(nullptr, ManglingContextDecl);
  318. // Fall through to get the current context.
  319. [[fallthrough]];
  320. case DataMember:
  321. // -- the in-class initializers of class members
  322. case DefaultArgument:
  323. // -- default arguments appearing in class definitions
  324. case InlineVariable:
  325. // -- the initializers of inline variables
  326. case VariableTemplate:
  327. // -- the initializers of templated variables
  328. return std::make_tuple(
  329. &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
  330. ManglingContextDecl),
  331. ManglingContextDecl);
  332. }
  333. llvm_unreachable("unexpected context");
  334. }
  335. CXXMethodDecl *Sema::startLambdaDefinition(
  336. CXXRecordDecl *Class, SourceRange IntroducerRange,
  337. TypeSourceInfo *MethodTypeInfo, SourceLocation EndLoc,
  338. ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind,
  339. StorageClass SC, Expr *TrailingRequiresClause) {
  340. QualType MethodType = MethodTypeInfo->getType();
  341. TemplateParameterList *TemplateParams =
  342. getGenericLambdaTemplateParameterList(getCurLambda(), *this);
  343. // If a lambda appears in a dependent context or is a generic lambda (has
  344. // template parameters) and has an 'auto' return type, deduce it to a
  345. // dependent type.
  346. if (Class->isDependentContext() || TemplateParams) {
  347. const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
  348. QualType Result = FPT->getReturnType();
  349. if (Result->isUndeducedType()) {
  350. Result = SubstAutoTypeDependent(Result);
  351. MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
  352. FPT->getExtProtoInfo());
  353. }
  354. }
  355. // C++11 [expr.prim.lambda]p5:
  356. // The closure type for a lambda-expression has a public inline function
  357. // call operator (13.5.4) whose parameters and return type are described by
  358. // the lambda-expression's parameter-declaration-clause and
  359. // trailing-return-type respectively.
  360. DeclarationName MethodName
  361. = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  362. DeclarationNameLoc MethodNameLoc =
  363. DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
  364. CXXMethodDecl *Method = CXXMethodDecl::Create(
  365. Context, Class, EndLoc,
  366. DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
  367. MethodNameLoc),
  368. MethodType, MethodTypeInfo, SC, getCurFPFeatures().isFPConstrained(),
  369. /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
  370. Method->setAccess(AS_public);
  371. if (!TemplateParams)
  372. Class->addDecl(Method);
  373. // Temporarily set the lexical declaration context to the current
  374. // context, so that the Scope stack matches the lexical nesting.
  375. Method->setLexicalDeclContext(CurContext);
  376. // Create a function template if we have a template parameter list
  377. FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
  378. FunctionTemplateDecl::Create(Context, Class,
  379. Method->getLocation(), MethodName,
  380. TemplateParams,
  381. Method) : nullptr;
  382. if (TemplateMethod) {
  383. TemplateMethod->setAccess(AS_public);
  384. Method->setDescribedFunctionTemplate(TemplateMethod);
  385. Class->addDecl(TemplateMethod);
  386. TemplateMethod->setLexicalDeclContext(CurContext);
  387. }
  388. // Add parameters.
  389. if (!Params.empty()) {
  390. Method->setParams(Params);
  391. CheckParmsForFunctionDef(Params,
  392. /*CheckParameterNames=*/false);
  393. for (auto *P : Method->parameters())
  394. P->setOwningFunction(Method);
  395. }
  396. return Method;
  397. }
  398. void Sema::handleLambdaNumbering(
  399. CXXRecordDecl *Class, CXXMethodDecl *Method,
  400. std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
  401. if (Mangling) {
  402. bool HasKnownInternalLinkage;
  403. unsigned ManglingNumber, DeviceManglingNumber;
  404. Decl *ManglingContextDecl;
  405. std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
  406. ManglingContextDecl) = *Mangling;
  407. Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
  408. HasKnownInternalLinkage);
  409. Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
  410. return;
  411. }
  412. auto getMangleNumberingContext =
  413. [this](CXXRecordDecl *Class,
  414. Decl *ManglingContextDecl) -> MangleNumberingContext * {
  415. // Get mangle numbering context if there's any extra decl context.
  416. if (ManglingContextDecl)
  417. return &Context.getManglingNumberContext(
  418. ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
  419. // Otherwise, from that lambda's decl context.
  420. auto DC = Class->getDeclContext();
  421. while (auto *CD = dyn_cast<CapturedDecl>(DC))
  422. DC = CD->getParent();
  423. return &Context.getManglingNumberContext(DC);
  424. };
  425. MangleNumberingContext *MCtx;
  426. Decl *ManglingContextDecl;
  427. std::tie(MCtx, ManglingContextDecl) =
  428. getCurrentMangleNumberContext(Class->getDeclContext());
  429. bool HasKnownInternalLinkage = false;
  430. if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
  431. getLangOpts().SYCLIsHost)) {
  432. // Force lambda numbering in CUDA/HIP as we need to name lambdas following
  433. // ODR. Both device- and host-compilation need to have a consistent naming
  434. // on kernel functions. As lambdas are potential part of these `__global__`
  435. // function names, they needs numbering following ODR.
  436. // Also force for SYCL, since we need this for the
  437. // __builtin_sycl_unique_stable_name implementation, which depends on lambda
  438. // mangling.
  439. MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
  440. assert(MCtx && "Retrieving mangle numbering context failed!");
  441. HasKnownInternalLinkage = true;
  442. }
  443. if (MCtx) {
  444. unsigned ManglingNumber = MCtx->getManglingNumber(Method);
  445. Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
  446. HasKnownInternalLinkage);
  447. Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
  448. }
  449. }
  450. void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
  451. CXXMethodDecl *CallOperator,
  452. SourceRange IntroducerRange,
  453. LambdaCaptureDefault CaptureDefault,
  454. SourceLocation CaptureDefaultLoc,
  455. bool ExplicitParams,
  456. bool ExplicitResultType,
  457. bool Mutable) {
  458. LSI->CallOperator = CallOperator;
  459. CXXRecordDecl *LambdaClass = CallOperator->getParent();
  460. LSI->Lambda = LambdaClass;
  461. if (CaptureDefault == LCD_ByCopy)
  462. LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
  463. else if (CaptureDefault == LCD_ByRef)
  464. LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
  465. LSI->CaptureDefaultLoc = CaptureDefaultLoc;
  466. LSI->IntroducerRange = IntroducerRange;
  467. LSI->ExplicitParams = ExplicitParams;
  468. LSI->Mutable = Mutable;
  469. if (ExplicitResultType) {
  470. LSI->ReturnType = CallOperator->getReturnType();
  471. if (!LSI->ReturnType->isDependentType() &&
  472. !LSI->ReturnType->isVoidType()) {
  473. if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
  474. diag::err_lambda_incomplete_result)) {
  475. // Do nothing.
  476. }
  477. }
  478. } else {
  479. LSI->HasImplicitReturnType = true;
  480. }
  481. }
  482. void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
  483. LSI->finishedExplicitCaptures();
  484. }
  485. void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
  486. ArrayRef<NamedDecl *> TParams,
  487. SourceLocation RAngleLoc,
  488. ExprResult RequiresClause) {
  489. LambdaScopeInfo *LSI = getCurLambda();
  490. assert(LSI && "Expected a lambda scope");
  491. assert(LSI->NumExplicitTemplateParams == 0 &&
  492. "Already acted on explicit template parameters");
  493. assert(LSI->TemplateParams.empty() &&
  494. "Explicit template parameters should come "
  495. "before invented (auto) ones");
  496. assert(!TParams.empty() &&
  497. "No template parameters to act on");
  498. LSI->TemplateParams.append(TParams.begin(), TParams.end());
  499. LSI->NumExplicitTemplateParams = TParams.size();
  500. LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
  501. LSI->RequiresClause = RequiresClause;
  502. }
  503. void Sema::addLambdaParameters(
  504. ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
  505. CXXMethodDecl *CallOperator, Scope *CurScope) {
  506. // Introduce our parameters into the function scope
  507. for (unsigned p = 0, NumParams = CallOperator->getNumParams();
  508. p < NumParams; ++p) {
  509. ParmVarDecl *Param = CallOperator->getParamDecl(p);
  510. // If this has an identifier, add it to the scope stack.
  511. if (CurScope && Param->getIdentifier()) {
  512. bool Error = false;
  513. // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
  514. // retroactively apply it.
  515. for (const auto &Capture : Captures) {
  516. if (Capture.Id == Param->getIdentifier()) {
  517. Error = true;
  518. Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
  519. Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
  520. << Capture.Id << true;
  521. }
  522. }
  523. if (!Error)
  524. CheckShadow(CurScope, Param);
  525. PushOnScopeChains(Param, CurScope);
  526. }
  527. }
  528. }
  529. /// If this expression is an enumerator-like expression of some type
  530. /// T, return the type T; otherwise, return null.
  531. ///
  532. /// Pointer comparisons on the result here should always work because
  533. /// it's derived from either the parent of an EnumConstantDecl
  534. /// (i.e. the definition) or the declaration returned by
  535. /// EnumType::getDecl() (i.e. the definition).
  536. static EnumDecl *findEnumForBlockReturn(Expr *E) {
  537. // An expression is an enumerator-like expression of type T if,
  538. // ignoring parens and parens-like expressions:
  539. E = E->IgnoreParens();
  540. // - it is an enumerator whose enum type is T or
  541. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  542. if (EnumConstantDecl *D
  543. = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  544. return cast<EnumDecl>(D->getDeclContext());
  545. }
  546. return nullptr;
  547. }
  548. // - it is a comma expression whose RHS is an enumerator-like
  549. // expression of type T or
  550. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  551. if (BO->getOpcode() == BO_Comma)
  552. return findEnumForBlockReturn(BO->getRHS());
  553. return nullptr;
  554. }
  555. // - it is a statement-expression whose value expression is an
  556. // enumerator-like expression of type T or
  557. if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  558. if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
  559. return findEnumForBlockReturn(last);
  560. return nullptr;
  561. }
  562. // - it is a ternary conditional operator (not the GNU ?:
  563. // extension) whose second and third operands are
  564. // enumerator-like expressions of type T or
  565. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  566. if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
  567. if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
  568. return ED;
  569. return nullptr;
  570. }
  571. // (implicitly:)
  572. // - it is an implicit integral conversion applied to an
  573. // enumerator-like expression of type T or
  574. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  575. // We can sometimes see integral conversions in valid
  576. // enumerator-like expressions.
  577. if (ICE->getCastKind() == CK_IntegralCast)
  578. return findEnumForBlockReturn(ICE->getSubExpr());
  579. // Otherwise, just rely on the type.
  580. }
  581. // - it is an expression of that formal enum type.
  582. if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
  583. return ET->getDecl();
  584. }
  585. // Otherwise, nope.
  586. return nullptr;
  587. }
  588. /// Attempt to find a type T for which the returned expression of the
  589. /// given statement is an enumerator-like expression of that type.
  590. static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
  591. if (Expr *retValue = ret->getRetValue())
  592. return findEnumForBlockReturn(retValue);
  593. return nullptr;
  594. }
  595. /// Attempt to find a common type T for which all of the returned
  596. /// expressions in a block are enumerator-like expressions of that
  597. /// type.
  598. static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
  599. ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
  600. // Try to find one for the first return.
  601. EnumDecl *ED = findEnumForBlockReturn(*i);
  602. if (!ED) return nullptr;
  603. // Check that the rest of the returns have the same enum.
  604. for (++i; i != e; ++i) {
  605. if (findEnumForBlockReturn(*i) != ED)
  606. return nullptr;
  607. }
  608. // Never infer an anonymous enum type.
  609. if (!ED->hasNameForLinkage()) return nullptr;
  610. return ED;
  611. }
  612. /// Adjust the given return statements so that they formally return
  613. /// the given type. It should require, at most, an IntegralCast.
  614. static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
  615. QualType returnType) {
  616. for (ArrayRef<ReturnStmt*>::iterator
  617. i = returns.begin(), e = returns.end(); i != e; ++i) {
  618. ReturnStmt *ret = *i;
  619. Expr *retValue = ret->getRetValue();
  620. if (S.Context.hasSameType(retValue->getType(), returnType))
  621. continue;
  622. // Right now we only support integral fixup casts.
  623. assert(returnType->isIntegralOrUnscopedEnumerationType());
  624. assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
  625. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
  626. Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
  627. E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
  628. /*base path*/ nullptr, VK_PRValue,
  629. FPOptionsOverride());
  630. if (cleanups) {
  631. cleanups->setSubExpr(E);
  632. } else {
  633. ret->setRetValue(E);
  634. }
  635. }
  636. }
  637. void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
  638. assert(CSI.HasImplicitReturnType);
  639. // If it was ever a placeholder, it had to been deduced to DependentTy.
  640. assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
  641. assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
  642. "lambda expressions use auto deduction in C++14 onwards");
  643. // C++ core issue 975:
  644. // If a lambda-expression does not include a trailing-return-type,
  645. // it is as if the trailing-return-type denotes the following type:
  646. // - if there are no return statements in the compound-statement,
  647. // or all return statements return either an expression of type
  648. // void or no expression or braced-init-list, the type void;
  649. // - otherwise, if all return statements return an expression
  650. // and the types of the returned expressions after
  651. // lvalue-to-rvalue conversion (4.1 [conv.lval]),
  652. // array-to-pointer conversion (4.2 [conv.array]), and
  653. // function-to-pointer conversion (4.3 [conv.func]) are the
  654. // same, that common type;
  655. // - otherwise, the program is ill-formed.
  656. //
  657. // C++ core issue 1048 additionally removes top-level cv-qualifiers
  658. // from the types of returned expressions to match the C++14 auto
  659. // deduction rules.
  660. //
  661. // In addition, in blocks in non-C++ modes, if all of the return
  662. // statements are enumerator-like expressions of some type T, where
  663. // T has a name for linkage, then we infer the return type of the
  664. // block to be that type.
  665. // First case: no return statements, implicit void return type.
  666. ASTContext &Ctx = getASTContext();
  667. if (CSI.Returns.empty()) {
  668. // It's possible there were simply no /valid/ return statements.
  669. // In this case, the first one we found may have at least given us a type.
  670. if (CSI.ReturnType.isNull())
  671. CSI.ReturnType = Ctx.VoidTy;
  672. return;
  673. }
  674. // Second case: at least one return statement has dependent type.
  675. // Delay type checking until instantiation.
  676. assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
  677. if (CSI.ReturnType->isDependentType())
  678. return;
  679. // Try to apply the enum-fuzz rule.
  680. if (!getLangOpts().CPlusPlus) {
  681. assert(isa<BlockScopeInfo>(CSI));
  682. const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
  683. if (ED) {
  684. CSI.ReturnType = Context.getTypeDeclType(ED);
  685. adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
  686. return;
  687. }
  688. }
  689. // Third case: only one return statement. Don't bother doing extra work!
  690. if (CSI.Returns.size() == 1)
  691. return;
  692. // General case: many return statements.
  693. // Check that they all have compatible return types.
  694. // We require the return types to strictly match here.
  695. // Note that we've already done the required promotions as part of
  696. // processing the return statement.
  697. for (const ReturnStmt *RS : CSI.Returns) {
  698. const Expr *RetE = RS->getRetValue();
  699. QualType ReturnType =
  700. (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
  701. if (Context.getCanonicalFunctionResultType(ReturnType) ==
  702. Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
  703. // Use the return type with the strictest possible nullability annotation.
  704. auto RetTyNullability = ReturnType->getNullability();
  705. auto BlockNullability = CSI.ReturnType->getNullability();
  706. if (BlockNullability &&
  707. (!RetTyNullability ||
  708. hasWeakerNullability(*RetTyNullability, *BlockNullability)))
  709. CSI.ReturnType = ReturnType;
  710. continue;
  711. }
  712. // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
  713. // TODO: It's possible that the *first* return is the divergent one.
  714. Diag(RS->getBeginLoc(),
  715. diag::err_typecheck_missing_return_type_incompatible)
  716. << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
  717. // Continue iterating so that we keep emitting diagnostics.
  718. }
  719. }
  720. QualType Sema::buildLambdaInitCaptureInitialization(
  721. SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
  722. std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
  723. bool IsDirectInit, Expr *&Init) {
  724. // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
  725. // deduce against.
  726. QualType DeductType = Context.getAutoDeductType();
  727. TypeLocBuilder TLB;
  728. AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
  729. TL.setNameLoc(Loc);
  730. if (ByRef) {
  731. DeductType = BuildReferenceType(DeductType, true, Loc, Id);
  732. assert(!DeductType.isNull() && "can't build reference to auto");
  733. TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
  734. }
  735. if (EllipsisLoc.isValid()) {
  736. if (Init->containsUnexpandedParameterPack()) {
  737. Diag(EllipsisLoc, getLangOpts().CPlusPlus20
  738. ? diag::warn_cxx17_compat_init_capture_pack
  739. : diag::ext_init_capture_pack);
  740. DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
  741. /*ExpectPackInType=*/false);
  742. TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
  743. } else {
  744. // Just ignore the ellipsis for now and form a non-pack variable. We'll
  745. // diagnose this later when we try to capture it.
  746. }
  747. }
  748. TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
  749. // Deduce the type of the init capture.
  750. QualType DeducedType = deduceVarTypeFromInitializer(
  751. /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
  752. SourceRange(Loc, Loc), IsDirectInit, Init);
  753. if (DeducedType.isNull())
  754. return QualType();
  755. // Are we a non-list direct initialization?
  756. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  757. // Perform initialization analysis and ensure any implicit conversions
  758. // (such as lvalue-to-rvalue) are enforced.
  759. InitializedEntity Entity =
  760. InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
  761. InitializationKind Kind =
  762. IsDirectInit
  763. ? (CXXDirectInit ? InitializationKind::CreateDirect(
  764. Loc, Init->getBeginLoc(), Init->getEndLoc())
  765. : InitializationKind::CreateDirectList(Loc))
  766. : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
  767. MultiExprArg Args = Init;
  768. if (CXXDirectInit)
  769. Args =
  770. MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
  771. QualType DclT;
  772. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  773. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  774. if (Result.isInvalid())
  775. return QualType();
  776. Init = Result.getAs<Expr>();
  777. return DeducedType;
  778. }
  779. VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
  780. QualType InitCaptureType,
  781. SourceLocation EllipsisLoc,
  782. IdentifierInfo *Id,
  783. unsigned InitStyle, Expr *Init) {
  784. // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
  785. // rather than reconstructing it here.
  786. TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
  787. if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
  788. PETL.setEllipsisLoc(EllipsisLoc);
  789. // Create a dummy variable representing the init-capture. This is not actually
  790. // used as a variable, and only exists as a way to name and refer to the
  791. // init-capture.
  792. // FIXME: Pass in separate source locations for '&' and identifier.
  793. VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
  794. Loc, Id, InitCaptureType, TSI, SC_Auto);
  795. NewVD->setInitCapture(true);
  796. NewVD->setReferenced(true);
  797. // FIXME: Pass in a VarDecl::InitializationStyle.
  798. NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
  799. NewVD->markUsed(Context);
  800. NewVD->setInit(Init);
  801. if (NewVD->isParameterPack())
  802. getCurLambda()->LocalPacks.push_back(NewVD);
  803. return NewVD;
  804. }
  805. void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var,
  806. bool isReferenceType) {
  807. assert(Var->isInitCapture() && "init capture flag should be set");
  808. LSI->addCapture(Var, /*isBlock*/ false, isReferenceType,
  809. /*isNested*/ false, Var->getLocation(), SourceLocation(),
  810. Var->getType(), /*Invalid*/ false);
  811. }
  812. void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
  813. Declarator &ParamInfo,
  814. Scope *CurScope) {
  815. LambdaScopeInfo *const LSI = getCurLambda();
  816. assert(LSI && "LambdaScopeInfo should be on stack!");
  817. // Determine if we're within a context where we know that the lambda will
  818. // be dependent, because there are template parameters in scope.
  819. CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
  820. CXXRecordDecl::LDK_Unknown;
  821. if (LSI->NumExplicitTemplateParams > 0) {
  822. auto *TemplateParamScope = CurScope->getTemplateParamParent();
  823. assert(TemplateParamScope &&
  824. "Lambda with explicit template param list should establish a "
  825. "template param scope");
  826. assert(TemplateParamScope->getParent());
  827. if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
  828. LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
  829. } else if (CurScope->getTemplateParamParent() != nullptr) {
  830. LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
  831. }
  832. // Determine the signature of the call operator.
  833. TypeSourceInfo *MethodTyInfo;
  834. bool ExplicitParams = true;
  835. bool ExplicitResultType = true;
  836. bool ContainsUnexpandedParameterPack = false;
  837. SourceLocation EndLoc;
  838. SmallVector<ParmVarDecl *, 8> Params;
  839. assert(
  840. (ParamInfo.getDeclSpec().getStorageClassSpec() ==
  841. DeclSpec::SCS_unspecified ||
  842. ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&
  843. "Unexpected storage specifier");
  844. bool IsLambdaStatic =
  845. ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
  846. if (ParamInfo.getNumTypeObjects() == 0) {
  847. // C++11 [expr.prim.lambda]p4:
  848. // If a lambda-expression does not include a lambda-declarator, it is as
  849. // if the lambda-declarator were ().
  850. FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
  851. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  852. EPI.HasTrailingReturn = true;
  853. EPI.TypeQuals.addConst();
  854. LangAS AS = getDefaultCXXMethodAddrSpace();
  855. if (AS != LangAS::Default)
  856. EPI.TypeQuals.addAddressSpace(AS);
  857. // C++1y [expr.prim.lambda]:
  858. // The lambda return type is 'auto', which is replaced by the
  859. // trailing-return type if provided and/or deduced from 'return'
  860. // statements
  861. // We don't do this before C++1y, because we don't support deduced return
  862. // types there.
  863. QualType DefaultTypeForNoTrailingReturn =
  864. getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
  865. : Context.DependentTy;
  866. QualType MethodTy = Context.getFunctionType(DefaultTypeForNoTrailingReturn,
  867. std::nullopt, EPI);
  868. MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
  869. ExplicitParams = false;
  870. ExplicitResultType = false;
  871. EndLoc = Intro.Range.getEnd();
  872. } else {
  873. assert(ParamInfo.isFunctionDeclarator() &&
  874. "lambda-declarator is a function");
  875. DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
  876. // C++11 [expr.prim.lambda]p5:
  877. // This function call operator is declared const (9.3.1) if and only if
  878. // the lambda-expression's parameter-declaration-clause is not followed
  879. // by mutable. It is neither virtual nor declared volatile. [...]
  880. if (!FTI.hasMutableQualifier() && !IsLambdaStatic) {
  881. FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
  882. SourceLocation());
  883. }
  884. MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
  885. assert(MethodTyInfo && "no type from lambda-declarator");
  886. EndLoc = ParamInfo.getSourceRange().getEnd();
  887. ExplicitResultType = FTI.hasTrailingReturnType();
  888. if (ExplicitResultType && getLangOpts().HLSL) {
  889. QualType RetTy = FTI.getTrailingReturnType().get();
  890. if (!RetTy.isNull()) {
  891. // HLSL does not support specifying an address space on a lambda return
  892. // type.
  893. LangAS AddressSpace = RetTy.getAddressSpace();
  894. if (AddressSpace != LangAS::Default)
  895. Diag(FTI.getTrailingReturnTypeLoc(),
  896. diag::err_return_value_with_address_space);
  897. }
  898. }
  899. if (FTIHasNonVoidParameters(FTI)) {
  900. Params.reserve(FTI.NumParams);
  901. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
  902. Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
  903. }
  904. // Check for unexpanded parameter packs in the method type.
  905. if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
  906. DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
  907. UPPC_DeclarationType);
  908. }
  909. CXXRecordDecl *Class = createLambdaClosureType(
  910. Intro.Range, MethodTyInfo, LambdaDependencyKind, Intro.Default);
  911. CXXMethodDecl *Method =
  912. startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
  913. ParamInfo.getDeclSpec().getConstexprSpecifier(),
  914. IsLambdaStatic ? SC_Static : SC_None,
  915. ParamInfo.getTrailingRequiresClause());
  916. if (ExplicitParams)
  917. CheckCXXDefaultArguments(Method);
  918. // This represents the function body for the lambda function, check if we
  919. // have to apply optnone due to a pragma.
  920. AddRangeBasedOptnone(Method);
  921. // code_seg attribute on lambda apply to the method.
  922. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  923. Method->addAttr(A);
  924. // Attributes on the lambda apply to the method.
  925. ProcessDeclAttributes(CurScope, Method, ParamInfo);
  926. // CUDA lambdas get implicit host and device attributes.
  927. if (getLangOpts().CUDA)
  928. CUDASetLambdaAttrs(Method);
  929. // OpenMP lambdas might get assumumption attributes.
  930. if (LangOpts.OpenMP)
  931. ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
  932. // Number the lambda for linkage purposes if necessary.
  933. handleLambdaNumbering(Class, Method);
  934. // Introduce the function call operator as the current declaration context.
  935. PushDeclContext(CurScope, Method);
  936. // Build the lambda scope.
  937. buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
  938. ExplicitParams, ExplicitResultType, !Method->isConst());
  939. // C++11 [expr.prim.lambda]p9:
  940. // A lambda-expression whose smallest enclosing scope is a block scope is a
  941. // local lambda expression; any other lambda expression shall not have a
  942. // capture-default or simple-capture in its lambda-introducer.
  943. //
  944. // For simple-captures, this is covered by the check below that any named
  945. // entity is a variable that can be captured.
  946. //
  947. // For DR1632, we also allow a capture-default in any context where we can
  948. // odr-use 'this' (in particular, in a default initializer for a non-static
  949. // data member).
  950. if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
  951. (getCurrentThisType().isNull() ||
  952. CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
  953. /*BuildAndDiagnose*/false)))
  954. Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
  955. // Distinct capture names, for diagnostics.
  956. llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
  957. // Handle explicit captures.
  958. SourceLocation PrevCaptureLoc
  959. = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
  960. for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
  961. PrevCaptureLoc = C->Loc, ++C) {
  962. if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
  963. if (C->Kind == LCK_StarThis)
  964. Diag(C->Loc, !getLangOpts().CPlusPlus17
  965. ? diag::ext_star_this_lambda_capture_cxx17
  966. : diag::warn_cxx14_compat_star_this_lambda_capture);
  967. // C++11 [expr.prim.lambda]p8:
  968. // An identifier or this shall not appear more than once in a
  969. // lambda-capture.
  970. if (LSI->isCXXThisCaptured()) {
  971. Diag(C->Loc, diag::err_capture_more_than_once)
  972. << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
  973. << FixItHint::CreateRemoval(
  974. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  975. continue;
  976. }
  977. // C++2a [expr.prim.lambda]p8:
  978. // If a lambda-capture includes a capture-default that is =,
  979. // each simple-capture of that lambda-capture shall be of the form
  980. // "&identifier", "this", or "* this". [ Note: The form [&,this] is
  981. // redundant but accepted for compatibility with ISO C++14. --end note ]
  982. if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
  983. Diag(C->Loc, !getLangOpts().CPlusPlus20
  984. ? diag::ext_equals_this_lambda_capture_cxx20
  985. : diag::warn_cxx17_compat_equals_this_lambda_capture);
  986. // C++11 [expr.prim.lambda]p12:
  987. // If this is captured by a local lambda expression, its nearest
  988. // enclosing function shall be a non-static member function.
  989. QualType ThisCaptureType = getCurrentThisType();
  990. if (ThisCaptureType.isNull()) {
  991. Diag(C->Loc, diag::err_this_capture) << true;
  992. continue;
  993. }
  994. CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
  995. /*FunctionScopeIndexToStopAtPtr*/ nullptr,
  996. C->Kind == LCK_StarThis);
  997. if (!LSI->Captures.empty())
  998. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  999. continue;
  1000. }
  1001. assert(C->Id && "missing identifier for capture");
  1002. if (C->Init.isInvalid())
  1003. continue;
  1004. ValueDecl *Var = nullptr;
  1005. if (C->Init.isUsable()) {
  1006. Diag(C->Loc, getLangOpts().CPlusPlus14
  1007. ? diag::warn_cxx11_compat_init_capture
  1008. : diag::ext_init_capture);
  1009. // If the initializer expression is usable, but the InitCaptureType
  1010. // is not, then an error has occurred - so ignore the capture for now.
  1011. // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
  1012. // FIXME: we should create the init capture variable and mark it invalid
  1013. // in this case.
  1014. if (C->InitCaptureType.get().isNull())
  1015. continue;
  1016. if (C->Init.get()->containsUnexpandedParameterPack() &&
  1017. !C->InitCaptureType.get()->getAs<PackExpansionType>())
  1018. DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
  1019. unsigned InitStyle;
  1020. switch (C->InitKind) {
  1021. case LambdaCaptureInitKind::NoInit:
  1022. llvm_unreachable("not an init-capture?");
  1023. case LambdaCaptureInitKind::CopyInit:
  1024. InitStyle = VarDecl::CInit;
  1025. break;
  1026. case LambdaCaptureInitKind::DirectInit:
  1027. InitStyle = VarDecl::CallInit;
  1028. break;
  1029. case LambdaCaptureInitKind::ListInit:
  1030. InitStyle = VarDecl::ListInit;
  1031. break;
  1032. }
  1033. Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
  1034. C->EllipsisLoc, C->Id, InitStyle,
  1035. C->Init.get());
  1036. // C++1y [expr.prim.lambda]p11:
  1037. // An init-capture behaves as if it declares and explicitly
  1038. // captures a variable [...] whose declarative region is the
  1039. // lambda-expression's compound-statement
  1040. if (Var)
  1041. PushOnScopeChains(Var, CurScope, false);
  1042. } else {
  1043. assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
  1044. "init capture has valid but null init?");
  1045. // C++11 [expr.prim.lambda]p8:
  1046. // If a lambda-capture includes a capture-default that is &, the
  1047. // identifiers in the lambda-capture shall not be preceded by &.
  1048. // If a lambda-capture includes a capture-default that is =, [...]
  1049. // each identifier it contains shall be preceded by &.
  1050. if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
  1051. Diag(C->Loc, diag::err_reference_capture_with_reference_default)
  1052. << FixItHint::CreateRemoval(
  1053. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1054. continue;
  1055. } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
  1056. Diag(C->Loc, diag::err_copy_capture_with_copy_default)
  1057. << FixItHint::CreateRemoval(
  1058. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1059. continue;
  1060. }
  1061. // C++11 [expr.prim.lambda]p10:
  1062. // The identifiers in a capture-list are looked up using the usual
  1063. // rules for unqualified name lookup (3.4.1)
  1064. DeclarationNameInfo Name(C->Id, C->Loc);
  1065. LookupResult R(*this, Name, LookupOrdinaryName);
  1066. LookupName(R, CurScope);
  1067. if (R.isAmbiguous())
  1068. continue;
  1069. if (R.empty()) {
  1070. // FIXME: Disable corrections that would add qualification?
  1071. CXXScopeSpec ScopeSpec;
  1072. DeclFilterCCC<VarDecl> Validator{};
  1073. if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
  1074. continue;
  1075. }
  1076. if (auto *BD = R.getAsSingle<BindingDecl>())
  1077. Var = BD;
  1078. else
  1079. Var = R.getAsSingle<VarDecl>();
  1080. if (Var && DiagnoseUseOfDecl(Var, C->Loc))
  1081. continue;
  1082. }
  1083. // C++11 [expr.prim.lambda]p8:
  1084. // An identifier or this shall not appear more than once in a
  1085. // lambda-capture.
  1086. if (!CaptureNames.insert(C->Id).second) {
  1087. if (Var && LSI->isCaptured(Var)) {
  1088. Diag(C->Loc, diag::err_capture_more_than_once)
  1089. << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
  1090. << FixItHint::CreateRemoval(
  1091. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1092. } else
  1093. // Previous capture captured something different (one or both was
  1094. // an init-cpature): no fixit.
  1095. Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
  1096. continue;
  1097. }
  1098. // C++11 [expr.prim.lambda]p10:
  1099. // [...] each such lookup shall find a variable with automatic storage
  1100. // duration declared in the reaching scope of the local lambda expression.
  1101. // Note that the 'reaching scope' check happens in tryCaptureVariable().
  1102. if (!Var) {
  1103. Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
  1104. continue;
  1105. }
  1106. // Ignore invalid decls; they'll just confuse the code later.
  1107. if (Var->isInvalidDecl())
  1108. continue;
  1109. VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
  1110. if (!Underlying->hasLocalStorage()) {
  1111. Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
  1112. Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
  1113. continue;
  1114. }
  1115. // C++11 [expr.prim.lambda]p23:
  1116. // A capture followed by an ellipsis is a pack expansion (14.5.3).
  1117. SourceLocation EllipsisLoc;
  1118. if (C->EllipsisLoc.isValid()) {
  1119. if (Var->isParameterPack()) {
  1120. EllipsisLoc = C->EllipsisLoc;
  1121. } else {
  1122. Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1123. << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
  1124. : SourceRange(C->Loc));
  1125. // Just ignore the ellipsis.
  1126. }
  1127. } else if (Var->isParameterPack()) {
  1128. ContainsUnexpandedParameterPack = true;
  1129. }
  1130. if (C->Init.isUsable()) {
  1131. addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
  1132. } else {
  1133. TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
  1134. TryCapture_ExplicitByVal;
  1135. tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
  1136. }
  1137. if (!LSI->Captures.empty())
  1138. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  1139. }
  1140. finishLambdaExplicitCaptures(LSI);
  1141. LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
  1142. // Add lambda parameters into scope.
  1143. addLambdaParameters(Intro.Captures, Method, CurScope);
  1144. // Enter a new evaluation context to insulate the lambda from any
  1145. // cleanups from the enclosing full-expression.
  1146. PushExpressionEvaluationContext(
  1147. LSI->CallOperator->isConsteval()
  1148. ? ExpressionEvaluationContext::ImmediateFunctionContext
  1149. : ExpressionEvaluationContext::PotentiallyEvaluated);
  1150. }
  1151. void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
  1152. bool IsInstantiation) {
  1153. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
  1154. // Leave the expression-evaluation context.
  1155. DiscardCleanupsInEvaluationContext();
  1156. PopExpressionEvaluationContext();
  1157. // Leave the context of the lambda.
  1158. if (!IsInstantiation)
  1159. PopDeclContext();
  1160. // Finalize the lambda.
  1161. CXXRecordDecl *Class = LSI->Lambda;
  1162. Class->setInvalidDecl();
  1163. SmallVector<Decl*, 4> Fields(Class->fields());
  1164. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1165. SourceLocation(), ParsedAttributesView());
  1166. CheckCompletedCXXClass(nullptr, Class);
  1167. PopFunctionScopeInfo();
  1168. }
  1169. template <typename Func>
  1170. static void repeatForLambdaConversionFunctionCallingConvs(
  1171. Sema &S, const FunctionProtoType &CallOpProto, Func F) {
  1172. CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
  1173. CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
  1174. CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
  1175. CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
  1176. CallingConv CallOpCC = CallOpProto.getCallConv();
  1177. /// Implement emitting a version of the operator for many of the calling
  1178. /// conventions for MSVC, as described here:
  1179. /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
  1180. /// Experimentally, we determined that cdecl, stdcall, fastcall, and
  1181. /// vectorcall are generated by MSVC when it is supported by the target.
  1182. /// Additionally, we are ensuring that the default-free/default-member and
  1183. /// call-operator calling convention are generated as well.
  1184. /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
  1185. /// 'member default', despite MSVC not doing so. We do this in order to ensure
  1186. /// that someone who intentionally places 'thiscall' on the lambda call
  1187. /// operator will still get that overload, since we don't have the a way of
  1188. /// detecting the attribute by the time we get here.
  1189. if (S.getLangOpts().MSVCCompat) {
  1190. CallingConv Convs[] = {
  1191. CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
  1192. DefaultFree, DefaultMember, CallOpCC};
  1193. llvm::sort(Convs);
  1194. llvm::iterator_range<CallingConv *> Range(
  1195. std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
  1196. const TargetInfo &TI = S.getASTContext().getTargetInfo();
  1197. for (CallingConv C : Range) {
  1198. if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
  1199. F(C);
  1200. }
  1201. return;
  1202. }
  1203. if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
  1204. F(DefaultFree);
  1205. F(DefaultMember);
  1206. } else {
  1207. F(CallOpCC);
  1208. }
  1209. }
  1210. // Returns the 'standard' calling convention to be used for the lambda
  1211. // conversion function, that is, the 'free' function calling convention unless
  1212. // it is overridden by a non-default calling convention attribute.
  1213. static CallingConv
  1214. getLambdaConversionFunctionCallConv(Sema &S,
  1215. const FunctionProtoType *CallOpProto) {
  1216. CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
  1217. CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
  1218. CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
  1219. CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
  1220. CallingConv CallOpCC = CallOpProto->getCallConv();
  1221. // If the call-operator hasn't been changed, return both the 'free' and
  1222. // 'member' function calling convention.
  1223. if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
  1224. return DefaultFree;
  1225. return CallOpCC;
  1226. }
  1227. QualType Sema::getLambdaConversionFunctionResultType(
  1228. const FunctionProtoType *CallOpProto, CallingConv CC) {
  1229. const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
  1230. CallOpProto->getExtProtoInfo();
  1231. FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
  1232. InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
  1233. InvokerExtInfo.TypeQuals = Qualifiers();
  1234. assert(InvokerExtInfo.RefQualifier == RQ_None &&
  1235. "Lambda's call operator should not have a reference qualifier");
  1236. return Context.getFunctionType(CallOpProto->getReturnType(),
  1237. CallOpProto->getParamTypes(), InvokerExtInfo);
  1238. }
  1239. /// Add a lambda's conversion to function pointer, as described in
  1240. /// C++11 [expr.prim.lambda]p6.
  1241. static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
  1242. CXXRecordDecl *Class,
  1243. CXXMethodDecl *CallOperator,
  1244. QualType InvokerFunctionTy) {
  1245. // This conversion is explicitly disabled if the lambda's function has
  1246. // pass_object_size attributes on any of its parameters.
  1247. auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
  1248. return P->hasAttr<PassObjectSizeAttr>();
  1249. };
  1250. if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
  1251. return;
  1252. // Add the conversion to function pointer.
  1253. QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
  1254. // Create the type of the conversion function.
  1255. FunctionProtoType::ExtProtoInfo ConvExtInfo(
  1256. S.Context.getDefaultCallingConvention(
  1257. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1258. // The conversion function is always const and noexcept.
  1259. ConvExtInfo.TypeQuals = Qualifiers();
  1260. ConvExtInfo.TypeQuals.addConst();
  1261. ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
  1262. QualType ConvTy =
  1263. S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
  1264. SourceLocation Loc = IntroducerRange.getBegin();
  1265. DeclarationName ConversionName
  1266. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1267. S.Context.getCanonicalType(PtrToFunctionTy));
  1268. // Construct a TypeSourceInfo for the conversion function, and wire
  1269. // all the parameters appropriately for the FunctionProtoTypeLoc
  1270. // so that everything works during transformation/instantiation of
  1271. // generic lambdas.
  1272. // The main reason for wiring up the parameters of the conversion
  1273. // function with that of the call operator is so that constructs
  1274. // like the following work:
  1275. // auto L = [](auto b) { <-- 1
  1276. // return [](auto a) -> decltype(a) { <-- 2
  1277. // return a;
  1278. // };
  1279. // };
  1280. // int (*fp)(int) = L(5);
  1281. // Because the trailing return type can contain DeclRefExprs that refer
  1282. // to the original call operator's variables, we hijack the call
  1283. // operators ParmVarDecls below.
  1284. TypeSourceInfo *ConvNamePtrToFunctionTSI =
  1285. S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
  1286. DeclarationNameLoc ConvNameLoc =
  1287. DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
  1288. // The conversion function is a conversion to a pointer-to-function.
  1289. TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
  1290. FunctionProtoTypeLoc ConvTL =
  1291. ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  1292. // Get the result of the conversion function which is a pointer-to-function.
  1293. PointerTypeLoc PtrToFunctionTL =
  1294. ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
  1295. // Do the same for the TypeSourceInfo that is used to name the conversion
  1296. // operator.
  1297. PointerTypeLoc ConvNamePtrToFunctionTL =
  1298. ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
  1299. // Get the underlying function types that the conversion function will
  1300. // be converting to (should match the type of the call operator).
  1301. FunctionProtoTypeLoc CallOpConvTL =
  1302. PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1303. FunctionProtoTypeLoc CallOpConvNameTL =
  1304. ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1305. // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
  1306. // These parameter's are essentially used to transform the name and
  1307. // the type of the conversion operator. By using the same parameters
  1308. // as the call operator's we don't have to fix any back references that
  1309. // the trailing return type of the call operator's uses (such as
  1310. // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
  1311. // - we can simply use the return type of the call operator, and
  1312. // everything should work.
  1313. SmallVector<ParmVarDecl *, 4> InvokerParams;
  1314. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1315. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1316. InvokerParams.push_back(ParmVarDecl::Create(
  1317. S.Context,
  1318. // Temporarily add to the TU. This is set to the invoker below.
  1319. S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
  1320. From->getLocation(), From->getIdentifier(), From->getType(),
  1321. From->getTypeSourceInfo(), From->getStorageClass(),
  1322. /*DefArg=*/nullptr));
  1323. CallOpConvTL.setParam(I, From);
  1324. CallOpConvNameTL.setParam(I, From);
  1325. }
  1326. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1327. S.Context, Class, Loc,
  1328. DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
  1329. S.getCurFPFeatures().isFPConstrained(),
  1330. /*isInline=*/true, ExplicitSpecifier(),
  1331. S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
  1332. : ConstexprSpecKind::Unspecified,
  1333. CallOperator->getBody()->getEndLoc());
  1334. Conversion->setAccess(AS_public);
  1335. Conversion->setImplicit(true);
  1336. if (Class->isGenericLambda()) {
  1337. // Create a template version of the conversion operator, using the template
  1338. // parameter list of the function call operator.
  1339. FunctionTemplateDecl *TemplateCallOperator =
  1340. CallOperator->getDescribedFunctionTemplate();
  1341. FunctionTemplateDecl *ConversionTemplate =
  1342. FunctionTemplateDecl::Create(S.Context, Class,
  1343. Loc, ConversionName,
  1344. TemplateCallOperator->getTemplateParameters(),
  1345. Conversion);
  1346. ConversionTemplate->setAccess(AS_public);
  1347. ConversionTemplate->setImplicit(true);
  1348. Conversion->setDescribedFunctionTemplate(ConversionTemplate);
  1349. Class->addDecl(ConversionTemplate);
  1350. } else
  1351. Class->addDecl(Conversion);
  1352. // If the lambda is not static, we need to add a static member
  1353. // function that will be the result of the conversion with a
  1354. // certain unique ID.
  1355. // When it is static we just return the static call operator instead.
  1356. if (CallOperator->isInstance()) {
  1357. DeclarationName InvokerName =
  1358. &S.Context.Idents.get(getLambdaStaticInvokerName());
  1359. // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
  1360. // we should get a prebuilt TrivialTypeSourceInfo from Context
  1361. // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
  1362. // then rewire the parameters accordingly, by hoisting up the InvokeParams
  1363. // loop below and then use its Params to set Invoke->setParams(...) below.
  1364. // This would avoid the 'const' qualifier of the calloperator from
  1365. // contaminating the type of the invoker, which is currently adjusted
  1366. // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
  1367. // trailing return type of the invoker would require a visitor to rebuild
  1368. // the trailing return type and adjusting all back DeclRefExpr's to refer
  1369. // to the new static invoker parameters - not the call operator's.
  1370. CXXMethodDecl *Invoke = CXXMethodDecl::Create(
  1371. S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
  1372. InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
  1373. S.getCurFPFeatures().isFPConstrained(),
  1374. /*isInline=*/true, ConstexprSpecKind::Unspecified,
  1375. CallOperator->getBody()->getEndLoc());
  1376. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
  1377. InvokerParams[I]->setOwningFunction(Invoke);
  1378. Invoke->setParams(InvokerParams);
  1379. Invoke->setAccess(AS_private);
  1380. Invoke->setImplicit(true);
  1381. if (Class->isGenericLambda()) {
  1382. FunctionTemplateDecl *TemplateCallOperator =
  1383. CallOperator->getDescribedFunctionTemplate();
  1384. FunctionTemplateDecl *StaticInvokerTemplate =
  1385. FunctionTemplateDecl::Create(
  1386. S.Context, Class, Loc, InvokerName,
  1387. TemplateCallOperator->getTemplateParameters(), Invoke);
  1388. StaticInvokerTemplate->setAccess(AS_private);
  1389. StaticInvokerTemplate->setImplicit(true);
  1390. Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
  1391. Class->addDecl(StaticInvokerTemplate);
  1392. } else
  1393. Class->addDecl(Invoke);
  1394. }
  1395. }
  1396. /// Add a lambda's conversion to function pointers, as described in
  1397. /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
  1398. /// single pointer conversion. In the event that the default calling convention
  1399. /// for free and member functions is different, it will emit both conventions.
  1400. static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
  1401. CXXRecordDecl *Class,
  1402. CXXMethodDecl *CallOperator) {
  1403. const FunctionProtoType *CallOpProto =
  1404. CallOperator->getType()->castAs<FunctionProtoType>();
  1405. repeatForLambdaConversionFunctionCallingConvs(
  1406. S, *CallOpProto, [&](CallingConv CC) {
  1407. QualType InvokerFunctionTy =
  1408. S.getLambdaConversionFunctionResultType(CallOpProto, CC);
  1409. addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
  1410. InvokerFunctionTy);
  1411. });
  1412. }
  1413. /// Add a lambda's conversion to block pointer.
  1414. static void addBlockPointerConversion(Sema &S,
  1415. SourceRange IntroducerRange,
  1416. CXXRecordDecl *Class,
  1417. CXXMethodDecl *CallOperator) {
  1418. const FunctionProtoType *CallOpProto =
  1419. CallOperator->getType()->castAs<FunctionProtoType>();
  1420. QualType FunctionTy = S.getLambdaConversionFunctionResultType(
  1421. CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
  1422. QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
  1423. FunctionProtoType::ExtProtoInfo ConversionEPI(
  1424. S.Context.getDefaultCallingConvention(
  1425. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1426. ConversionEPI.TypeQuals = Qualifiers();
  1427. ConversionEPI.TypeQuals.addConst();
  1428. QualType ConvTy =
  1429. S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
  1430. SourceLocation Loc = IntroducerRange.getBegin();
  1431. DeclarationName Name
  1432. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1433. S.Context.getCanonicalType(BlockPtrTy));
  1434. DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
  1435. S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
  1436. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1437. S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
  1438. S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
  1439. S.getCurFPFeatures().isFPConstrained(),
  1440. /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
  1441. CallOperator->getBody()->getEndLoc());
  1442. Conversion->setAccess(AS_public);
  1443. Conversion->setImplicit(true);
  1444. Class->addDecl(Conversion);
  1445. }
  1446. ExprResult Sema::BuildCaptureInit(const Capture &Cap,
  1447. SourceLocation ImplicitCaptureLoc,
  1448. bool IsOpenMPMapping) {
  1449. // VLA captures don't have a stored initialization expression.
  1450. if (Cap.isVLATypeCapture())
  1451. return ExprResult();
  1452. // An init-capture is initialized directly from its stored initializer.
  1453. if (Cap.isInitCapture())
  1454. return cast<VarDecl>(Cap.getVariable())->getInit();
  1455. // For anything else, build an initialization expression. For an implicit
  1456. // capture, the capture notionally happens at the capture-default, so use
  1457. // that location here.
  1458. SourceLocation Loc =
  1459. ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
  1460. // C++11 [expr.prim.lambda]p21:
  1461. // When the lambda-expression is evaluated, the entities that
  1462. // are captured by copy are used to direct-initialize each
  1463. // corresponding non-static data member of the resulting closure
  1464. // object. (For array members, the array elements are
  1465. // direct-initialized in increasing subscript order.) These
  1466. // initializations are performed in the (unspecified) order in
  1467. // which the non-static data members are declared.
  1468. // C++ [expr.prim.lambda]p12:
  1469. // An entity captured by a lambda-expression is odr-used (3.2) in
  1470. // the scope containing the lambda-expression.
  1471. ExprResult Init;
  1472. IdentifierInfo *Name = nullptr;
  1473. if (Cap.isThisCapture()) {
  1474. QualType ThisTy = getCurrentThisType();
  1475. Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
  1476. if (Cap.isCopyCapture())
  1477. Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  1478. else
  1479. Init = This;
  1480. } else {
  1481. assert(Cap.isVariableCapture() && "unknown kind of capture");
  1482. ValueDecl *Var = Cap.getVariable();
  1483. Name = Var->getIdentifier();
  1484. Init = BuildDeclarationNameExpr(
  1485. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  1486. }
  1487. // In OpenMP, the capture kind doesn't actually describe how to capture:
  1488. // variables are "mapped" onto the device in a process that does not formally
  1489. // make a copy, even for a "copy capture".
  1490. if (IsOpenMPMapping)
  1491. return Init;
  1492. if (Init.isInvalid())
  1493. return ExprError();
  1494. Expr *InitExpr = Init.get();
  1495. InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
  1496. Name, Cap.getCaptureType(), Loc);
  1497. InitializationKind InitKind =
  1498. InitializationKind::CreateDirect(Loc, Loc, Loc);
  1499. InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
  1500. return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
  1501. }
  1502. ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
  1503. Scope *CurScope) {
  1504. LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
  1505. ActOnFinishFunctionBody(LSI.CallOperator, Body);
  1506. return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
  1507. }
  1508. static LambdaCaptureDefault
  1509. mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
  1510. switch (ICS) {
  1511. case CapturingScopeInfo::ImpCap_None:
  1512. return LCD_None;
  1513. case CapturingScopeInfo::ImpCap_LambdaByval:
  1514. return LCD_ByCopy;
  1515. case CapturingScopeInfo::ImpCap_CapturedRegion:
  1516. case CapturingScopeInfo::ImpCap_LambdaByref:
  1517. return LCD_ByRef;
  1518. case CapturingScopeInfo::ImpCap_Block:
  1519. llvm_unreachable("block capture in lambda");
  1520. }
  1521. llvm_unreachable("Unknown implicit capture style");
  1522. }
  1523. bool Sema::CaptureHasSideEffects(const Capture &From) {
  1524. if (From.isInitCapture()) {
  1525. Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
  1526. if (Init && Init->HasSideEffects(Context))
  1527. return true;
  1528. }
  1529. if (!From.isCopyCapture())
  1530. return false;
  1531. const QualType T = From.isThisCapture()
  1532. ? getCurrentThisType()->getPointeeType()
  1533. : From.getCaptureType();
  1534. if (T.isVolatileQualified())
  1535. return true;
  1536. const Type *BaseT = T->getBaseElementTypeUnsafe();
  1537. if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
  1538. return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
  1539. !RD->hasTrivialDestructor();
  1540. return false;
  1541. }
  1542. bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
  1543. const Capture &From) {
  1544. if (CaptureHasSideEffects(From))
  1545. return false;
  1546. if (From.isVLATypeCapture())
  1547. return false;
  1548. auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
  1549. if (From.isThisCapture())
  1550. diag << "'this'";
  1551. else
  1552. diag << From.getVariable();
  1553. diag << From.isNonODRUsed();
  1554. diag << FixItHint::CreateRemoval(CaptureRange);
  1555. return true;
  1556. }
  1557. /// Create a field within the lambda class or captured statement record for the
  1558. /// given capture.
  1559. FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
  1560. const sema::Capture &Capture) {
  1561. SourceLocation Loc = Capture.getLocation();
  1562. QualType FieldType = Capture.getCaptureType();
  1563. TypeSourceInfo *TSI = nullptr;
  1564. if (Capture.isVariableCapture()) {
  1565. const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
  1566. if (Var && Var->isInitCapture())
  1567. TSI = Var->getTypeSourceInfo();
  1568. }
  1569. // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
  1570. // appropriate, at least for an implicit capture.
  1571. if (!TSI)
  1572. TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
  1573. // Build the non-static data member.
  1574. FieldDecl *Field =
  1575. FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
  1576. /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
  1577. /*Mutable=*/false, ICIS_NoInit);
  1578. // If the variable being captured has an invalid type, mark the class as
  1579. // invalid as well.
  1580. if (!FieldType->isDependentType()) {
  1581. if (RequireCompleteSizedType(Loc, FieldType,
  1582. diag::err_field_incomplete_or_sizeless)) {
  1583. RD->setInvalidDecl();
  1584. Field->setInvalidDecl();
  1585. } else {
  1586. NamedDecl *Def;
  1587. FieldType->isIncompleteType(&Def);
  1588. if (Def && Def->isInvalidDecl()) {
  1589. RD->setInvalidDecl();
  1590. Field->setInvalidDecl();
  1591. }
  1592. }
  1593. }
  1594. Field->setImplicit(true);
  1595. Field->setAccess(AS_private);
  1596. RD->addDecl(Field);
  1597. if (Capture.isVLATypeCapture())
  1598. Field->setCapturedVLAType(Capture.getCapturedVLAType());
  1599. return Field;
  1600. }
  1601. ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
  1602. LambdaScopeInfo *LSI) {
  1603. // Collect information from the lambda scope.
  1604. SmallVector<LambdaCapture, 4> Captures;
  1605. SmallVector<Expr *, 4> CaptureInits;
  1606. SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
  1607. LambdaCaptureDefault CaptureDefault =
  1608. mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
  1609. CXXRecordDecl *Class;
  1610. CXXMethodDecl *CallOperator;
  1611. SourceRange IntroducerRange;
  1612. bool ExplicitParams;
  1613. bool ExplicitResultType;
  1614. CleanupInfo LambdaCleanup;
  1615. bool ContainsUnexpandedParameterPack;
  1616. bool IsGenericLambda;
  1617. {
  1618. CallOperator = LSI->CallOperator;
  1619. Class = LSI->Lambda;
  1620. IntroducerRange = LSI->IntroducerRange;
  1621. ExplicitParams = LSI->ExplicitParams;
  1622. ExplicitResultType = !LSI->HasImplicitReturnType;
  1623. LambdaCleanup = LSI->Cleanup;
  1624. ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
  1625. IsGenericLambda = Class->isGenericLambda();
  1626. CallOperator->setLexicalDeclContext(Class);
  1627. Decl *TemplateOrNonTemplateCallOperatorDecl =
  1628. CallOperator->getDescribedFunctionTemplate()
  1629. ? CallOperator->getDescribedFunctionTemplate()
  1630. : cast<Decl>(CallOperator);
  1631. // FIXME: Is this really the best choice? Keeping the lexical decl context
  1632. // set as CurContext seems more faithful to the source.
  1633. TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
  1634. PopExpressionEvaluationContext();
  1635. // True if the current capture has a used capture or default before it.
  1636. bool CurHasPreviousCapture = CaptureDefault != LCD_None;
  1637. SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
  1638. CaptureDefaultLoc : IntroducerRange.getBegin();
  1639. for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
  1640. const Capture &From = LSI->Captures[I];
  1641. if (From.isInvalid())
  1642. return ExprError();
  1643. assert(!From.isBlockCapture() && "Cannot capture __block variables");
  1644. bool IsImplicit = I >= LSI->NumExplicitCaptures;
  1645. SourceLocation ImplicitCaptureLoc =
  1646. IsImplicit ? CaptureDefaultLoc : SourceLocation();
  1647. // Use source ranges of explicit captures for fixits where available.
  1648. SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
  1649. // Warn about unused explicit captures.
  1650. bool IsCaptureUsed = true;
  1651. if (!CurContext->isDependentContext() && !IsImplicit &&
  1652. !From.isODRUsed()) {
  1653. // Initialized captures that are non-ODR used may not be eliminated.
  1654. // FIXME: Where did the IsGenericLambda here come from?
  1655. bool NonODRUsedInitCapture =
  1656. IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
  1657. if (!NonODRUsedInitCapture) {
  1658. bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
  1659. SourceRange FixItRange;
  1660. if (CaptureRange.isValid()) {
  1661. if (!CurHasPreviousCapture && !IsLast) {
  1662. // If there are no captures preceding this capture, remove the
  1663. // following comma.
  1664. FixItRange = SourceRange(CaptureRange.getBegin(),
  1665. getLocForEndOfToken(CaptureRange.getEnd()));
  1666. } else {
  1667. // Otherwise, remove the comma since the last used capture.
  1668. FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
  1669. CaptureRange.getEnd());
  1670. }
  1671. }
  1672. IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
  1673. }
  1674. }
  1675. if (CaptureRange.isValid()) {
  1676. CurHasPreviousCapture |= IsCaptureUsed;
  1677. PrevCaptureLoc = CaptureRange.getEnd();
  1678. }
  1679. // Map the capture to our AST representation.
  1680. LambdaCapture Capture = [&] {
  1681. if (From.isThisCapture()) {
  1682. // Capturing 'this' implicitly with a default of '[=]' is deprecated,
  1683. // because it results in a reference capture. Don't warn prior to
  1684. // C++2a; there's nothing that can be done about it before then.
  1685. if (getLangOpts().CPlusPlus20 && IsImplicit &&
  1686. CaptureDefault == LCD_ByCopy) {
  1687. Diag(From.getLocation(), diag::warn_deprecated_this_capture);
  1688. Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
  1689. << FixItHint::CreateInsertion(
  1690. getLocForEndOfToken(CaptureDefaultLoc), ", this");
  1691. }
  1692. return LambdaCapture(From.getLocation(), IsImplicit,
  1693. From.isCopyCapture() ? LCK_StarThis : LCK_This);
  1694. } else if (From.isVLATypeCapture()) {
  1695. return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
  1696. } else {
  1697. assert(From.isVariableCapture() && "unknown kind of capture");
  1698. ValueDecl *Var = From.getVariable();
  1699. LambdaCaptureKind Kind =
  1700. From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
  1701. return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
  1702. From.getEllipsisLoc());
  1703. }
  1704. }();
  1705. // Form the initializer for the capture field.
  1706. ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
  1707. // FIXME: Skip this capture if the capture is not used, the initializer
  1708. // has no side-effects, the type of the capture is trivial, and the
  1709. // lambda is not externally visible.
  1710. // Add a FieldDecl for the capture and form its initializer.
  1711. BuildCaptureField(Class, From);
  1712. Captures.push_back(Capture);
  1713. CaptureInits.push_back(Init.get());
  1714. if (LangOpts.CUDA)
  1715. CUDACheckLambdaCapture(CallOperator, From);
  1716. }
  1717. Class->setCaptures(Context, Captures);
  1718. // C++11 [expr.prim.lambda]p6:
  1719. // The closure type for a lambda-expression with no lambda-capture
  1720. // has a public non-virtual non-explicit const conversion function
  1721. // to pointer to function having the same parameter and return
  1722. // types as the closure type's function call operator.
  1723. if (Captures.empty() && CaptureDefault == LCD_None)
  1724. addFunctionPointerConversions(*this, IntroducerRange, Class,
  1725. CallOperator);
  1726. // Objective-C++:
  1727. // The closure type for a lambda-expression has a public non-virtual
  1728. // non-explicit const conversion function to a block pointer having the
  1729. // same parameter and return types as the closure type's function call
  1730. // operator.
  1731. // FIXME: Fix generic lambda to block conversions.
  1732. if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
  1733. addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
  1734. // Finalize the lambda class.
  1735. SmallVector<Decl*, 4> Fields(Class->fields());
  1736. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1737. SourceLocation(), ParsedAttributesView());
  1738. CheckCompletedCXXClass(nullptr, Class);
  1739. }
  1740. Cleanup.mergeFrom(LambdaCleanup);
  1741. LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
  1742. CaptureDefault, CaptureDefaultLoc,
  1743. ExplicitParams, ExplicitResultType,
  1744. CaptureInits, EndLoc,
  1745. ContainsUnexpandedParameterPack);
  1746. // If the lambda expression's call operator is not explicitly marked constexpr
  1747. // and we are not in a dependent context, analyze the call operator to infer
  1748. // its constexpr-ness, suppressing diagnostics while doing so.
  1749. if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
  1750. !CallOperator->isConstexpr() &&
  1751. !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
  1752. !Class->getDeclContext()->isDependentContext()) {
  1753. CallOperator->setConstexprKind(
  1754. CheckConstexprFunctionDefinition(CallOperator,
  1755. CheckConstexprKind::CheckValid)
  1756. ? ConstexprSpecKind::Constexpr
  1757. : ConstexprSpecKind::Unspecified);
  1758. }
  1759. // Emit delayed shadowing warnings now that the full capture list is known.
  1760. DiagnoseShadowingLambdaDecls(LSI);
  1761. if (!CurContext->isDependentContext()) {
  1762. switch (ExprEvalContexts.back().Context) {
  1763. // C++11 [expr.prim.lambda]p2:
  1764. // A lambda-expression shall not appear in an unevaluated operand
  1765. // (Clause 5).
  1766. case ExpressionEvaluationContext::Unevaluated:
  1767. case ExpressionEvaluationContext::UnevaluatedList:
  1768. case ExpressionEvaluationContext::UnevaluatedAbstract:
  1769. // C++1y [expr.const]p2:
  1770. // A conditional-expression e is a core constant expression unless the
  1771. // evaluation of e, following the rules of the abstract machine, would
  1772. // evaluate [...] a lambda-expression.
  1773. //
  1774. // This is technically incorrect, there are some constant evaluated contexts
  1775. // where this should be allowed. We should probably fix this when DR1607 is
  1776. // ratified, it lays out the exact set of conditions where we shouldn't
  1777. // allow a lambda-expression.
  1778. case ExpressionEvaluationContext::ConstantEvaluated:
  1779. case ExpressionEvaluationContext::ImmediateFunctionContext:
  1780. // We don't actually diagnose this case immediately, because we
  1781. // could be within a context where we might find out later that
  1782. // the expression is potentially evaluated (e.g., for typeid).
  1783. ExprEvalContexts.back().Lambdas.push_back(Lambda);
  1784. break;
  1785. case ExpressionEvaluationContext::DiscardedStatement:
  1786. case ExpressionEvaluationContext::PotentiallyEvaluated:
  1787. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  1788. break;
  1789. }
  1790. }
  1791. return MaybeBindToTemporary(Lambda);
  1792. }
  1793. ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
  1794. SourceLocation ConvLocation,
  1795. CXXConversionDecl *Conv,
  1796. Expr *Src) {
  1797. // Make sure that the lambda call operator is marked used.
  1798. CXXRecordDecl *Lambda = Conv->getParent();
  1799. CXXMethodDecl *CallOperator
  1800. = cast<CXXMethodDecl>(
  1801. Lambda->lookup(
  1802. Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
  1803. CallOperator->setReferenced();
  1804. CallOperator->markUsed(Context);
  1805. ExprResult Init = PerformCopyInitialization(
  1806. InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
  1807. CurrentLocation, Src);
  1808. if (!Init.isInvalid())
  1809. Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  1810. if (Init.isInvalid())
  1811. return ExprError();
  1812. // Create the new block to be returned.
  1813. BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
  1814. // Set the type information.
  1815. Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
  1816. Block->setIsVariadic(CallOperator->isVariadic());
  1817. Block->setBlockMissingReturnType(false);
  1818. // Add parameters.
  1819. SmallVector<ParmVarDecl *, 4> BlockParams;
  1820. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1821. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1822. BlockParams.push_back(ParmVarDecl::Create(
  1823. Context, Block, From->getBeginLoc(), From->getLocation(),
  1824. From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
  1825. From->getStorageClass(),
  1826. /*DefArg=*/nullptr));
  1827. }
  1828. Block->setParams(BlockParams);
  1829. Block->setIsConversionFromLambda(true);
  1830. // Add capture. The capture uses a fake variable, which doesn't correspond
  1831. // to any actual memory location. However, the initializer copy-initializes
  1832. // the lambda object.
  1833. TypeSourceInfo *CapVarTSI =
  1834. Context.getTrivialTypeSourceInfo(Src->getType());
  1835. VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
  1836. ConvLocation, nullptr,
  1837. Src->getType(), CapVarTSI,
  1838. SC_None);
  1839. BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
  1840. /*nested=*/false, /*copy=*/Init.get());
  1841. Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
  1842. // Add a fake function body to the block. IR generation is responsible
  1843. // for filling in the actual body, which cannot be expressed as an AST.
  1844. Block->setBody(new (Context) CompoundStmt(ConvLocation));
  1845. // Create the block literal expression.
  1846. Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
  1847. ExprCleanupObjects.push_back(Block);
  1848. Cleanup.setExprNeedsCleanups(true);
  1849. return BuildBlock;
  1850. }