CGCoroutine.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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 =
  208. CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(), 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. namespace {
  403. struct GetReturnObjectManager {
  404. CodeGenFunction &CGF;
  405. CGBuilderTy &Builder;
  406. const CoroutineBodyStmt &S;
  407. Address GroActiveFlag;
  408. CodeGenFunction::AutoVarEmission GroEmission;
  409. GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
  410. : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
  411. GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
  412. // The gro variable has to outlive coroutine frame and coroutine promise, but,
  413. // it can only be initialized after coroutine promise was created, thus, we
  414. // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
  415. // cleanups. Later when coroutine promise is available we initialize the gro
  416. // and sets the flag that the cleanup is now active.
  417. void EmitGroAlloca() {
  418. auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
  419. if (!GroDeclStmt) {
  420. // If get_return_object returns void, no need to do an alloca.
  421. return;
  422. }
  423. auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
  424. // Set GRO flag that it is not initialized yet
  425. GroActiveFlag =
  426. CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
  427. Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
  428. GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
  429. // Remember the top of EHStack before emitting the cleanup.
  430. auto old_top = CGF.EHStack.stable_begin();
  431. CGF.EmitAutoVarCleanups(GroEmission);
  432. auto top = CGF.EHStack.stable_begin();
  433. // Make the cleanup conditional on gro.active
  434. for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
  435. b != e; b++) {
  436. if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
  437. assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
  438. Cleanup->setActiveFlag(GroActiveFlag);
  439. Cleanup->setTestFlagInEHCleanup();
  440. Cleanup->setTestFlagInNormalCleanup();
  441. }
  442. }
  443. }
  444. void EmitGroInit() {
  445. if (!GroActiveFlag.isValid()) {
  446. // No Gro variable was allocated. Simply emit the call to
  447. // get_return_object.
  448. CGF.EmitStmt(S.getResultDecl());
  449. return;
  450. }
  451. CGF.EmitAutoVarInit(GroEmission);
  452. Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
  453. }
  454. };
  455. }
  456. static void emitBodyAndFallthrough(CodeGenFunction &CGF,
  457. const CoroutineBodyStmt &S, Stmt *Body) {
  458. CGF.EmitStmt(Body);
  459. const bool CanFallthrough = CGF.Builder.GetInsertBlock();
  460. if (CanFallthrough)
  461. if (Stmt *OnFallthrough = S.getFallthroughHandler())
  462. CGF.EmitStmt(OnFallthrough);
  463. }
  464. void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
  465. auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
  466. auto &TI = CGM.getContext().getTargetInfo();
  467. unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
  468. auto *EntryBB = Builder.GetInsertBlock();
  469. auto *AllocBB = createBasicBlock("coro.alloc");
  470. auto *InitBB = createBasicBlock("coro.init");
  471. auto *FinalBB = createBasicBlock("coro.final");
  472. auto *RetBB = createBasicBlock("coro.ret");
  473. auto *CoroId = Builder.CreateCall(
  474. CGM.getIntrinsic(llvm::Intrinsic::coro_id),
  475. {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
  476. createCoroData(*this, CurCoro, CoroId);
  477. CurCoro.Data->SuspendBB = RetBB;
  478. assert(ShouldEmitLifetimeMarkers &&
  479. "Must emit lifetime intrinsics for coroutines");
  480. // Backend is allowed to elide memory allocations, to help it, emit
  481. // auto mem = coro.alloc() ? 0 : ... allocation code ...;
  482. auto *CoroAlloc = Builder.CreateCall(
  483. CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
  484. Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
  485. EmitBlock(AllocBB);
  486. auto *AllocateCall = EmitScalarExpr(S.getAllocate());
  487. auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
  488. // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
  489. if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
  490. auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
  491. // See if allocation was successful.
  492. auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
  493. auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
  494. Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
  495. // If not, return OnAllocFailure object.
  496. EmitBlock(RetOnFailureBB);
  497. EmitStmt(RetOnAllocFailure);
  498. }
  499. else {
  500. Builder.CreateBr(InitBB);
  501. }
  502. EmitBlock(InitBB);
  503. // Pass the result of the allocation to coro.begin.
  504. auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
  505. Phi->addIncoming(NullPtr, EntryBB);
  506. Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
  507. auto *CoroBegin = Builder.CreateCall(
  508. CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
  509. CurCoro.Data->CoroBegin = CoroBegin;
  510. // We need to emit `get_­return_­object` first. According to:
  511. // [dcl.fct.def.coroutine]p7
  512. // The call to get_­return_­object is sequenced before the call to
  513. // initial_­suspend and is invoked at most once.
  514. GetReturnObjectManager GroManager(*this, S);
  515. GroManager.EmitGroAlloca();
  516. CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
  517. {
  518. CGDebugInfo *DI = getDebugInfo();
  519. ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
  520. CodeGenFunction::RunCleanupsScope ResumeScope(*this);
  521. EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
  522. // Create mapping between parameters and copy-params for coroutine function.
  523. auto ParamMoves = S.getParamMoves();
  524. assert(
  525. (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
  526. "ParamMoves and FnArgs should be the same size for coroutine function");
  527. if (ParamMoves.size() == FnArgs.size() && DI)
  528. for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
  529. DI->getCoroutineParameterMappings().insert(
  530. {std::get<0>(Pair), std::get<1>(Pair)});
  531. // Create parameter copies. We do it before creating a promise, since an
  532. // evolution of coroutine TS may allow promise constructor to observe
  533. // parameter copies.
  534. for (auto *PM : S.getParamMoves()) {
  535. EmitStmt(PM);
  536. ParamReplacer.addCopy(cast<DeclStmt>(PM));
  537. // TODO: if(CoroParam(...)) need to surround ctor and dtor
  538. // for the copy, so that llvm can elide it if the copy is
  539. // not needed.
  540. }
  541. EmitStmt(S.getPromiseDeclStmt());
  542. Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
  543. auto *PromiseAddrVoidPtr =
  544. new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
  545. // Update CoroId to refer to the promise. We could not do it earlier because
  546. // promise local variable was not emitted yet.
  547. CoroId->setArgOperand(1, PromiseAddrVoidPtr);
  548. // Now we have the promise, initialize the GRO
  549. GroManager.EmitGroInit();
  550. EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
  551. CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
  552. CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
  553. EmitStmt(S.getInitSuspendStmt());
  554. CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
  555. CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
  556. if (CurCoro.Data->ExceptionHandler) {
  557. // If we generated IR to record whether an exception was thrown from
  558. // 'await_resume', then use that IR to determine whether the coroutine
  559. // body should be skipped.
  560. // If we didn't generate the IR (perhaps because 'await_resume' was marked
  561. // as 'noexcept'), then we skip this check.
  562. BasicBlock *ContBB = nullptr;
  563. if (CurCoro.Data->ResumeEHVar) {
  564. BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
  565. ContBB = createBasicBlock("coro.resumed.cont");
  566. Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
  567. "coro.resumed.eh");
  568. Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
  569. EmitBlock(BodyBB);
  570. }
  571. auto Loc = S.getBeginLoc();
  572. CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
  573. CurCoro.Data->ExceptionHandler);
  574. auto *TryStmt =
  575. CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
  576. EnterCXXTryStmt(*TryStmt);
  577. emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
  578. ExitCXXTryStmt(*TryStmt);
  579. if (ContBB)
  580. EmitBlock(ContBB);
  581. }
  582. else {
  583. emitBodyAndFallthrough(*this, S, S.getBody());
  584. }
  585. // See if we need to generate final suspend.
  586. const bool CanFallthrough = Builder.GetInsertBlock();
  587. const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
  588. if (CanFallthrough || HasCoreturns) {
  589. EmitBlock(FinalBB);
  590. CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
  591. EmitStmt(S.getFinalSuspendStmt());
  592. } else {
  593. // We don't need FinalBB. Emit it to make sure the block is deleted.
  594. EmitBlock(FinalBB, /*IsFinished=*/true);
  595. }
  596. }
  597. EmitBlock(RetBB);
  598. // Emit coro.end before getReturnStmt (and parameter destructors), since
  599. // resume and destroy parts of the coroutine should not include them.
  600. llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
  601. Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
  602. if (Stmt *Ret = S.getReturnStmt())
  603. EmitStmt(Ret);
  604. // LLVM require the frontend to add the function attribute. See
  605. // Coroutines.rst.
  606. CurFn->addFnAttr("coroutine.presplit", "0");
  607. }
  608. // Emit coroutine intrinsic and patch up arguments of the token type.
  609. RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
  610. unsigned int IID) {
  611. SmallVector<llvm::Value *, 8> Args;
  612. switch (IID) {
  613. default:
  614. break;
  615. // The coro.frame builtin is replaced with an SSA value of the coro.begin
  616. // intrinsic.
  617. case llvm::Intrinsic::coro_frame: {
  618. if (CurCoro.Data && CurCoro.Data->CoroBegin) {
  619. return RValue::get(CurCoro.Data->CoroBegin);
  620. }
  621. CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
  622. "has been used earlier in this function");
  623. auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
  624. return RValue::get(NullPtr);
  625. }
  626. // The following three intrinsics take a token parameter referring to a token
  627. // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
  628. // builtins, we patch it up here.
  629. case llvm::Intrinsic::coro_alloc:
  630. case llvm::Intrinsic::coro_begin:
  631. case llvm::Intrinsic::coro_free: {
  632. if (CurCoro.Data && CurCoro.Data->CoroId) {
  633. Args.push_back(CurCoro.Data->CoroId);
  634. break;
  635. }
  636. CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
  637. " been used earlier in this function");
  638. // Fallthrough to the next case to add TokenNone as the first argument.
  639. LLVM_FALLTHROUGH;
  640. }
  641. // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
  642. // argument.
  643. case llvm::Intrinsic::coro_suspend:
  644. Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
  645. break;
  646. }
  647. for (const Expr *Arg : E->arguments())
  648. Args.push_back(EmitScalarExpr(Arg));
  649. llvm::Function *F = CGM.getIntrinsic(IID);
  650. llvm::CallInst *Call = Builder.CreateCall(F, Args);
  651. // Note: The following code is to enable to emit coro.id and coro.begin by
  652. // hand to experiment with coroutines in C.
  653. // If we see @llvm.coro.id remember it in the CoroData. We will update
  654. // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
  655. if (IID == llvm::Intrinsic::coro_id) {
  656. createCoroData(*this, CurCoro, Call, E);
  657. }
  658. else if (IID == llvm::Intrinsic::coro_begin) {
  659. if (CurCoro.Data)
  660. CurCoro.Data->CoroBegin = Call;
  661. }
  662. else if (IID == llvm::Intrinsic::coro_free) {
  663. // Remember the last coro_free as we need it to build the conditional
  664. // deletion of the coroutine frame.
  665. if (CurCoro.Data)
  666. CurCoro.Data->LastCoroFree = Call;
  667. }
  668. return RValue::get(Call);
  669. }