1 //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation of coroutines.
12 //===----------------------------------------------------------------------===//
14 #include "CGCleanup.h"
15 #include "CodeGenFunction.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/AST/StmtVisitor.h"
20 using namespace clang;
21 using namespace CodeGen;
24 using llvm::BasicBlock;
27 enum class AwaitKind { Init, Normal, Yield, Final };
28 static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
32 struct clang::CodeGen::CGCoroData {
33 // What is the current await expression kind and how many
34 // await/yield expressions were encountered so far.
35 // These are used to generate pretty labels for await expressions in LLVM IR.
36 AwaitKind CurrentAwaitKind = AwaitKind::Init;
37 unsigned AwaitNum = 0;
38 unsigned YieldNum = 0;
40 // How many co_return statements are in the coroutine. Used to decide whether
41 // we need to add co_return; equivalent at the end of the user authored body.
42 unsigned CoreturnCount = 0;
44 // A branch to this block is emitted when coroutine needs to suspend.
45 llvm::BasicBlock *SuspendBB = nullptr;
47 // The promise type's 'unhandled_exception' handler, if it defines one.
48 Stmt *ExceptionHandler = nullptr;
50 // A temporary i1 alloca that stores whether 'await_resume' threw an
51 // exception. If it did, 'true' is stored in this variable, and the coroutine
52 // body must be skipped. If the promise type does not define an exception
53 // handler, this is null.
54 llvm::Value *ResumeEHVar = nullptr;
56 // Stores the jump destination just before the coroutine memory is freed.
57 // This is the destination that every suspend point jumps to for the cleanup
59 CodeGenFunction::JumpDest CleanupJD;
61 // Stores the jump destination just before the final suspend. The co_return
62 // statements jumps to this point after calling return_xxx promise member.
63 CodeGenFunction::JumpDest FinalJD;
65 // Stores the llvm.coro.id emitted in the function so that we can supply it
66 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
67 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
69 llvm::CallInst *CoroId = nullptr;
71 // Stores the llvm.coro.begin emitted in the function so that we can replace
72 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
73 // the address of the coroutine frame of the current coroutine.
74 llvm::CallInst *CoroBegin = nullptr;
76 // Stores the last emitted coro.free for the deallocate expressions, we use it
77 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
78 llvm::CallInst *LastCoroFree = nullptr;
80 // If coro.id came from the builtin, remember the expression to give better
81 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
83 CallExpr const *CoroIdExpr = nullptr;
86 // Defining these here allows to keep CGCoroData private to this file.
87 clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
88 CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
90 static void createCoroData(CodeGenFunction &CGF,
91 CodeGenFunction::CGCoroInfo &CurCoro,
92 llvm::CallInst *CoroId,
93 CallExpr const *CoroIdExpr = nullptr) {
95 if (CurCoro.Data->CoroIdExpr)
96 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
97 "only one __builtin_coro_id can be used in a function");
99 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
100 "__builtin_coro_id shall not be used in a C++ coroutine");
102 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
107 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
108 CurCoro.Data->CoroId = CoroId;
109 CurCoro.Data->CoroIdExpr = CoroIdExpr;
112 // Synthesize a pretty name for a suspend point.
113 static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
116 case AwaitKind::Init:
117 case AwaitKind::Final:
119 case AwaitKind::Normal:
120 No = ++Coro.AwaitNum;
122 case AwaitKind::Yield:
123 No = ++Coro.YieldNum;
126 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
128 Twine(No).toVector(Prefix);
133 static bool memberCallExpressionCanThrow(const Expr *E) {
134 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
135 if (const auto *Proto =
136 CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
137 if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
138 Proto->canThrow() == CT_Cannot)
143 // Emit suspend expression which roughly looks like:
145 // auto && x = CommonExpr();
146 // if (!x.await_ready()) {
148 // x.await_suspend(...); (*)
149 // llvm_coro_suspend(); (**)
153 // where the result of the entire expression is the result of x.await_resume()
155 // (*) If x.await_suspend return type is bool, it allows to veto a suspend:
156 // if (x.await_suspend(...))
157 // llvm_coro_suspend();
159 // (**) llvm_coro_suspend() encodes three possible continuations as
160 // a switch instruction:
162 // %where-to = call i8 @llvm.coro.suspend(...)
163 // switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
164 // i8 0, label %yield.ready ; go here when resumed
165 // i8 1, label %yield.cleanup ; go here when destroyed
168 // See llvm's docs/Coroutines.rst for more details.
171 struct LValueOrRValue {
176 static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
177 CoroutineSuspendExpr const &S,
178 AwaitKind Kind, AggValueSlot aggSlot,
179 bool ignoreResult, bool forLValue) {
180 auto *E = S.getCommonExpr();
183 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
184 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
186 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
187 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
188 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
189 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
191 // If expression is ready, no need to suspend.
192 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
194 // Otherwise, emit suspend logic.
195 CGF.EmitBlock(SuspendBlock);
197 auto &Builder = CGF.Builder;
198 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
199 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
200 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
202 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
203 if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
204 // Veto suspension if requested by bool returning await_suspend.
205 BasicBlock *RealSuspendBlock =
206 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
207 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
208 SuspendBlock = RealSuspendBlock;
209 CGF.EmitBlock(RealSuspendBlock);
212 // Emit the suspend point.
213 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
214 llvm::Function *CoroSuspend =
215 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
216 auto *SuspendResult = Builder.CreateCall(
217 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
219 // Create a switch capturing three possible continuations.
220 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
221 Switch->addCase(Builder.getInt8(0), ReadyBlock);
222 Switch->addCase(Builder.getInt8(1), CleanupBlock);
224 // Emit cleanup for this suspend point.
225 CGF.EmitBlock(CleanupBlock);
226 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
228 // Emit await_resume expression.
229 CGF.EmitBlock(ReadyBlock);
231 // Exception handling requires additional IR. If the 'await_resume' function
232 // is marked as 'noexcept', we avoid generating this additional IR.
233 CXXTryStmt *TryStmt = nullptr;
234 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
235 memberCallExpressionCanThrow(S.getResumeExpr())) {
237 CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
238 Builder.CreateFlagStore(true, Coro.ResumeEHVar);
240 auto Loc = S.getResumeExpr()->getExprLoc();
241 auto *Catch = new (CGF.getContext())
242 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
244 CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(), Loc, Loc);
245 TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
246 CGF.EnterCXXTryStmt(*TryStmt);
251 Res.LV = CGF.EmitLValue(S.getResumeExpr());
253 Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
256 Builder.CreateFlagStore(false, Coro.ResumeEHVar);
257 CGF.ExitCXXTryStmt(*TryStmt);
263 RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
264 AggValueSlot aggSlot,
266 return emitSuspendExpression(*this, *CurCoro.Data, E,
267 CurCoro.Data->CurrentAwaitKind, aggSlot,
268 ignoreResult, /*forLValue*/false).RV;
270 RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
271 AggValueSlot aggSlot,
273 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
274 aggSlot, ignoreResult, /*forLValue*/false).RV;
277 void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
278 ++CurCoro.Data->CoreturnCount;
279 const Expr *RV = S.getOperand();
280 if (RV && RV->getType()->isVoidType()) {
281 // Make sure to evaluate the expression of a co_return with a void
282 // expression for side effects.
283 RunCleanupsScope cleanupScope(*this);
286 EmitStmt(S.getPromiseCall());
287 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
292 static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
293 const CoroutineSuspendExpr *E) {
294 const auto *RE = E->getResumeExpr();
295 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
297 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
298 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
303 CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
304 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
305 "Can't have a scalar return unless the return type is a "
307 return emitSuspendExpression(*this, *CurCoro.Data, *E,
308 CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
309 /*ignoreResult*/false, /*forLValue*/true).LV;
313 CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
314 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
315 "Can't have a scalar return unless the return type is a "
317 return emitSuspendExpression(*this, *CurCoro.Data, *E,
318 AwaitKind::Yield, AggValueSlot::ignored(),
319 /*ignoreResult*/false, /*forLValue*/true).LV;
322 // Hunts for the parameter reference in the parameter copy/move declaration.
324 struct GetParamRef : public StmtVisitor<GetParamRef> {
326 DeclRefExpr *Expr = nullptr;
328 void VisitDeclRefExpr(DeclRefExpr *E) {
329 assert(Expr == nullptr && "multilple declref in param move");
332 void VisitStmt(Stmt *S) {
333 for (auto *C : S->children()) {
341 // This class replaces references to parameters to their copies by changing
342 // the addresses in CGF.LocalDeclMap and restoring back the original values in
346 struct ParamReferenceReplacerRAII {
347 CodeGenFunction::DeclMapTy SavedLocals;
348 CodeGenFunction::DeclMapTy& LocalDeclMap;
350 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
351 : LocalDeclMap(LocalDeclMap) {}
353 void addCopy(DeclStmt const *PM) {
354 // Figure out what param it refers to.
356 assert(PM->isSingleDecl());
357 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
358 Expr const *InitExpr = VD->getInit();
360 Visitor.Visit(const_cast<Expr*>(InitExpr));
361 assert(Visitor.Expr);
362 DeclRefExpr *DREOrig = Visitor.Expr;
363 auto *PD = DREOrig->getDecl();
365 auto it = LocalDeclMap.find(PD);
366 assert(it != LocalDeclMap.end() && "parameter is not found");
367 SavedLocals.insert({ PD, it->second });
369 auto copyIt = LocalDeclMap.find(VD);
370 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
371 it->second = copyIt->getSecond();
374 ~ParamReferenceReplacerRAII() {
375 for (auto&& SavedLocal : SavedLocals) {
376 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
382 // For WinEH exception representation backend needs to know what funclet coro.end
383 // belongs to. That information is passed in a funclet bundle.
384 static SmallVector<llvm::OperandBundleDef, 1>
385 getBundlesForCoroEnd(CodeGenFunction &CGF) {
386 SmallVector<llvm::OperandBundleDef, 1> BundleList;
388 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
389 BundleList.emplace_back("funclet", EHPad);
395 // We will insert coro.end to cut any of the destructors for objects that
396 // do not need to be destroyed once the coroutine is resumed.
397 // See llvm/docs/Coroutines.rst for more details about coro.end.
398 struct CallCoroEnd final : public EHScopeStack::Cleanup {
399 void Emit(CodeGenFunction &CGF, Flags flags) override {
401 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
402 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
403 // See if we have a funclet bundle to associate coro.end with. (WinEH)
404 auto Bundles = getBundlesForCoroEnd(CGF);
405 auto *CoroEnd = CGF.Builder.CreateCall(
406 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
407 if (Bundles.empty()) {
408 // Otherwise, (landingpad model), create a conditional branch that leads
409 // either to a cleanup block or a block with EH resume instruction.
410 auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
411 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
412 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
413 CGF.EmitBlock(CleanupContBB);
420 // Make sure to call coro.delete on scope exit.
421 struct CallCoroDelete final : public EHScopeStack::Cleanup {
424 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
426 // Note: That deallocation will be emitted twice: once for a normal exit and
427 // once for exceptional exit. This usage is safe because Deallocate does not
428 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
429 // builds a single call to a deallocation function which is safe to emit
431 void Emit(CodeGenFunction &CGF, Flags) override {
432 // Remember the current point, as we are going to emit deallocation code
433 // first to get to coro.free instruction that is an argument to a delete
435 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
437 auto *FreeBB = CGF.createBasicBlock("coro.free");
438 CGF.EmitBlock(FreeBB);
439 CGF.EmitStmt(Deallocate);
441 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
442 CGF.EmitBlock(AfterFreeBB);
444 // We should have captured coro.free from the emission of deallocate.
445 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
447 CGF.CGM.Error(Deallocate->getBeginLoc(),
448 "Deallocation expressoin does not refer to coro.free");
452 // Get back to the block we were originally and move coro.free there.
453 auto *InsertPt = SaveInsertBlock->getTerminator();
454 CoroFree->moveBefore(InsertPt);
455 CGF.Builder.SetInsertPoint(InsertPt);
457 // Add if (auto *mem = coro.free) Deallocate;
458 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
459 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
460 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
462 // No longer need old terminator.
463 InsertPt->eraseFromParent();
464 CGF.Builder.SetInsertPoint(AfterFreeBB);
466 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
471 struct GetReturnObjectManager {
472 CodeGenFunction &CGF;
473 CGBuilderTy &Builder;
474 const CoroutineBodyStmt &S;
476 Address GroActiveFlag;
477 CodeGenFunction::AutoVarEmission GroEmission;
479 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
480 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
481 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
483 // The gro variable has to outlive coroutine frame and coroutine promise, but,
484 // it can only be initialized after coroutine promise was created, thus, we
485 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
486 // cleanups. Later when coroutine promise is available we initialize the gro
487 // and sets the flag that the cleanup is now active.
489 void EmitGroAlloca() {
490 auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
492 // If get_return_object returns void, no need to do an alloca.
496 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
498 // Set GRO flag that it is not initialized yet
500 CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
501 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
503 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
505 // Remember the top of EHStack before emitting the cleanup.
506 auto old_top = CGF.EHStack.stable_begin();
507 CGF.EmitAutoVarCleanups(GroEmission);
508 auto top = CGF.EHStack.stable_begin();
510 // Make the cleanup conditional on gro.active
511 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
513 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
514 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
515 Cleanup->setActiveFlag(GroActiveFlag);
516 Cleanup->setTestFlagInEHCleanup();
517 Cleanup->setTestFlagInNormalCleanup();
523 if (!GroActiveFlag.isValid()) {
524 // No Gro variable was allocated. Simply emit the call to
525 // get_return_object.
526 CGF.EmitStmt(S.getResultDecl());
530 CGF.EmitAutoVarInit(GroEmission);
531 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
536 static void emitBodyAndFallthrough(CodeGenFunction &CGF,
537 const CoroutineBodyStmt &S, Stmt *Body) {
539 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
541 if (Stmt *OnFallthrough = S.getFallthroughHandler())
542 CGF.EmitStmt(OnFallthrough);
545 void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
546 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
547 auto &TI = CGM.getContext().getTargetInfo();
548 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
550 auto *EntryBB = Builder.GetInsertBlock();
551 auto *AllocBB = createBasicBlock("coro.alloc");
552 auto *InitBB = createBasicBlock("coro.init");
553 auto *FinalBB = createBasicBlock("coro.final");
554 auto *RetBB = createBasicBlock("coro.ret");
556 auto *CoroId = Builder.CreateCall(
557 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
558 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
559 createCoroData(*this, CurCoro, CoroId);
560 CurCoro.Data->SuspendBB = RetBB;
562 // Backend is allowed to elide memory allocations, to help it, emit
563 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
564 auto *CoroAlloc = Builder.CreateCall(
565 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
567 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
570 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
571 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
573 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
574 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
575 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
577 // See if allocation was successful.
578 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
579 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
580 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
582 // If not, return OnAllocFailure object.
583 EmitBlock(RetOnFailureBB);
584 EmitStmt(RetOnAllocFailure);
587 Builder.CreateBr(InitBB);
592 // Pass the result of the allocation to coro.begin.
593 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
594 Phi->addIncoming(NullPtr, EntryBB);
595 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
596 auto *CoroBegin = Builder.CreateCall(
597 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
598 CurCoro.Data->CoroBegin = CoroBegin;
600 GetReturnObjectManager GroManager(*this, S);
601 GroManager.EmitGroAlloca();
603 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
605 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
606 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
607 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
609 // Create parameter copies. We do it before creating a promise, since an
610 // evolution of coroutine TS may allow promise constructor to observe
612 for (auto *PM : S.getParamMoves()) {
614 ParamReplacer.addCopy(cast<DeclStmt>(PM));
615 // TODO: if(CoroParam(...)) need to surround ctor and dtor
616 // for the copy, so that llvm can elide it if the copy is
620 EmitStmt(S.getPromiseDeclStmt());
622 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
623 auto *PromiseAddrVoidPtr =
624 new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
625 // Update CoroId to refer to the promise. We could not do it earlier because
626 // promise local variable was not emitted yet.
627 CoroId->setArgOperand(1, PromiseAddrVoidPtr);
629 // Now we have the promise, initialize the GRO
630 GroManager.EmitGroInit();
632 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
634 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
635 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
636 EmitStmt(S.getInitSuspendStmt());
637 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
639 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
641 if (CurCoro.Data->ExceptionHandler) {
642 // If we generated IR to record whether an exception was thrown from
643 // 'await_resume', then use that IR to determine whether the coroutine
644 // body should be skipped.
645 // If we didn't generate the IR (perhaps because 'await_resume' was marked
646 // as 'noexcept'), then we skip this check.
647 BasicBlock *ContBB = nullptr;
648 if (CurCoro.Data->ResumeEHVar) {
649 BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
650 ContBB = createBasicBlock("coro.resumed.cont");
651 Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
653 Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
657 auto Loc = S.getBeginLoc();
658 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
659 CurCoro.Data->ExceptionHandler);
661 CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
663 EnterCXXTryStmt(*TryStmt);
664 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
665 ExitCXXTryStmt(*TryStmt);
671 emitBodyAndFallthrough(*this, S, S.getBody());
674 // See if we need to generate final suspend.
675 const bool CanFallthrough = Builder.GetInsertBlock();
676 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
677 if (CanFallthrough || HasCoreturns) {
679 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
680 EmitStmt(S.getFinalSuspendStmt());
682 // We don't need FinalBB. Emit it to make sure the block is deleted.
683 EmitBlock(FinalBB, /*IsFinished=*/true);
688 // Emit coro.end before getReturnStmt (and parameter destructors), since
689 // resume and destroy parts of the coroutine should not include them.
690 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
691 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
693 if (Stmt *Ret = S.getReturnStmt())
697 // Emit coroutine intrinsic and patch up arguments of the token type.
698 RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
700 SmallVector<llvm::Value *, 8> Args;
704 // The coro.frame builtin is replaced with an SSA value of the coro.begin
706 case llvm::Intrinsic::coro_frame: {
707 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
708 return RValue::get(CurCoro.Data->CoroBegin);
710 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
711 "has been used earlier in this function");
712 auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
713 return RValue::get(NullPtr);
715 // The following three intrinsics take a token parameter referring to a token
716 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
717 // builtins, we patch it up here.
718 case llvm::Intrinsic::coro_alloc:
719 case llvm::Intrinsic::coro_begin:
720 case llvm::Intrinsic::coro_free: {
721 if (CurCoro.Data && CurCoro.Data->CoroId) {
722 Args.push_back(CurCoro.Data->CoroId);
725 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
726 " been used earlier in this function");
727 // Fallthrough to the next case to add TokenNone as the first argument.
730 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
732 case llvm::Intrinsic::coro_suspend:
733 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
736 for (auto &Arg : E->arguments())
737 Args.push_back(EmitScalarExpr(Arg));
739 llvm::Value *F = CGM.getIntrinsic(IID);
740 llvm::CallInst *Call = Builder.CreateCall(F, Args);
742 // Note: The following code is to enable to emit coro.id and coro.begin by
743 // hand to experiment with coroutines in C.
744 // If we see @llvm.coro.id remember it in the CoroData. We will update
745 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
746 if (IID == llvm::Intrinsic::coro_id) {
747 createCoroData(*this, CurCoro, Call, E);
749 else if (IID == llvm::Intrinsic::coro_begin) {
751 CurCoro.Data->CoroBegin = Call;
753 else if (IID == llvm::Intrinsic::coro_free) {
754 // Remember the last coro_free as we need it to build the conditional
755 // deletion of the coroutine frame.
757 CurCoro.Data->LastCoroFree = Call;
759 return RValue::get(Call);