CGCoroutine.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. //===----- CGCoroutine.cpp - Emit LLVM Code for C++ 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 contains code dealing with C++ code generation of coroutines.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCleanup.h"
  13. #include "CodeGenFunction.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "clang/AST/StmtCXX.h"
  16. #include "clang/AST/StmtVisitor.h"
  17. using namespace clang;
  18. using namespace CodeGen;
  19. using llvm::Value;
  20. using llvm::BasicBlock;
  21. namespace {
  22. enum class AwaitKind { Init, Normal, Yield, Final };
  23. static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
  24. "final"};
  25. }
  26. struct clang::CodeGen::CGCoroData {
  27. // What is the current await expression kind and how many
  28. // await/yield expressions were encountered so far.
  29. // These are used to generate pretty labels for await expressions in LLVM IR.
  30. AwaitKind CurrentAwaitKind = AwaitKind::Init;
  31. unsigned AwaitNum = 0;
  32. unsigned YieldNum = 0;
  33. // How many co_return statements are in the coroutine. Used to decide whether
  34. // we need to add co_return; equivalent at the end of the user authored body.
  35. unsigned CoreturnCount = 0;
  36. // A branch to this block is emitted when coroutine needs to suspend.
  37. llvm::BasicBlock *SuspendBB = nullptr;
  38. // The promise type's 'unhandled_exception' handler, if it defines one.
  39. Stmt *ExceptionHandler = nullptr;
  40. // A temporary i1 alloca that stores whether 'await_resume' threw an
  41. // exception. If it did, 'true' is stored in this variable, and the coroutine
  42. // body must be skipped. If the promise type does not define an exception
  43. // handler, this is null.
  44. llvm::Value *ResumeEHVar = nullptr;
  45. // Stores the jump destination just before the coroutine memory is freed.
  46. // This is the destination that every suspend point jumps to for the cleanup
  47. // branch.
  48. CodeGenFunction::JumpDest CleanupJD;
  49. // Stores the jump destination just before the final suspend. The co_return
  50. // statements jumps to this point after calling return_xxx promise member.
  51. CodeGenFunction::JumpDest FinalJD;
  52. // Stores the llvm.coro.id emitted in the function so that we can supply it
  53. // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
  54. // Note: llvm.coro.id returns a token that cannot be directly expressed in a
  55. // builtin.
  56. llvm::CallInst *CoroId = nullptr;
  57. // Stores the llvm.coro.begin emitted in the function so that we can replace
  58. // all coro.frame intrinsics with direct SSA value of coro.begin that returns
  59. // the address of the coroutine frame of the current coroutine.
  60. llvm::CallInst *CoroBegin = nullptr;
  61. // Stores the last emitted coro.free for the deallocate expressions, we use it
  62. // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
  63. llvm::CallInst *LastCoroFree = nullptr;
  64. // If coro.id came from the builtin, remember the expression to give better
  65. // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
  66. // EmitCoroutineBody.
  67. CallExpr const *CoroIdExpr = nullptr;
  68. };
  69. // Defining these here allows to keep CGCoroData private to this file.
  70. clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
  71. CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
  72. static void createCoroData(CodeGenFunction &CGF,
  73. CodeGenFunction::CGCoroInfo &CurCoro,
  74. llvm::CallInst *CoroId,
  75. CallExpr const *CoroIdExpr = nullptr) {
  76. if (CurCoro.Data) {
  77. if (CurCoro.Data->CoroIdExpr)
  78. CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
  79. "only one __builtin_coro_id can be used in a function");
  80. else if (CoroIdExpr)
  81. CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
  82. "__builtin_coro_id shall not be used in a C++ coroutine");
  83. else
  84. llvm_unreachable("EmitCoroutineBodyStatement called twice?");
  85. return;
  86. }
  87. CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
  88. CurCoro.Data->CoroId = CoroId;
  89. CurCoro.Data->CoroIdExpr = CoroIdExpr;
  90. }
  91. // Synthesize a pretty name for a suspend point.
  92. static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
  93. unsigned No = 0;
  94. switch (Kind) {
  95. case AwaitKind::Init:
  96. case AwaitKind::Final:
  97. break;
  98. case AwaitKind::Normal:
  99. No = ++Coro.AwaitNum;
  100. break;
  101. case AwaitKind::Yield:
  102. No = ++Coro.YieldNum;
  103. break;
  104. }
  105. SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
  106. if (No > 1) {
  107. Twine(No).toVector(Prefix);
  108. }
  109. return Prefix;
  110. }
  111. static bool memberCallExpressionCanThrow(const Expr *E) {
  112. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  113. if (const auto *Proto =
  114. CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
  115. if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
  116. Proto->canThrow() == CT_Cannot)
  117. return false;
  118. return true;
  119. }
  120. // Emit suspend expression which roughly looks like:
  121. //
  122. // auto && x = CommonExpr();
  123. // if (!x.await_ready()) {
  124. // llvm_coro_save();
  125. // x.await_suspend(...); (*)
  126. // llvm_coro_suspend(); (**)
  127. // }
  128. // x.await_resume();
  129. //
  130. // where the result of the entire expression is the result of x.await_resume()
  131. //
  132. // (*) If x.await_suspend return type is bool, it allows to veto a suspend:
  133. // if (x.await_suspend(...))
  134. // llvm_coro_suspend();
  135. //
  136. // (**) llvm_coro_suspend() encodes three possible continuations as
  137. // a switch instruction:
  138. //
  139. // %where-to = call i8 @llvm.coro.suspend(...)
  140. // switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
  141. // i8 0, label %yield.ready ; go here when resumed
  142. // i8 1, label %yield.cleanup ; go here when destroyed
  143. // ]
  144. //
  145. // See llvm's docs/Coroutines.rst for more details.
  146. //
  147. namespace {
  148. struct LValueOrRValue {
  149. LValue LV;
  150. RValue RV;
  151. };
  152. }
  153. static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
  154. CoroutineSuspendExpr const &S,
  155. AwaitKind Kind, AggValueSlot aggSlot,
  156. bool ignoreResult, bool forLValue) {
  157. auto *E = S.getCommonExpr();
  158. auto Binder =
  159. CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
  160. auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
  161. auto Prefix = buildSuspendPrefixStr(Coro, Kind);
  162. BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
  163. BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
  164. BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
  165. // If expression is ready, no need to suspend.
  166. CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
  167. // Otherwise, emit suspend logic.
  168. CGF.EmitBlock(SuspendBlock);
  169. auto &Builder = CGF.Builder;
  170. llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
  171. auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
  172. auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
  173. auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
  174. if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
  175. // Veto suspension if requested by bool returning await_suspend.
  176. BasicBlock *RealSuspendBlock =
  177. CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
  178. CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
  179. CGF.EmitBlock(RealSuspendBlock);
  180. }
  181. // Emit the suspend point.
  182. const bool IsFinalSuspend = (Kind == AwaitKind::Final);
  183. llvm::Function *CoroSuspend =
  184. CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
  185. auto *SuspendResult = Builder.CreateCall(
  186. CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
  187. // Create a switch capturing three possible continuations.
  188. auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
  189. Switch->addCase(Builder.getInt8(0), ReadyBlock);
  190. Switch->addCase(Builder.getInt8(1), CleanupBlock);
  191. // Emit cleanup for this suspend point.
  192. CGF.EmitBlock(CleanupBlock);
  193. CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
  194. // Emit await_resume expression.
  195. CGF.EmitBlock(ReadyBlock);
  196. // Exception handling requires additional IR. If the 'await_resume' function
  197. // is marked as 'noexcept', we avoid generating this additional IR.
  198. CXXTryStmt *TryStmt = nullptr;
  199. if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
  200. memberCallExpressionCanThrow(S.getResumeExpr())) {
  201. Coro.ResumeEHVar =
  202. CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
  203. Builder.CreateFlagStore(true, Coro.ResumeEHVar);
  204. auto Loc = S.getResumeExpr()->getExprLoc();
  205. auto *Catch = new (CGF.getContext())
  206. CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
  207. auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
  208. FPOptionsOverride(), Loc, Loc);
  209. TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
  210. CGF.EnterCXXTryStmt(*TryStmt);
  211. }
  212. LValueOrRValue Res;
  213. if (forLValue)
  214. Res.LV = CGF.EmitLValue(S.getResumeExpr());
  215. else
  216. Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
  217. if (TryStmt) {
  218. Builder.CreateFlagStore(false, Coro.ResumeEHVar);
  219. CGF.ExitCXXTryStmt(*TryStmt);
  220. }
  221. return Res;
  222. }
  223. RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
  224. AggValueSlot aggSlot,
  225. bool ignoreResult) {
  226. return emitSuspendExpression(*this, *CurCoro.Data, E,
  227. CurCoro.Data->CurrentAwaitKind, aggSlot,
  228. ignoreResult, /*forLValue*/false).RV;
  229. }
  230. RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
  231. AggValueSlot aggSlot,
  232. bool ignoreResult) {
  233. return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
  234. aggSlot, ignoreResult, /*forLValue*/false).RV;
  235. }
  236. void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
  237. ++CurCoro.Data->CoreturnCount;
  238. const Expr *RV = S.getOperand();
  239. if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
  240. // Make sure to evaluate the non initlist expression of a co_return
  241. // with a void expression for side effects.
  242. RunCleanupsScope cleanupScope(*this);
  243. EmitIgnoredExpr(RV);
  244. }
  245. EmitStmt(S.getPromiseCall());
  246. EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
  247. }
  248. #ifndef NDEBUG
  249. static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
  250. const CoroutineSuspendExpr *E) {
  251. const auto *RE = E->getResumeExpr();
  252. // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
  253. // a MemberCallExpr?
  254. assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
  255. return cast<CallExpr>(RE)->getCallReturnType(Ctx);
  256. }
  257. #endif
  258. LValue
  259. CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
  260. assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
  261. "Can't have a scalar return unless the return type is a "
  262. "reference type!");
  263. return emitSuspendExpression(*this, *CurCoro.Data, *E,
  264. CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
  265. /*ignoreResult*/false, /*forLValue*/true).LV;
  266. }
  267. LValue
  268. CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
  269. assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
  270. "Can't have a scalar return unless the return type is a "
  271. "reference type!");
  272. return emitSuspendExpression(*this, *CurCoro.Data, *E,
  273. AwaitKind::Yield, AggValueSlot::ignored(),
  274. /*ignoreResult*/false, /*forLValue*/true).LV;
  275. }
  276. // Hunts for the parameter reference in the parameter copy/move declaration.
  277. namespace {
  278. struct GetParamRef : public StmtVisitor<GetParamRef> {
  279. public:
  280. DeclRefExpr *Expr = nullptr;
  281. GetParamRef() {}
  282. void VisitDeclRefExpr(DeclRefExpr *E) {
  283. assert(Expr == nullptr && "multilple declref in param move");
  284. Expr = E;
  285. }
  286. void VisitStmt(Stmt *S) {
  287. for (auto *C : S->children()) {
  288. if (C)
  289. Visit(C);
  290. }
  291. }
  292. };
  293. }
  294. // This class replaces references to parameters to their copies by changing
  295. // the addresses in CGF.LocalDeclMap and restoring back the original values in
  296. // its destructor.
  297. namespace {
  298. struct ParamReferenceReplacerRAII {
  299. CodeGenFunction::DeclMapTy SavedLocals;
  300. CodeGenFunction::DeclMapTy& LocalDeclMap;
  301. ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
  302. : LocalDeclMap(LocalDeclMap) {}
  303. void addCopy(DeclStmt const *PM) {
  304. // Figure out what param it refers to.
  305. assert(PM->isSingleDecl());
  306. VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
  307. Expr const *InitExpr = VD->getInit();
  308. GetParamRef Visitor;
  309. Visitor.Visit(const_cast<Expr*>(InitExpr));
  310. assert(Visitor.Expr);
  311. DeclRefExpr *DREOrig = Visitor.Expr;
  312. auto *PD = DREOrig->getDecl();
  313. auto it = LocalDeclMap.find(PD);
  314. assert(it != LocalDeclMap.end() && "parameter is not found");
  315. SavedLocals.insert({ PD, it->second });
  316. auto copyIt = LocalDeclMap.find(VD);
  317. assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
  318. it->second = copyIt->getSecond();
  319. }
  320. ~ParamReferenceReplacerRAII() {
  321. for (auto&& SavedLocal : SavedLocals) {
  322. LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
  323. }
  324. }
  325. };
  326. }
  327. // For WinEH exception representation backend needs to know what funclet coro.end
  328. // belongs to. That information is passed in a funclet bundle.
  329. static SmallVector<llvm::OperandBundleDef, 1>
  330. getBundlesForCoroEnd(CodeGenFunction &CGF) {
  331. SmallVector<llvm::OperandBundleDef, 1> BundleList;
  332. if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
  333. BundleList.emplace_back("funclet", EHPad);
  334. return BundleList;
  335. }
  336. namespace {
  337. // We will insert coro.end to cut any of the destructors for objects that
  338. // do not need to be destroyed once the coroutine is resumed.
  339. // See llvm/docs/Coroutines.rst for more details about coro.end.
  340. struct CallCoroEnd final : public EHScopeStack::Cleanup {
  341. void Emit(CodeGenFunction &CGF, Flags flags) override {
  342. auto &CGM = CGF.CGM;
  343. auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  344. llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
  345. // See if we have a funclet bundle to associate coro.end with. (WinEH)
  346. auto Bundles = getBundlesForCoroEnd(CGF);
  347. auto *CoroEnd = CGF.Builder.CreateCall(
  348. CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
  349. if (Bundles.empty()) {
  350. // Otherwise, (landingpad model), create a conditional branch that leads
  351. // either to a cleanup block or a block with EH resume instruction.
  352. auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
  353. auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
  354. CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
  355. CGF.EmitBlock(CleanupContBB);
  356. }
  357. }
  358. };
  359. }
  360. namespace {
  361. // Make sure to call coro.delete on scope exit.
  362. struct CallCoroDelete final : public EHScopeStack::Cleanup {
  363. Stmt *Deallocate;
  364. // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
  365. // Note: That deallocation will be emitted twice: once for a normal exit and
  366. // once for exceptional exit. This usage is safe because Deallocate does not
  367. // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
  368. // builds a single call to a deallocation function which is safe to emit
  369. // multiple times.
  370. void Emit(CodeGenFunction &CGF, Flags) override {
  371. // Remember the current point, as we are going to emit deallocation code
  372. // first to get to coro.free instruction that is an argument to a delete
  373. // call.
  374. BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
  375. auto *FreeBB = CGF.createBasicBlock("coro.free");
  376. CGF.EmitBlock(FreeBB);
  377. CGF.EmitStmt(Deallocate);
  378. auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
  379. CGF.EmitBlock(AfterFreeBB);
  380. // We should have captured coro.free from the emission of deallocate.
  381. auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
  382. if (!CoroFree) {
  383. CGF.CGM.Error(Deallocate->getBeginLoc(),
  384. "Deallocation expressoin does not refer to coro.free");
  385. return;
  386. }
  387. // Get back to the block we were originally and move coro.free there.
  388. auto *InsertPt = SaveInsertBlock->getTerminator();
  389. CoroFree->moveBefore(InsertPt);
  390. CGF.Builder.SetInsertPoint(InsertPt);
  391. // Add if (auto *mem = coro.free) Deallocate;
  392. auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  393. auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
  394. CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
  395. // No longer need old terminator.
  396. InsertPt->eraseFromParent();
  397. CGF.Builder.SetInsertPoint(AfterFreeBB);
  398. }
  399. explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
  400. };
  401. }
  402. static void emitBodyAndFallthrough(CodeGenFunction &CGF,
  403. const CoroutineBodyStmt &S, Stmt *Body) {
  404. CGF.EmitStmt(Body);
  405. const bool CanFallthrough = CGF.Builder.GetInsertBlock();
  406. if (CanFallthrough)
  407. if (Stmt *OnFallthrough = S.getFallthroughHandler())
  408. CGF.EmitStmt(OnFallthrough);
  409. }
  410. void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
  411. auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
  412. auto &TI = CGM.getContext().getTargetInfo();
  413. unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
  414. auto *EntryBB = Builder.GetInsertBlock();
  415. auto *AllocBB = createBasicBlock("coro.alloc");
  416. auto *InitBB = createBasicBlock("coro.init");
  417. auto *FinalBB = createBasicBlock("coro.final");
  418. auto *RetBB = createBasicBlock("coro.ret");
  419. auto *CoroId = Builder.CreateCall(
  420. CGM.getIntrinsic(llvm::Intrinsic::coro_id),
  421. {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
  422. createCoroData(*this, CurCoro, CoroId);
  423. CurCoro.Data->SuspendBB = RetBB;
  424. assert(ShouldEmitLifetimeMarkers &&
  425. "Must emit lifetime intrinsics for coroutines");
  426. // Backend is allowed to elide memory allocations, to help it, emit
  427. // auto mem = coro.alloc() ? 0 : ... allocation code ...;
  428. auto *CoroAlloc = Builder.CreateCall(
  429. CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
  430. Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
  431. EmitBlock(AllocBB);
  432. auto *AllocateCall = EmitScalarExpr(S.getAllocate());
  433. auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
  434. // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
  435. if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
  436. auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
  437. // See if allocation was successful.
  438. auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
  439. auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
  440. Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
  441. // If not, return OnAllocFailure object.
  442. EmitBlock(RetOnFailureBB);
  443. EmitStmt(RetOnAllocFailure);
  444. }
  445. else {
  446. Builder.CreateBr(InitBB);
  447. }
  448. EmitBlock(InitBB);
  449. // Pass the result of the allocation to coro.begin.
  450. auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
  451. Phi->addIncoming(NullPtr, EntryBB);
  452. Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
  453. auto *CoroBegin = Builder.CreateCall(
  454. CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
  455. CurCoro.Data->CoroBegin = CoroBegin;
  456. CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
  457. {
  458. CGDebugInfo *DI = getDebugInfo();
  459. ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
  460. CodeGenFunction::RunCleanupsScope ResumeScope(*this);
  461. EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
  462. // Create mapping between parameters and copy-params for coroutine function.
  463. llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
  464. assert(
  465. (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
  466. "ParamMoves and FnArgs should be the same size for coroutine function");
  467. if (ParamMoves.size() == FnArgs.size() && DI)
  468. for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
  469. DI->getCoroutineParameterMappings().insert(
  470. {std::get<0>(Pair), std::get<1>(Pair)});
  471. // Create parameter copies. We do it before creating a promise, since an
  472. // evolution of coroutine TS may allow promise constructor to observe
  473. // parameter copies.
  474. for (auto *PM : S.getParamMoves()) {
  475. EmitStmt(PM);
  476. ParamReplacer.addCopy(cast<DeclStmt>(PM));
  477. // TODO: if(CoroParam(...)) need to surround ctor and dtor
  478. // for the copy, so that llvm can elide it if the copy is
  479. // not needed.
  480. }
  481. EmitStmt(S.getPromiseDeclStmt());
  482. Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
  483. auto *PromiseAddrVoidPtr =
  484. new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
  485. // Update CoroId to refer to the promise. We could not do it earlier because
  486. // promise local variable was not emitted yet.
  487. CoroId->setArgOperand(1, PromiseAddrVoidPtr);
  488. // ReturnValue should be valid as long as the coroutine's return type
  489. // is not void. The assertion could help us to reduce the check later.
  490. assert(ReturnValue.isValid() == (bool)S.getReturnStmt());
  491. // Now we have the promise, initialize the GRO.
  492. // We need to emit `get_return_object` first. According to:
  493. // [dcl.fct.def.coroutine]p7
  494. // The call to get_return_­object is sequenced before the call to
  495. // initial_suspend and is invoked at most once.
  496. //
  497. // So we couldn't emit return value when we emit return statment,
  498. // otherwise the call to get_return_object wouldn't be in front
  499. // of initial_suspend.
  500. if (ReturnValue.isValid()) {
  501. EmitAnyExprToMem(S.getReturnValue(), ReturnValue,
  502. S.getReturnValue()->getType().getQualifiers(),
  503. /*IsInit*/ true);
  504. }
  505. EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
  506. CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
  507. CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
  508. EmitStmt(S.getInitSuspendStmt());
  509. CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
  510. CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
  511. if (CurCoro.Data->ExceptionHandler) {
  512. // If we generated IR to record whether an exception was thrown from
  513. // 'await_resume', then use that IR to determine whether the coroutine
  514. // body should be skipped.
  515. // If we didn't generate the IR (perhaps because 'await_resume' was marked
  516. // as 'noexcept'), then we skip this check.
  517. BasicBlock *ContBB = nullptr;
  518. if (CurCoro.Data->ResumeEHVar) {
  519. BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
  520. ContBB = createBasicBlock("coro.resumed.cont");
  521. Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
  522. "coro.resumed.eh");
  523. Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
  524. EmitBlock(BodyBB);
  525. }
  526. auto Loc = S.getBeginLoc();
  527. CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
  528. CurCoro.Data->ExceptionHandler);
  529. auto *TryStmt =
  530. CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
  531. EnterCXXTryStmt(*TryStmt);
  532. emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
  533. ExitCXXTryStmt(*TryStmt);
  534. if (ContBB)
  535. EmitBlock(ContBB);
  536. }
  537. else {
  538. emitBodyAndFallthrough(*this, S, S.getBody());
  539. }
  540. // See if we need to generate final suspend.
  541. const bool CanFallthrough = Builder.GetInsertBlock();
  542. const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
  543. if (CanFallthrough || HasCoreturns) {
  544. EmitBlock(FinalBB);
  545. CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
  546. EmitStmt(S.getFinalSuspendStmt());
  547. } else {
  548. // We don't need FinalBB. Emit it to make sure the block is deleted.
  549. EmitBlock(FinalBB, /*IsFinished=*/true);
  550. }
  551. }
  552. EmitBlock(RetBB);
  553. // Emit coro.end before getReturnStmt (and parameter destructors), since
  554. // resume and destroy parts of the coroutine should not include them.
  555. llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
  556. Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
  557. if (Stmt *Ret = S.getReturnStmt()) {
  558. // Since we already emitted the return value above, so we shouldn't
  559. // emit it again here.
  560. cast<ReturnStmt>(Ret)->setRetValue(nullptr);
  561. EmitStmt(Ret);
  562. }
  563. // LLVM require the frontend to mark the coroutine.
  564. CurFn->setPresplitCoroutine();
  565. }
  566. // Emit coroutine intrinsic and patch up arguments of the token type.
  567. RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
  568. unsigned int IID) {
  569. SmallVector<llvm::Value *, 8> Args;
  570. switch (IID) {
  571. default:
  572. break;
  573. // The coro.frame builtin is replaced with an SSA value of the coro.begin
  574. // intrinsic.
  575. case llvm::Intrinsic::coro_frame: {
  576. if (CurCoro.Data && CurCoro.Data->CoroBegin) {
  577. return RValue::get(CurCoro.Data->CoroBegin);
  578. }
  579. CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
  580. "has been used earlier in this function");
  581. auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
  582. return RValue::get(NullPtr);
  583. }
  584. case llvm::Intrinsic::coro_size: {
  585. auto &Context = getContext();
  586. CanQualType SizeTy = Context.getSizeType();
  587. llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
  588. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
  589. return RValue::get(Builder.CreateCall(F));
  590. }
  591. case llvm::Intrinsic::coro_align: {
  592. auto &Context = getContext();
  593. CanQualType SizeTy = Context.getSizeType();
  594. llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
  595. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
  596. return RValue::get(Builder.CreateCall(F));
  597. }
  598. // The following three intrinsics take a token parameter referring to a token
  599. // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
  600. // builtins, we patch it up here.
  601. case llvm::Intrinsic::coro_alloc:
  602. case llvm::Intrinsic::coro_begin:
  603. case llvm::Intrinsic::coro_free: {
  604. if (CurCoro.Data && CurCoro.Data->CoroId) {
  605. Args.push_back(CurCoro.Data->CoroId);
  606. break;
  607. }
  608. CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
  609. " been used earlier in this function");
  610. // Fallthrough to the next case to add TokenNone as the first argument.
  611. [[fallthrough]];
  612. }
  613. // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
  614. // argument.
  615. case llvm::Intrinsic::coro_suspend:
  616. Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
  617. break;
  618. }
  619. for (const Expr *Arg : E->arguments())
  620. Args.push_back(EmitScalarExpr(Arg));
  621. llvm::Function *F = CGM.getIntrinsic(IID);
  622. llvm::CallInst *Call = Builder.CreateCall(F, Args);
  623. // Note: The following code is to enable to emit coro.id and coro.begin by
  624. // hand to experiment with coroutines in C.
  625. // If we see @llvm.coro.id remember it in the CoroData. We will update
  626. // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
  627. if (IID == llvm::Intrinsic::coro_id) {
  628. createCoroData(*this, CurCoro, Call, E);
  629. }
  630. else if (IID == llvm::Intrinsic::coro_begin) {
  631. if (CurCoro.Data)
  632. CurCoro.Data->CoroBegin = Call;
  633. }
  634. else if (IID == llvm::Intrinsic::coro_free) {
  635. // Remember the last coro_free as we need it to build the conditional
  636. // deletion of the coroutine frame.
  637. if (CurCoro.Data)
  638. CurCoro.Data->LastCoroFree = Call;
  639. }
  640. return RValue::get(Call);
  641. }