SemaCoroutine.cpp 57 KB

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