SemaLambda.cpp 78 KB

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