SemaCoroutine.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. //===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
  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++ Coroutines.
  10. //
  11. // This file contains references to sections of the Coroutines TS, which
  12. // can be found at http://wg21.link/coroutines.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CoroutineStmtBuilder.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Sema/Initialization.h"
  22. #include "clang/Sema/Overload.h"
  23. #include "clang/Sema/ScopeInfo.h"
  24. #include "clang/Sema/SemaInternal.h"
  25. using namespace clang;
  26. using namespace sema;
  27. static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
  28. SourceLocation Loc, bool &Res) {
  29. DeclarationName DN = S.PP.getIdentifierInfo(Name);
  30. LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
  31. // Suppress diagnostics when a private member is selected. The same warnings
  32. // will be produced again when building the call.
  33. LR.suppressDiagnostics();
  34. Res = S.LookupQualifiedName(LR, RD);
  35. return LR;
  36. }
  37. static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
  38. SourceLocation Loc) {
  39. bool Res;
  40. lookupMember(S, Name, RD, Loc, Res);
  41. return Res;
  42. }
  43. /// Look up the std::coroutine_traits<...>::promise_type for the given
  44. /// function type.
  45. static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
  46. SourceLocation KwLoc) {
  47. const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
  48. const SourceLocation FuncLoc = FD->getLocation();
  49. // FIXME: Cache std::coroutine_traits once we've found it.
  50. NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
  51. if (!StdExp) {
  52. S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
  53. << "std::experimental::coroutine_traits";
  54. return QualType();
  55. }
  56. ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
  57. if (!CoroTraits) {
  58. return QualType();
  59. }
  60. // Form template argument list for coroutine_traits<R, P1, P2, ...> according
  61. // to [dcl.fct.def.coroutine]3
  62. TemplateArgumentListInfo Args(KwLoc, KwLoc);
  63. auto AddArg = [&](QualType T) {
  64. Args.addArgument(TemplateArgumentLoc(
  65. TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
  66. };
  67. AddArg(FnType->getReturnType());
  68. // If the function is a non-static member function, add the type
  69. // of the implicit object parameter before the formal parameters.
  70. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  71. if (MD->isInstance()) {
  72. // [over.match.funcs]4
  73. // For non-static member functions, the type of the implicit object
  74. // parameter is
  75. // -- "lvalue reference to cv X" for functions declared without a
  76. // ref-qualifier or with the & ref-qualifier
  77. // -- "rvalue reference to cv X" for functions declared with the &&
  78. // ref-qualifier
  79. QualType T = MD->getThisType()->getAs<PointerType>()->getPointeeType();
  80. T = FnType->getRefQualifier() == RQ_RValue
  81. ? S.Context.getRValueReferenceType(T)
  82. : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
  83. AddArg(T);
  84. }
  85. }
  86. for (QualType T : FnType->getParamTypes())
  87. AddArg(T);
  88. // Build the template-id.
  89. QualType CoroTrait =
  90. S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
  91. if (CoroTrait.isNull())
  92. return QualType();
  93. if (S.RequireCompleteType(KwLoc, CoroTrait,
  94. diag::err_coroutine_type_missing_specialization))
  95. return QualType();
  96. auto *RD = CoroTrait->getAsCXXRecordDecl();
  97. assert(RD && "specialization of class template is not a class?");
  98. // Look up the ::promise_type member.
  99. LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
  100. Sema::LookupOrdinaryName);
  101. S.LookupQualifiedName(R, RD);
  102. auto *Promise = R.getAsSingle<TypeDecl>();
  103. if (!Promise) {
  104. S.Diag(FuncLoc,
  105. diag::err_implied_std_coroutine_traits_promise_type_not_found)
  106. << RD;
  107. return QualType();
  108. }
  109. // The promise type is required to be a class type.
  110. QualType PromiseType = S.Context.getTypeDeclType(Promise);
  111. auto buildElaboratedType = [&]() {
  112. auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
  113. NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
  114. CoroTrait.getTypePtr());
  115. return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
  116. };
  117. if (!PromiseType->getAsCXXRecordDecl()) {
  118. S.Diag(FuncLoc,
  119. diag::err_implied_std_coroutine_traits_promise_type_not_class)
  120. << buildElaboratedType();
  121. return QualType();
  122. }
  123. if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
  124. diag::err_coroutine_promise_type_incomplete))
  125. return QualType();
  126. return PromiseType;
  127. }
  128. /// Look up the std::experimental::coroutine_handle<PromiseType>.
  129. static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
  130. SourceLocation Loc) {
  131. if (PromiseType.isNull())
  132. return QualType();
  133. NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
  134. assert(StdExp && "Should already be diagnosed");
  135. LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
  136. Loc, Sema::LookupOrdinaryName);
  137. if (!S.LookupQualifiedName(Result, StdExp)) {
  138. S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
  139. << "std::experimental::coroutine_handle";
  140. return QualType();
  141. }
  142. ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
  143. if (!CoroHandle) {
  144. Result.suppressDiagnostics();
  145. // We found something weird. Complain about the first thing we found.
  146. NamedDecl *Found = *Result.begin();
  147. S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
  148. return QualType();
  149. }
  150. // Form template argument list for coroutine_handle<Promise>.
  151. TemplateArgumentListInfo Args(Loc, Loc);
  152. Args.addArgument(TemplateArgumentLoc(
  153. TemplateArgument(PromiseType),
  154. S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
  155. // Build the template-id.
  156. QualType CoroHandleType =
  157. S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
  158. if (CoroHandleType.isNull())
  159. return QualType();
  160. if (S.RequireCompleteType(Loc, CoroHandleType,
  161. diag::err_coroutine_type_missing_specialization))
  162. return QualType();
  163. return CoroHandleType;
  164. }
  165. static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
  166. StringRef Keyword) {
  167. // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
  168. // a function body.
  169. // FIXME: This also covers [expr.await]p2: "An await-expression shall not
  170. // appear in a default argument." But the diagnostic QoI here could be
  171. // improved to inform the user that default arguments specifically are not
  172. // allowed.
  173. auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
  174. if (!FD) {
  175. S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
  176. ? diag::err_coroutine_objc_method
  177. : diag::err_coroutine_outside_function) << Keyword;
  178. return false;
  179. }
  180. // An enumeration for mapping the diagnostic type to the correct diagnostic
  181. // selection index.
  182. enum InvalidFuncDiag {
  183. DiagCtor = 0,
  184. DiagDtor,
  185. DiagCopyAssign,
  186. DiagMoveAssign,
  187. DiagMain,
  188. DiagConstexpr,
  189. DiagAutoRet,
  190. DiagVarargs,
  191. };
  192. bool Diagnosed = false;
  193. auto DiagInvalid = [&](InvalidFuncDiag ID) {
  194. S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
  195. Diagnosed = true;
  196. return false;
  197. };
  198. // Diagnose when a constructor, destructor, copy/move assignment operator,
  199. // or the function 'main' are declared as a coroutine.
  200. auto *MD = dyn_cast<CXXMethodDecl>(FD);
  201. // [class.ctor]p6: "A constructor shall not be a coroutine."
  202. if (MD && isa<CXXConstructorDecl>(MD))
  203. return DiagInvalid(DiagCtor);
  204. // [class.dtor]p17: "A destructor shall not be a coroutine."
  205. else if (MD && isa<CXXDestructorDecl>(MD))
  206. return DiagInvalid(DiagDtor);
  207. // N4499 [special]p6: "A special member function shall not be a coroutine."
  208. // Per C++ [special]p1, special member functions are the "default constructor,
  209. // copy constructor and copy assignment operator, move constructor and move
  210. // assignment operator, and destructor."
  211. else if (MD && MD->isCopyAssignmentOperator())
  212. return DiagInvalid(DiagCopyAssign);
  213. else if (MD && MD->isMoveAssignmentOperator())
  214. return DiagInvalid(DiagMoveAssign);
  215. // [basic.start.main]p3: "The function main shall not be a coroutine."
  216. else if (FD->isMain())
  217. return DiagInvalid(DiagMain);
  218. // Emit a diagnostics for each of the following conditions which is not met.
  219. // [expr.const]p2: "An expression e is a core constant expression unless the
  220. // evaluation of e [...] would evaluate one of the following expressions:
  221. // [...] an await-expression [...] a yield-expression."
  222. if (FD->isConstexpr())
  223. DiagInvalid(DiagConstexpr);
  224. // [dcl.spec.auto]p15: "A function declared with a return type that uses a
  225. // placeholder type shall not be a coroutine."
  226. if (FD->getReturnType()->isUndeducedType())
  227. DiagInvalid(DiagAutoRet);
  228. // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
  229. // coroutine shall not terminate with an ellipsis that is not part of a
  230. // parameter-declaration."
  231. if (FD->isVariadic())
  232. DiagInvalid(DiagVarargs);
  233. return !Diagnosed;
  234. }
  235. static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
  236. SourceLocation Loc) {
  237. DeclarationName OpName =
  238. SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
  239. LookupResult Operators(SemaRef, OpName, SourceLocation(),
  240. Sema::LookupOperatorName);
  241. SemaRef.LookupName(Operators, S);
  242. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  243. const auto &Functions = Operators.asUnresolvedSet();
  244. bool IsOverloaded =
  245. Functions.size() > 1 ||
  246. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  247. Expr *CoawaitOp = UnresolvedLookupExpr::Create(
  248. SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
  249. DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
  250. Functions.begin(), Functions.end());
  251. assert(CoawaitOp);
  252. return CoawaitOp;
  253. }
  254. /// Build a call to 'operator co_await' if there is a suitable operator for
  255. /// the given expression.
  256. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
  257. Expr *E,
  258. UnresolvedLookupExpr *Lookup) {
  259. UnresolvedSet<16> Functions;
  260. Functions.append(Lookup->decls_begin(), Lookup->decls_end());
  261. return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
  262. }
  263. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
  264. SourceLocation Loc, Expr *E) {
  265. ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
  266. if (R.isInvalid())
  267. return ExprError();
  268. return buildOperatorCoawaitCall(SemaRef, Loc, E,
  269. cast<UnresolvedLookupExpr>(R.get()));
  270. }
  271. static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
  272. MultiExprArg CallArgs) {
  273. StringRef Name = S.Context.BuiltinInfo.getName(Id);
  274. LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
  275. S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
  276. auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
  277. assert(BuiltInDecl && "failed to find builtin declaration");
  278. ExprResult DeclRef =
  279. S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
  280. assert(DeclRef.isUsable() && "Builtin reference cannot fail");
  281. ExprResult Call =
  282. S.BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
  283. assert(!Call.isInvalid() && "Call to builtin cannot fail!");
  284. return Call.get();
  285. }
  286. static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
  287. SourceLocation Loc) {
  288. QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
  289. if (CoroHandleType.isNull())
  290. return ExprError();
  291. DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
  292. LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
  293. Sema::LookupOrdinaryName);
  294. if (!S.LookupQualifiedName(Found, LookupCtx)) {
  295. S.Diag(Loc, diag::err_coroutine_handle_missing_member)
  296. << "from_address";
  297. return ExprError();
  298. }
  299. Expr *FramePtr =
  300. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
  301. CXXScopeSpec SS;
  302. ExprResult FromAddr =
  303. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  304. if (FromAddr.isInvalid())
  305. return ExprError();
  306. return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
  307. }
  308. struct ReadySuspendResumeResult {
  309. enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
  310. Expr *Results[3];
  311. OpaqueValueExpr *OpaqueValue;
  312. bool IsInvalid;
  313. };
  314. static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
  315. StringRef Name, MultiExprArg Args) {
  316. DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
  317. // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
  318. CXXScopeSpec SS;
  319. ExprResult Result = S.BuildMemberReferenceExpr(
  320. Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
  321. SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
  322. /*Scope=*/nullptr);
  323. if (Result.isInvalid())
  324. return ExprError();
  325. // We meant exactly what we asked for. No need for typo correction.
  326. if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
  327. S.clearDelayedTypo(TE);
  328. S.Diag(Loc, diag::err_no_member)
  329. << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
  330. << Base->getSourceRange();
  331. return ExprError();
  332. }
  333. return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
  334. }
  335. // See if return type is coroutine-handle and if so, invoke builtin coro-resume
  336. // on its address. This is to enable experimental support for coroutine-handle
  337. // returning await_suspend that results in a guaranteed tail call to the target
  338. // coroutine.
  339. static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
  340. SourceLocation Loc) {
  341. if (RetType->isReferenceType())
  342. return nullptr;
  343. Type const *T = RetType.getTypePtr();
  344. if (!T->isClassType() && !T->isStructureType())
  345. return nullptr;
  346. // FIXME: Add convertability check to coroutine_handle<>. Possibly via
  347. // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
  348. // a private function in SemaExprCXX.cpp
  349. ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
  350. if (AddressExpr.isInvalid())
  351. return nullptr;
  352. Expr *JustAddress = AddressExpr.get();
  353. // FIXME: Check that the type of AddressExpr is void*
  354. return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
  355. JustAddress);
  356. }
  357. /// Build calls to await_ready, await_suspend, and await_resume for a co_await
  358. /// expression.
  359. static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
  360. SourceLocation Loc, Expr *E) {
  361. OpaqueValueExpr *Operand = new (S.Context)
  362. OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
  363. // Assume invalid until we see otherwise.
  364. ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
  365. ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
  366. if (CoroHandleRes.isInvalid())
  367. return Calls;
  368. Expr *CoroHandle = CoroHandleRes.get();
  369. const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
  370. MultiExprArg Args[] = {None, CoroHandle, None};
  371. for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
  372. ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
  373. if (Result.isInvalid())
  374. return Calls;
  375. Calls.Results[I] = Result.get();
  376. }
  377. // Assume the calls are valid; all further checking should make them invalid.
  378. Calls.IsInvalid = false;
  379. using ACT = ReadySuspendResumeResult::AwaitCallType;
  380. CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
  381. if (!AwaitReady->getType()->isDependentType()) {
  382. // [expr.await]p3 [...]
  383. // — await-ready is the expression e.await_ready(), contextually converted
  384. // to bool.
  385. ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
  386. if (Conv.isInvalid()) {
  387. S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
  388. diag::note_await_ready_no_bool_conversion);
  389. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  390. << AwaitReady->getDirectCallee() << E->getSourceRange();
  391. Calls.IsInvalid = true;
  392. }
  393. Calls.Results[ACT::ACT_Ready] = Conv.get();
  394. }
  395. CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
  396. if (!AwaitSuspend->getType()->isDependentType()) {
  397. // [expr.await]p3 [...]
  398. // - await-suspend is the expression e.await_suspend(h), which shall be
  399. // a prvalue of type void or bool.
  400. QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
  401. // Experimental support for coroutine_handle returning await_suspend.
  402. if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
  403. Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
  404. else {
  405. // non-class prvalues always have cv-unqualified types
  406. if (RetType->isReferenceType() ||
  407. (!RetType->isBooleanType() && !RetType->isVoidType())) {
  408. S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
  409. diag::err_await_suspend_invalid_return_type)
  410. << RetType;
  411. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  412. << AwaitSuspend->getDirectCallee();
  413. Calls.IsInvalid = true;
  414. }
  415. }
  416. }
  417. return Calls;
  418. }
  419. static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
  420. SourceLocation Loc, StringRef Name,
  421. MultiExprArg Args) {
  422. // Form a reference to the promise.
  423. ExprResult PromiseRef = S.BuildDeclRefExpr(
  424. Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
  425. if (PromiseRef.isInvalid())
  426. return ExprError();
  427. return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
  428. }
  429. VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
  430. assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
  431. auto *FD = cast<FunctionDecl>(CurContext);
  432. bool IsThisDependentType = [&] {
  433. if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
  434. return MD->isInstance() && MD->getThisType()->isDependentType();
  435. else
  436. return false;
  437. }();
  438. QualType T = FD->getType()->isDependentType() || IsThisDependentType
  439. ? Context.DependentTy
  440. : lookupPromiseType(*this, FD, Loc);
  441. if (T.isNull())
  442. return nullptr;
  443. auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
  444. &PP.getIdentifierTable().get("__promise"), T,
  445. Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
  446. CheckVariableDeclarationType(VD);
  447. if (VD->isInvalidDecl())
  448. return nullptr;
  449. auto *ScopeInfo = getCurFunction();
  450. // Build a list of arguments, based on the coroutine functions arguments,
  451. // that will be passed to the promise type's constructor.
  452. llvm::SmallVector<Expr *, 4> CtorArgExprs;
  453. // Add implicit object parameter.
  454. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  455. if (MD->isInstance() && !isLambdaCallOperator(MD)) {
  456. ExprResult ThisExpr = ActOnCXXThis(Loc);
  457. if (ThisExpr.isInvalid())
  458. return nullptr;
  459. ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
  460. if (ThisExpr.isInvalid())
  461. return nullptr;
  462. CtorArgExprs.push_back(ThisExpr.get());
  463. }
  464. }
  465. auto &Moves = ScopeInfo->CoroutineParameterMoves;
  466. for (auto *PD : FD->parameters()) {
  467. if (PD->getType()->isDependentType())
  468. continue;
  469. auto RefExpr = ExprEmpty();
  470. auto Move = Moves.find(PD);
  471. assert(Move != Moves.end() &&
  472. "Coroutine function parameter not inserted into move map");
  473. // If a reference to the function parameter exists in the coroutine
  474. // frame, use that reference.
  475. auto *MoveDecl =
  476. cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
  477. RefExpr =
  478. BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
  479. ExprValueKind::VK_LValue, FD->getLocation());
  480. if (RefExpr.isInvalid())
  481. return nullptr;
  482. CtorArgExprs.push_back(RefExpr.get());
  483. }
  484. // Create an initialization sequence for the promise type using the
  485. // constructor arguments, wrapped in a parenthesized list expression.
  486. Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
  487. CtorArgExprs, FD->getLocation());
  488. InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
  489. InitializationKind Kind = InitializationKind::CreateForInit(
  490. VD->getLocation(), /*DirectInit=*/true, PLE);
  491. InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
  492. /*TopLevelOfInitList=*/false,
  493. /*TreatUnavailableAsInvalid=*/false);
  494. // Attempt to initialize the promise type with the arguments.
  495. // If that fails, fall back to the promise type's default constructor.
  496. if (InitSeq) {
  497. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
  498. if (Result.isInvalid()) {
  499. VD->setInvalidDecl();
  500. } else if (Result.get()) {
  501. VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
  502. VD->setInitStyle(VarDecl::CallInit);
  503. CheckCompleteVariableDeclaration(VD);
  504. }
  505. } else
  506. ActOnUninitializedDecl(VD);
  507. FD->addDecl(VD);
  508. return VD;
  509. }
  510. /// Check that this is a context in which a coroutine suspension can appear.
  511. static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
  512. StringRef Keyword,
  513. bool IsImplicit = false) {
  514. if (!isValidCoroutineContext(S, Loc, Keyword))
  515. return nullptr;
  516. assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
  517. auto *ScopeInfo = S.getCurFunction();
  518. assert(ScopeInfo && "missing function scope for function");
  519. if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
  520. ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
  521. if (ScopeInfo->CoroutinePromise)
  522. return ScopeInfo;
  523. if (!S.buildCoroutineParameterMoves(Loc))
  524. return nullptr;
  525. ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
  526. if (!ScopeInfo->CoroutinePromise)
  527. return nullptr;
  528. return ScopeInfo;
  529. }
  530. bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
  531. StringRef Keyword) {
  532. if (!checkCoroutineContext(*this, KWLoc, Keyword))
  533. return false;
  534. auto *ScopeInfo = getCurFunction();
  535. assert(ScopeInfo->CoroutinePromise);
  536. // If we have existing coroutine statements then we have already built
  537. // the initial and final suspend points.
  538. if (!ScopeInfo->NeedsCoroutineSuspends)
  539. return true;
  540. ScopeInfo->setNeedsCoroutineSuspends(false);
  541. auto *Fn = cast<FunctionDecl>(CurContext);
  542. SourceLocation Loc = Fn->getLocation();
  543. // Build the initial suspend point
  544. auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
  545. ExprResult Suspend =
  546. buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
  547. if (Suspend.isInvalid())
  548. return StmtError();
  549. Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
  550. if (Suspend.isInvalid())
  551. return StmtError();
  552. Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
  553. /*IsImplicit*/ true);
  554. Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
  555. if (Suspend.isInvalid()) {
  556. Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
  557. << ((Name == "initial_suspend") ? 0 : 1);
  558. Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
  559. return StmtError();
  560. }
  561. return cast<Stmt>(Suspend.get());
  562. };
  563. StmtResult InitSuspend = buildSuspends("initial_suspend");
  564. if (InitSuspend.isInvalid())
  565. return true;
  566. StmtResult FinalSuspend = buildSuspends("final_suspend");
  567. if (FinalSuspend.isInvalid())
  568. return true;
  569. ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
  570. return true;
  571. }
  572. // Recursively walks up the scope hierarchy until either a 'catch' or a function
  573. // scope is found, whichever comes first.
  574. static bool isWithinCatchScope(Scope *S) {
  575. // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
  576. // lambdas that use 'co_await' are allowed. The loop below ends when a
  577. // function scope is found in order to ensure the following behavior:
  578. //
  579. // void foo() { // <- function scope
  580. // try { //
  581. // co_await x; // <- 'co_await' is OK within a function scope
  582. // } catch { // <- catch scope
  583. // co_await x; // <- 'co_await' is not OK within a catch scope
  584. // []() { // <- function scope
  585. // co_await x; // <- 'co_await' is OK within a function scope
  586. // }();
  587. // }
  588. // }
  589. while (S && !(S->getFlags() & Scope::FnScope)) {
  590. if (S->getFlags() & Scope::CatchScope)
  591. return true;
  592. S = S->getParent();
  593. }
  594. return false;
  595. }
  596. // [expr.await]p2, emphasis added: "An await-expression shall appear only in
  597. // a *potentially evaluated* expression within the compound-statement of a
  598. // function-body *outside of a handler* [...] A context within a function
  599. // where an await-expression can appear is called a suspension context of the
  600. // function."
  601. static void checkSuspensionContext(Sema &S, SourceLocation Loc,
  602. StringRef Keyword) {
  603. // First emphasis of [expr.await]p2: must be a potentially evaluated context.
  604. // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
  605. // \c sizeof.
  606. if (S.isUnevaluatedContext())
  607. S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
  608. // Second emphasis of [expr.await]p2: must be outside of an exception handler.
  609. if (isWithinCatchScope(S.getCurScope()))
  610. S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
  611. }
  612. ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
  613. if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
  614. CorrectDelayedTyposInExpr(E);
  615. return ExprError();
  616. }
  617. checkSuspensionContext(*this, Loc, "co_await");
  618. if (E->getType()->isPlaceholderType()) {
  619. ExprResult R = CheckPlaceholderExpr(E);
  620. if (R.isInvalid()) return ExprError();
  621. E = R.get();
  622. }
  623. ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
  624. if (Lookup.isInvalid())
  625. return ExprError();
  626. return BuildUnresolvedCoawaitExpr(Loc, E,
  627. cast<UnresolvedLookupExpr>(Lookup.get()));
  628. }
  629. ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
  630. UnresolvedLookupExpr *Lookup) {
  631. auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
  632. if (!FSI)
  633. return ExprError();
  634. if (E->getType()->isPlaceholderType()) {
  635. ExprResult R = CheckPlaceholderExpr(E);
  636. if (R.isInvalid())
  637. return ExprError();
  638. E = R.get();
  639. }
  640. auto *Promise = FSI->CoroutinePromise;
  641. if (Promise->getType()->isDependentType()) {
  642. Expr *Res =
  643. new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
  644. return Res;
  645. }
  646. auto *RD = Promise->getType()->getAsCXXRecordDecl();
  647. if (lookupMember(*this, "await_transform", RD, Loc)) {
  648. ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
  649. if (R.isInvalid()) {
  650. Diag(Loc,
  651. diag::note_coroutine_promise_implicit_await_transform_required_here)
  652. << E->getSourceRange();
  653. return ExprError();
  654. }
  655. E = R.get();
  656. }
  657. ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
  658. if (Awaitable.isInvalid())
  659. return ExprError();
  660. return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
  661. }
  662. ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
  663. bool IsImplicit) {
  664. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
  665. if (!Coroutine)
  666. return ExprError();
  667. if (E->getType()->isPlaceholderType()) {
  668. ExprResult R = CheckPlaceholderExpr(E);
  669. if (R.isInvalid()) return ExprError();
  670. E = R.get();
  671. }
  672. if (E->getType()->isDependentType()) {
  673. Expr *Res = new (Context)
  674. CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
  675. return Res;
  676. }
  677. // If the expression is a temporary, materialize it as an lvalue so that we
  678. // can use it multiple times.
  679. if (E->getValueKind() == VK_RValue)
  680. E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
  681. // The location of the `co_await` token cannot be used when constructing
  682. // the member call expressions since it's before the location of `Expr`, which
  683. // is used as the start of the member call expression.
  684. SourceLocation CallLoc = E->getExprLoc();
  685. // Build the await_ready, await_suspend, await_resume calls.
  686. ReadySuspendResumeResult RSS =
  687. buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
  688. if (RSS.IsInvalid)
  689. return ExprError();
  690. Expr *Res =
  691. new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
  692. RSS.Results[2], RSS.OpaqueValue, IsImplicit);
  693. return Res;
  694. }
  695. ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
  696. if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
  697. CorrectDelayedTyposInExpr(E);
  698. return ExprError();
  699. }
  700. checkSuspensionContext(*this, Loc, "co_yield");
  701. // Build yield_value call.
  702. ExprResult Awaitable = buildPromiseCall(
  703. *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
  704. if (Awaitable.isInvalid())
  705. return ExprError();
  706. // Build 'operator co_await' call.
  707. Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
  708. if (Awaitable.isInvalid())
  709. return ExprError();
  710. return BuildCoyieldExpr(Loc, Awaitable.get());
  711. }
  712. ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
  713. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
  714. if (!Coroutine)
  715. return ExprError();
  716. if (E->getType()->isPlaceholderType()) {
  717. ExprResult R = CheckPlaceholderExpr(E);
  718. if (R.isInvalid()) return ExprError();
  719. E = R.get();
  720. }
  721. if (E->getType()->isDependentType()) {
  722. Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
  723. return Res;
  724. }
  725. // If the expression is a temporary, materialize it as an lvalue so that we
  726. // can use it multiple times.
  727. if (E->getValueKind() == VK_RValue)
  728. E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
  729. // Build the await_ready, await_suspend, await_resume calls.
  730. ReadySuspendResumeResult RSS =
  731. buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
  732. if (RSS.IsInvalid)
  733. return ExprError();
  734. Expr *Res =
  735. new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
  736. RSS.Results[2], RSS.OpaqueValue);
  737. return Res;
  738. }
  739. StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
  740. if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
  741. CorrectDelayedTyposInExpr(E);
  742. return StmtError();
  743. }
  744. return BuildCoreturnStmt(Loc, E);
  745. }
  746. StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
  747. bool IsImplicit) {
  748. auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
  749. if (!FSI)
  750. return StmtError();
  751. if (E && E->getType()->isPlaceholderType() &&
  752. !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
  753. ExprResult R = CheckPlaceholderExpr(E);
  754. if (R.isInvalid()) return StmtError();
  755. E = R.get();
  756. }
  757. // Move the return value if we can
  758. if (E) {
  759. auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
  760. if (NRVOCandidate) {
  761. InitializedEntity Entity =
  762. InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
  763. ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
  764. Entity, NRVOCandidate, E->getType(), E);
  765. if (MoveResult.get())
  766. E = MoveResult.get();
  767. }
  768. }
  769. // FIXME: If the operand is a reference to a variable that's about to go out
  770. // of scope, we should treat the operand as an xvalue for this overload
  771. // resolution.
  772. VarDecl *Promise = FSI->CoroutinePromise;
  773. ExprResult PC;
  774. if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
  775. PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
  776. } else {
  777. E = MakeFullDiscardedValueExpr(E).get();
  778. PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
  779. }
  780. if (PC.isInvalid())
  781. return StmtError();
  782. Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
  783. Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
  784. return Res;
  785. }
  786. /// Look up the std::nothrow object.
  787. static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
  788. NamespaceDecl *Std = S.getStdNamespace();
  789. assert(Std && "Should already be diagnosed");
  790. LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
  791. Sema::LookupOrdinaryName);
  792. if (!S.LookupQualifiedName(Result, Std)) {
  793. // FIXME: <experimental/coroutine> should have been included already.
  794. // If we require it to include <new> then this diagnostic is no longer
  795. // needed.
  796. S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
  797. return nullptr;
  798. }
  799. auto *VD = Result.getAsSingle<VarDecl>();
  800. if (!VD) {
  801. Result.suppressDiagnostics();
  802. // We found something weird. Complain about the first thing we found.
  803. NamedDecl *Found = *Result.begin();
  804. S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
  805. return nullptr;
  806. }
  807. ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
  808. if (DR.isInvalid())
  809. return nullptr;
  810. return DR.get();
  811. }
  812. // Find an appropriate delete for the promise.
  813. static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
  814. QualType PromiseType) {
  815. FunctionDecl *OperatorDelete = nullptr;
  816. DeclarationName DeleteName =
  817. S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  818. auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
  819. assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
  820. if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
  821. return nullptr;
  822. if (!OperatorDelete) {
  823. // Look for a global declaration.
  824. const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
  825. const bool Overaligned = false;
  826. OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
  827. Overaligned, DeleteName);
  828. }
  829. S.MarkFunctionReferenced(Loc, OperatorDelete);
  830. return OperatorDelete;
  831. }
  832. void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
  833. FunctionScopeInfo *Fn = getCurFunction();
  834. assert(Fn && Fn->isCoroutine() && "not a coroutine");
  835. if (!Body) {
  836. assert(FD->isInvalidDecl() &&
  837. "a null body is only allowed for invalid declarations");
  838. return;
  839. }
  840. // We have a function that uses coroutine keywords, but we failed to build
  841. // the promise type.
  842. if (!Fn->CoroutinePromise)
  843. return FD->setInvalidDecl();
  844. if (isa<CoroutineBodyStmt>(Body)) {
  845. // Nothing todo. the body is already a transformed coroutine body statement.
  846. return;
  847. }
  848. // Coroutines [stmt.return]p1:
  849. // A return statement shall not appear in a coroutine.
  850. if (Fn->FirstReturnLoc.isValid()) {
  851. assert(Fn->FirstCoroutineStmtLoc.isValid() &&
  852. "first coroutine location not set");
  853. Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
  854. Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  855. << Fn->getFirstCoroutineStmtKeyword();
  856. }
  857. CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
  858. if (Builder.isInvalid() || !Builder.buildStatements())
  859. return FD->setInvalidDecl();
  860. // Build body for the coroutine wrapper statement.
  861. Body = CoroutineBodyStmt::Create(Context, Builder);
  862. }
  863. CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
  864. sema::FunctionScopeInfo &Fn,
  865. Stmt *Body)
  866. : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
  867. IsPromiseDependentType(
  868. !Fn.CoroutinePromise ||
  869. Fn.CoroutinePromise->getType()->isDependentType()) {
  870. this->Body = Body;
  871. for (auto KV : Fn.CoroutineParameterMoves)
  872. this->ParamMovesVector.push_back(KV.second);
  873. this->ParamMoves = this->ParamMovesVector;
  874. if (!IsPromiseDependentType) {
  875. PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
  876. assert(PromiseRecordDecl && "Type should have already been checked");
  877. }
  878. this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
  879. }
  880. bool CoroutineStmtBuilder::buildStatements() {
  881. assert(this->IsValid && "coroutine already invalid");
  882. this->IsValid = makeReturnObject();
  883. if (this->IsValid && !IsPromiseDependentType)
  884. buildDependentStatements();
  885. return this->IsValid;
  886. }
  887. bool CoroutineStmtBuilder::buildDependentStatements() {
  888. assert(this->IsValid && "coroutine already invalid");
  889. assert(!this->IsPromiseDependentType &&
  890. "coroutine cannot have a dependent promise type");
  891. this->IsValid = makeOnException() && makeOnFallthrough() &&
  892. makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
  893. makeNewAndDeleteExpr();
  894. return this->IsValid;
  895. }
  896. bool CoroutineStmtBuilder::makePromiseStmt() {
  897. // Form a declaration statement for the promise declaration, so that AST
  898. // visitors can more easily find it.
  899. StmtResult PromiseStmt =
  900. S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
  901. if (PromiseStmt.isInvalid())
  902. return false;
  903. this->Promise = PromiseStmt.get();
  904. return true;
  905. }
  906. bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
  907. if (Fn.hasInvalidCoroutineSuspends())
  908. return false;
  909. this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
  910. this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
  911. return true;
  912. }
  913. static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
  914. CXXRecordDecl *PromiseRecordDecl,
  915. FunctionScopeInfo &Fn) {
  916. auto Loc = E->getExprLoc();
  917. if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
  918. auto *Decl = DeclRef->getDecl();
  919. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
  920. if (Method->isStatic())
  921. return true;
  922. else
  923. Loc = Decl->getLocation();
  924. }
  925. }
  926. S.Diag(
  927. Loc,
  928. diag::err_coroutine_promise_get_return_object_on_allocation_failure)
  929. << PromiseRecordDecl;
  930. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  931. << Fn.getFirstCoroutineStmtKeyword();
  932. return false;
  933. }
  934. bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
  935. assert(!IsPromiseDependentType &&
  936. "cannot make statement while the promise type is dependent");
  937. // [dcl.fct.def.coroutine]/8
  938. // The unqualified-id get_return_object_on_allocation_failure is looked up in
  939. // the scope of class P by class member access lookup (3.4.5). ...
  940. // If an allocation function returns nullptr, ... the coroutine return value
  941. // is obtained by a call to ... get_return_object_on_allocation_failure().
  942. DeclarationName DN =
  943. S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
  944. LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
  945. if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
  946. return true;
  947. CXXScopeSpec SS;
  948. ExprResult DeclNameExpr =
  949. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  950. if (DeclNameExpr.isInvalid())
  951. return false;
  952. if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
  953. return false;
  954. ExprResult ReturnObjectOnAllocationFailure =
  955. S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
  956. if (ReturnObjectOnAllocationFailure.isInvalid())
  957. return false;
  958. StmtResult ReturnStmt =
  959. S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
  960. if (ReturnStmt.isInvalid()) {
  961. S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
  962. << DN;
  963. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  964. << Fn.getFirstCoroutineStmtKeyword();
  965. return false;
  966. }
  967. this->ReturnStmtOnAllocFailure = ReturnStmt.get();
  968. return true;
  969. }
  970. bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
  971. // Form and check allocation and deallocation calls.
  972. assert(!IsPromiseDependentType &&
  973. "cannot make statement while the promise type is dependent");
  974. QualType PromiseType = Fn.CoroutinePromise->getType();
  975. if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
  976. return false;
  977. const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
  978. // [dcl.fct.def.coroutine]/7
  979. // Lookup allocation functions using a parameter list composed of the
  980. // requested size of the coroutine state being allocated, followed by
  981. // the coroutine function's arguments. If a matching allocation function
  982. // exists, use it. Otherwise, use an allocation function that just takes
  983. // the requested size.
  984. FunctionDecl *OperatorNew = nullptr;
  985. FunctionDecl *OperatorDelete = nullptr;
  986. FunctionDecl *UnusedResult = nullptr;
  987. bool PassAlignment = false;
  988. SmallVector<Expr *, 1> PlacementArgs;
  989. // [dcl.fct.def.coroutine]/7
  990. // "The allocation function’s name is looked up in the scope of P.
  991. // [...] If the lookup finds an allocation function in the scope of P,
  992. // overload resolution is performed on a function call created by assembling
  993. // an argument list. The first argument is the amount of space requested,
  994. // and has type std::size_t. The lvalues p1 ... pn are the succeeding
  995. // arguments."
  996. //
  997. // ...where "p1 ... pn" are defined earlier as:
  998. //
  999. // [dcl.fct.def.coroutine]/3
  1000. // "For a coroutine f that is a non-static member function, let P1 denote the
  1001. // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
  1002. // of the function parameters; otherwise let P1 ... Pn be the types of the
  1003. // function parameters. Let p1 ... pn be lvalues denoting those objects."
  1004. if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
  1005. if (MD->isInstance() && !isLambdaCallOperator(MD)) {
  1006. ExprResult ThisExpr = S.ActOnCXXThis(Loc);
  1007. if (ThisExpr.isInvalid())
  1008. return false;
  1009. ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
  1010. if (ThisExpr.isInvalid())
  1011. return false;
  1012. PlacementArgs.push_back(ThisExpr.get());
  1013. }
  1014. }
  1015. for (auto *PD : FD.parameters()) {
  1016. if (PD->getType()->isDependentType())
  1017. continue;
  1018. // Build a reference to the parameter.
  1019. auto PDLoc = PD->getLocation();
  1020. ExprResult PDRefExpr =
  1021. S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
  1022. ExprValueKind::VK_LValue, PDLoc);
  1023. if (PDRefExpr.isInvalid())
  1024. return false;
  1025. PlacementArgs.push_back(PDRefExpr.get());
  1026. }
  1027. S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
  1028. /*DeleteScope*/ Sema::AFS_Both, PromiseType,
  1029. /*isArray*/ false, PassAlignment, PlacementArgs,
  1030. OperatorNew, UnusedResult, /*Diagnose*/ false);
  1031. // [dcl.fct.def.coroutine]/7
  1032. // "If no matching function is found, overload resolution is performed again
  1033. // on a function call created by passing just the amount of space required as
  1034. // an argument of type std::size_t."
  1035. if (!OperatorNew && !PlacementArgs.empty()) {
  1036. PlacementArgs.clear();
  1037. S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
  1038. /*DeleteScope*/ Sema::AFS_Both, PromiseType,
  1039. /*isArray*/ false, PassAlignment, PlacementArgs,
  1040. OperatorNew, UnusedResult, /*Diagnose*/ false);
  1041. }
  1042. // [dcl.fct.def.coroutine]/7
  1043. // "The allocation function’s name is looked up in the scope of P. If this
  1044. // lookup fails, the allocation function’s name is looked up in the global
  1045. // scope."
  1046. if (!OperatorNew) {
  1047. S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
  1048. /*DeleteScope*/ Sema::AFS_Both, PromiseType,
  1049. /*isArray*/ false, PassAlignment, PlacementArgs,
  1050. OperatorNew, UnusedResult);
  1051. }
  1052. bool IsGlobalOverload =
  1053. OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
  1054. // If we didn't find a class-local new declaration and non-throwing new
  1055. // was is required then we need to lookup the non-throwing global operator
  1056. // instead.
  1057. if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
  1058. auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
  1059. if (!StdNoThrow)
  1060. return false;
  1061. PlacementArgs = {StdNoThrow};
  1062. OperatorNew = nullptr;
  1063. S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
  1064. /*DeleteScope*/ Sema::AFS_Both, PromiseType,
  1065. /*isArray*/ false, PassAlignment, PlacementArgs,
  1066. OperatorNew, UnusedResult);
  1067. }
  1068. if (!OperatorNew)
  1069. return false;
  1070. if (RequiresNoThrowAlloc) {
  1071. const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
  1072. if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
  1073. S.Diag(OperatorNew->getLocation(),
  1074. diag::err_coroutine_promise_new_requires_nothrow)
  1075. << OperatorNew;
  1076. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  1077. << OperatorNew;
  1078. return false;
  1079. }
  1080. }
  1081. if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
  1082. return false;
  1083. Expr *FramePtr =
  1084. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
  1085. Expr *FrameSize =
  1086. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
  1087. // Make new call.
  1088. ExprResult NewRef =
  1089. S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
  1090. if (NewRef.isInvalid())
  1091. return false;
  1092. SmallVector<Expr *, 2> NewArgs(1, FrameSize);
  1093. for (auto Arg : PlacementArgs)
  1094. NewArgs.push_back(Arg);
  1095. ExprResult NewExpr =
  1096. S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
  1097. NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
  1098. if (NewExpr.isInvalid())
  1099. return false;
  1100. // Make delete call.
  1101. QualType OpDeleteQualType = OperatorDelete->getType();
  1102. ExprResult DeleteRef =
  1103. S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
  1104. if (DeleteRef.isInvalid())
  1105. return false;
  1106. Expr *CoroFree =
  1107. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
  1108. SmallVector<Expr *, 2> DeleteArgs{CoroFree};
  1109. // Check if we need to pass the size.
  1110. const auto *OpDeleteType =
  1111. OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
  1112. if (OpDeleteType->getNumParams() > 1)
  1113. DeleteArgs.push_back(FrameSize);
  1114. ExprResult DeleteExpr =
  1115. S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
  1116. DeleteExpr =
  1117. S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
  1118. if (DeleteExpr.isInvalid())
  1119. return false;
  1120. this->Allocate = NewExpr.get();
  1121. this->Deallocate = DeleteExpr.get();
  1122. return true;
  1123. }
  1124. bool CoroutineStmtBuilder::makeOnFallthrough() {
  1125. assert(!IsPromiseDependentType &&
  1126. "cannot make statement while the promise type is dependent");
  1127. // [dcl.fct.def.coroutine]/4
  1128. // The unqualified-ids 'return_void' and 'return_value' are looked up in
  1129. // the scope of class P. If both are found, the program is ill-formed.
  1130. bool HasRVoid, HasRValue;
  1131. LookupResult LRVoid =
  1132. lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
  1133. LookupResult LRValue =
  1134. lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
  1135. StmtResult Fallthrough;
  1136. if (HasRVoid && HasRValue) {
  1137. // FIXME Improve this diagnostic
  1138. S.Diag(FD.getLocation(),
  1139. diag::err_coroutine_promise_incompatible_return_functions)
  1140. << PromiseRecordDecl;
  1141. S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
  1142. diag::note_member_first_declared_here)
  1143. << LRVoid.getLookupName();
  1144. S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
  1145. diag::note_member_first_declared_here)
  1146. << LRValue.getLookupName();
  1147. return false;
  1148. } else if (!HasRVoid && !HasRValue) {
  1149. // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
  1150. // However we still diagnose this as an error since until the PDTS is fixed.
  1151. S.Diag(FD.getLocation(),
  1152. diag::err_coroutine_promise_requires_return_function)
  1153. << PromiseRecordDecl;
  1154. S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
  1155. << PromiseRecordDecl;
  1156. return false;
  1157. } else if (HasRVoid) {
  1158. // If the unqualified-id return_void is found, flowing off the end of a
  1159. // coroutine is equivalent to a co_return with no operand. Otherwise,
  1160. // flowing off the end of a coroutine results in undefined behavior.
  1161. Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
  1162. /*IsImplicit*/false);
  1163. Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
  1164. if (Fallthrough.isInvalid())
  1165. return false;
  1166. }
  1167. this->OnFallthrough = Fallthrough.get();
  1168. return true;
  1169. }
  1170. bool CoroutineStmtBuilder::makeOnException() {
  1171. // Try to form 'p.unhandled_exception();'
  1172. assert(!IsPromiseDependentType &&
  1173. "cannot make statement while the promise type is dependent");
  1174. const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
  1175. if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
  1176. auto DiagID =
  1177. RequireUnhandledException
  1178. ? diag::err_coroutine_promise_unhandled_exception_required
  1179. : diag::
  1180. warn_coroutine_promise_unhandled_exception_required_with_exceptions;
  1181. S.Diag(Loc, DiagID) << PromiseRecordDecl;
  1182. S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
  1183. << PromiseRecordDecl;
  1184. return !RequireUnhandledException;
  1185. }
  1186. // If exceptions are disabled, don't try to build OnException.
  1187. if (!S.getLangOpts().CXXExceptions)
  1188. return true;
  1189. ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
  1190. "unhandled_exception", None);
  1191. UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
  1192. /*DiscardedValue*/ false);
  1193. if (UnhandledException.isInvalid())
  1194. return false;
  1195. // Since the body of the coroutine will be wrapped in try-catch, it will
  1196. // be incompatible with SEH __try if present in a function.
  1197. if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
  1198. S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
  1199. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1200. << Fn.getFirstCoroutineStmtKeyword();
  1201. return false;
  1202. }
  1203. this->OnException = UnhandledException.get();
  1204. return true;
  1205. }
  1206. bool CoroutineStmtBuilder::makeReturnObject() {
  1207. // Build implicit 'p.get_return_object()' expression and form initialization
  1208. // of return type from it.
  1209. ExprResult ReturnObject =
  1210. buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
  1211. if (ReturnObject.isInvalid())
  1212. return false;
  1213. this->ReturnValue = ReturnObject.get();
  1214. return true;
  1215. }
  1216. static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
  1217. if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
  1218. auto *MethodDecl = MbrRef->getMethodDecl();
  1219. S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
  1220. << MethodDecl;
  1221. }
  1222. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1223. << Fn.getFirstCoroutineStmtKeyword();
  1224. }
  1225. bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
  1226. assert(!IsPromiseDependentType &&
  1227. "cannot make statement while the promise type is dependent");
  1228. assert(this->ReturnValue && "ReturnValue must be already formed");
  1229. QualType const GroType = this->ReturnValue->getType();
  1230. assert(!GroType->isDependentType() &&
  1231. "get_return_object type must no longer be dependent");
  1232. QualType const FnRetType = FD.getReturnType();
  1233. assert(!FnRetType->isDependentType() &&
  1234. "get_return_object type must no longer be dependent");
  1235. if (FnRetType->isVoidType()) {
  1236. ExprResult Res =
  1237. S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
  1238. if (Res.isInvalid())
  1239. return false;
  1240. this->ResultDecl = Res.get();
  1241. return true;
  1242. }
  1243. if (GroType->isVoidType()) {
  1244. // Trigger a nice error message.
  1245. InitializedEntity Entity =
  1246. InitializedEntity::InitializeResult(Loc, FnRetType, false);
  1247. S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
  1248. noteMemberDeclaredHere(S, ReturnValue, Fn);
  1249. return false;
  1250. }
  1251. auto *GroDecl = VarDecl::Create(
  1252. S.Context, &FD, FD.getLocation(), FD.getLocation(),
  1253. &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
  1254. S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
  1255. S.CheckVariableDeclarationType(GroDecl);
  1256. if (GroDecl->isInvalidDecl())
  1257. return false;
  1258. InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
  1259. ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
  1260. this->ReturnValue);
  1261. if (Res.isInvalid())
  1262. return false;
  1263. Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
  1264. if (Res.isInvalid())
  1265. return false;
  1266. S.AddInitializerToDecl(GroDecl, Res.get(),
  1267. /*DirectInit=*/false);
  1268. S.FinalizeDeclaration(GroDecl);
  1269. // Form a declaration statement for the return declaration, so that AST
  1270. // visitors can more easily find it.
  1271. StmtResult GroDeclStmt =
  1272. S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
  1273. if (GroDeclStmt.isInvalid())
  1274. return false;
  1275. this->ResultDecl = GroDeclStmt.get();
  1276. ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
  1277. if (declRef.isInvalid())
  1278. return false;
  1279. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
  1280. if (ReturnStmt.isInvalid()) {
  1281. noteMemberDeclaredHere(S, ReturnValue, Fn);
  1282. return false;
  1283. }
  1284. if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
  1285. GroDecl->setNRVOVariable(true);
  1286. this->ReturnStmt = ReturnStmt.get();
  1287. return true;
  1288. }
  1289. // Create a static_cast\<T&&>(expr).
  1290. static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
  1291. if (T.isNull())
  1292. T = E->getType();
  1293. QualType TargetType = S.BuildReferenceType(
  1294. T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
  1295. SourceLocation ExprLoc = E->getBeginLoc();
  1296. TypeSourceInfo *TargetLoc =
  1297. S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
  1298. return S
  1299. .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  1300. SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
  1301. .get();
  1302. }
  1303. /// Build a variable declaration for move parameter.
  1304. static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
  1305. IdentifierInfo *II) {
  1306. TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
  1307. VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
  1308. TInfo, SC_None);
  1309. Decl->setImplicit();
  1310. return Decl;
  1311. }
  1312. // Build statements that move coroutine function parameters to the coroutine
  1313. // frame, and store them on the function scope info.
  1314. bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
  1315. assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
  1316. auto *FD = cast<FunctionDecl>(CurContext);
  1317. auto *ScopeInfo = getCurFunction();
  1318. assert(ScopeInfo->CoroutineParameterMoves.empty() &&
  1319. "Should not build parameter moves twice");
  1320. for (auto *PD : FD->parameters()) {
  1321. if (PD->getType()->isDependentType())
  1322. continue;
  1323. ExprResult PDRefExpr =
  1324. BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  1325. ExprValueKind::VK_LValue, Loc); // FIXME: scope?
  1326. if (PDRefExpr.isInvalid())
  1327. return false;
  1328. Expr *CExpr = nullptr;
  1329. if (PD->getType()->getAsCXXRecordDecl() ||
  1330. PD->getType()->isRValueReferenceType())
  1331. CExpr = castForMoving(*this, PDRefExpr.get());
  1332. else
  1333. CExpr = PDRefExpr.get();
  1334. auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
  1335. AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
  1336. // Convert decl to a statement.
  1337. StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
  1338. if (Stmt.isInvalid())
  1339. return false;
  1340. ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
  1341. }
  1342. return true;
  1343. }
  1344. StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
  1345. CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
  1346. if (!Res)
  1347. return StmtError();
  1348. return Res;
  1349. }
  1350. ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
  1351. SourceLocation FuncLoc) {
  1352. if (!StdCoroutineTraitsCache) {
  1353. if (auto StdExp = lookupStdExperimentalNamespace()) {
  1354. LookupResult Result(*this,
  1355. &PP.getIdentifierTable().get("coroutine_traits"),
  1356. FuncLoc, LookupOrdinaryName);
  1357. if (!LookupQualifiedName(Result, StdExp)) {
  1358. Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
  1359. << "std::experimental::coroutine_traits";
  1360. return nullptr;
  1361. }
  1362. if (!(StdCoroutineTraitsCache =
  1363. Result.getAsSingle<ClassTemplateDecl>())) {
  1364. Result.suppressDiagnostics();
  1365. NamedDecl *Found = *Result.begin();
  1366. Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
  1367. return nullptr;
  1368. }
  1369. }
  1370. }
  1371. return StdCoroutineTraitsCache;
  1372. }