1 //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with C++ code generation of coroutines.
11 //===----------------------------------------------------------------------===//
13 #include "CGCleanup.h"
14 #include "CodeGenFunction.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "clang/AST/StmtCXX.h"
17 #include "clang/AST/StmtVisitor.h"
19 using namespace clang
;
20 using namespace CodeGen
;
23 using llvm::BasicBlock
;
26 enum class AwaitKind
{ Init
, Normal
, Yield
, Final
};
27 static constexpr llvm::StringLiteral AwaitKindStr
[] = {"init", "await", "yield",
31 struct clang::CodeGen::CGCoroData
{
32 // What is the current await expression kind and how many
33 // await/yield expressions were encountered so far.
34 // These are used to generate pretty labels for await expressions in LLVM IR.
35 AwaitKind CurrentAwaitKind
= AwaitKind::Init
;
36 unsigned AwaitNum
= 0;
37 unsigned YieldNum
= 0;
39 // How many co_return statements are in the coroutine. Used to decide whether
40 // we need to add co_return; equivalent at the end of the user authored body.
41 unsigned CoreturnCount
= 0;
43 // A branch to this block is emitted when coroutine needs to suspend.
44 llvm::BasicBlock
*SuspendBB
= nullptr;
46 // The promise type's 'unhandled_exception' handler, if it defines one.
47 Stmt
*ExceptionHandler
= nullptr;
49 // A temporary i1 alloca that stores whether 'await_resume' threw an
50 // exception. If it did, 'true' is stored in this variable, and the coroutine
51 // body must be skipped. If the promise type does not define an exception
52 // handler, this is null.
53 llvm::Value
*ResumeEHVar
= nullptr;
55 // Stores the jump destination just before the coroutine memory is freed.
56 // This is the destination that every suspend point jumps to for the cleanup
58 CodeGenFunction::JumpDest CleanupJD
;
60 // Stores the jump destination just before the final suspend. The co_return
61 // statements jumps to this point after calling return_xxx promise member.
62 CodeGenFunction::JumpDest FinalJD
;
64 // Stores the llvm.coro.id emitted in the function so that we can supply it
65 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
66 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
68 llvm::CallInst
*CoroId
= nullptr;
70 // Stores the llvm.coro.begin emitted in the function so that we can replace
71 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
72 // the address of the coroutine frame of the current coroutine.
73 llvm::CallInst
*CoroBegin
= nullptr;
75 // Stores the last emitted coro.free for the deallocate expressions, we use it
76 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
77 llvm::CallInst
*LastCoroFree
= nullptr;
79 // If coro.id came from the builtin, remember the expression to give better
80 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
82 CallExpr
const *CoroIdExpr
= nullptr;
85 // Defining these here allows to keep CGCoroData private to this file.
86 clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
87 CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
89 static void createCoroData(CodeGenFunction
&CGF
,
90 CodeGenFunction::CGCoroInfo
&CurCoro
,
91 llvm::CallInst
*CoroId
,
92 CallExpr
const *CoroIdExpr
= nullptr) {
94 if (CurCoro
.Data
->CoroIdExpr
)
95 CGF
.CGM
.Error(CoroIdExpr
->getBeginLoc(),
96 "only one __builtin_coro_id can be used in a function");
98 CGF
.CGM
.Error(CoroIdExpr
->getBeginLoc(),
99 "__builtin_coro_id shall not be used in a C++ coroutine");
101 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
106 CurCoro
.Data
= std::unique_ptr
<CGCoroData
>(new CGCoroData
);
107 CurCoro
.Data
->CoroId
= CoroId
;
108 CurCoro
.Data
->CoroIdExpr
= CoroIdExpr
;
111 // Synthesize a pretty name for a suspend point.
112 static SmallString
<32> buildSuspendPrefixStr(CGCoroData
&Coro
, AwaitKind Kind
) {
115 case AwaitKind::Init
:
116 case AwaitKind::Final
:
118 case AwaitKind::Normal
:
119 No
= ++Coro
.AwaitNum
;
121 case AwaitKind::Yield
:
122 No
= ++Coro
.YieldNum
;
125 SmallString
<32> Prefix(AwaitKindStr
[static_cast<unsigned>(Kind
)]);
127 Twine(No
).toVector(Prefix
);
132 static bool memberCallExpressionCanThrow(const Expr
*E
) {
133 if (const auto *CE
= dyn_cast
<CXXMemberCallExpr
>(E
))
134 if (const auto *Proto
=
135 CE
->getMethodDecl()->getType()->getAs
<FunctionProtoType
>())
136 if (isNoexceptExceptionSpec(Proto
->getExceptionSpecType()) &&
137 Proto
->canThrow() == CT_Cannot
)
142 // Emit suspend expression which roughly looks like:
144 // auto && x = CommonExpr();
145 // if (!x.await_ready()) {
147 // x.await_suspend(...); (*)
148 // llvm_coro_suspend(); (**)
152 // where the result of the entire expression is the result of x.await_resume()
154 // (*) If x.await_suspend return type is bool, it allows to veto a suspend:
155 // if (x.await_suspend(...))
156 // llvm_coro_suspend();
158 // (**) llvm_coro_suspend() encodes three possible continuations as
159 // a switch instruction:
161 // %where-to = call i8 @llvm.coro.suspend(...)
162 // switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
163 // i8 0, label %yield.ready ; go here when resumed
164 // i8 1, label %yield.cleanup ; go here when destroyed
167 // See llvm's docs/Coroutines.rst for more details.
170 struct LValueOrRValue
{
175 static LValueOrRValue
emitSuspendExpression(CodeGenFunction
&CGF
, CGCoroData
&Coro
,
176 CoroutineSuspendExpr
const &S
,
177 AwaitKind Kind
, AggValueSlot aggSlot
,
178 bool ignoreResult
, bool forLValue
) {
179 auto *E
= S
.getCommonExpr();
182 CodeGenFunction::OpaqueValueMappingData::bind(CGF
, S
.getOpaqueValue(), E
);
183 auto UnbindOnExit
= llvm::make_scope_exit([&] { Binder
.unbind(CGF
); });
185 auto Prefix
= buildSuspendPrefixStr(Coro
, Kind
);
186 BasicBlock
*ReadyBlock
= CGF
.createBasicBlock(Prefix
+ Twine(".ready"));
187 BasicBlock
*SuspendBlock
= CGF
.createBasicBlock(Prefix
+ Twine(".suspend"));
188 BasicBlock
*CleanupBlock
= CGF
.createBasicBlock(Prefix
+ Twine(".cleanup"));
190 // If expression is ready, no need to suspend.
191 CGF
.EmitBranchOnBoolExpr(S
.getReadyExpr(), ReadyBlock
, SuspendBlock
, 0);
193 // Otherwise, emit suspend logic.
194 CGF
.EmitBlock(SuspendBlock
);
196 auto &Builder
= CGF
.Builder
;
197 llvm::Function
*CoroSave
= CGF
.CGM
.getIntrinsic(llvm::Intrinsic::coro_save
);
198 auto *NullPtr
= llvm::ConstantPointerNull::get(CGF
.CGM
.Int8PtrTy
);
199 auto *SaveCall
= Builder
.CreateCall(CoroSave
, {NullPtr
});
201 CGF
.CurCoro
.InSuspendBlock
= true;
202 auto *SuspendRet
= CGF
.EmitScalarExpr(S
.getSuspendExpr());
203 CGF
.CurCoro
.InSuspendBlock
= false;
205 if (SuspendRet
!= nullptr && SuspendRet
->getType()->isIntegerTy(1)) {
206 // Veto suspension if requested by bool returning await_suspend.
207 BasicBlock
*RealSuspendBlock
=
208 CGF
.createBasicBlock(Prefix
+ Twine(".suspend.bool"));
209 CGF
.Builder
.CreateCondBr(SuspendRet
, RealSuspendBlock
, ReadyBlock
);
210 CGF
.EmitBlock(RealSuspendBlock
);
213 // Emit the suspend point.
214 const bool IsFinalSuspend
= (Kind
== AwaitKind::Final
);
215 llvm::Function
*CoroSuspend
=
216 CGF
.CGM
.getIntrinsic(llvm::Intrinsic::coro_suspend
);
217 auto *SuspendResult
= Builder
.CreateCall(
218 CoroSuspend
, {SaveCall
, Builder
.getInt1(IsFinalSuspend
)});
220 // Create a switch capturing three possible continuations.
221 auto *Switch
= Builder
.CreateSwitch(SuspendResult
, Coro
.SuspendBB
, 2);
222 Switch
->addCase(Builder
.getInt8(0), ReadyBlock
);
223 Switch
->addCase(Builder
.getInt8(1), CleanupBlock
);
225 // Emit cleanup for this suspend point.
226 CGF
.EmitBlock(CleanupBlock
);
227 CGF
.EmitBranchThroughCleanup(Coro
.CleanupJD
);
229 // Emit await_resume expression.
230 CGF
.EmitBlock(ReadyBlock
);
232 // Exception handling requires additional IR. If the 'await_resume' function
233 // is marked as 'noexcept', we avoid generating this additional IR.
234 CXXTryStmt
*TryStmt
= nullptr;
235 if (Coro
.ExceptionHandler
&& Kind
== AwaitKind::Init
&&
236 memberCallExpressionCanThrow(S
.getResumeExpr())) {
238 CGF
.CreateTempAlloca(Builder
.getInt1Ty(), Prefix
+ Twine("resume.eh"));
239 Builder
.CreateFlagStore(true, Coro
.ResumeEHVar
);
241 auto Loc
= S
.getResumeExpr()->getExprLoc();
242 auto *Catch
= new (CGF
.getContext())
243 CXXCatchStmt(Loc
, /*exDecl=*/nullptr, Coro
.ExceptionHandler
);
244 auto *TryBody
= CompoundStmt::Create(CGF
.getContext(), S
.getResumeExpr(),
245 FPOptionsOverride(), Loc
, Loc
);
246 TryStmt
= CXXTryStmt::Create(CGF
.getContext(), Loc
, TryBody
, Catch
);
247 CGF
.EnterCXXTryStmt(*TryStmt
);
252 Res
.LV
= CGF
.EmitLValue(S
.getResumeExpr());
254 Res
.RV
= CGF
.EmitAnyExpr(S
.getResumeExpr(), aggSlot
, ignoreResult
);
257 Builder
.CreateFlagStore(false, Coro
.ResumeEHVar
);
258 CGF
.ExitCXXTryStmt(*TryStmt
);
264 RValue
CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr
&E
,
265 AggValueSlot aggSlot
,
267 return emitSuspendExpression(*this, *CurCoro
.Data
, E
,
268 CurCoro
.Data
->CurrentAwaitKind
, aggSlot
,
269 ignoreResult
, /*forLValue*/false).RV
;
271 RValue
CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr
&E
,
272 AggValueSlot aggSlot
,
274 return emitSuspendExpression(*this, *CurCoro
.Data
, E
, AwaitKind::Yield
,
275 aggSlot
, ignoreResult
, /*forLValue*/false).RV
;
278 void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt
const &S
) {
279 ++CurCoro
.Data
->CoreturnCount
;
280 const Expr
*RV
= S
.getOperand();
281 if (RV
&& RV
->getType()->isVoidType() && !isa
<InitListExpr
>(RV
)) {
282 // Make sure to evaluate the non initlist expression of a co_return
283 // with a void expression for side effects.
284 RunCleanupsScope
cleanupScope(*this);
287 EmitStmt(S
.getPromiseCall());
288 EmitBranchThroughCleanup(CurCoro
.Data
->FinalJD
);
293 static QualType
getCoroutineSuspendExprReturnType(const ASTContext
&Ctx
,
294 const CoroutineSuspendExpr
*E
) {
295 const auto *RE
= E
->getResumeExpr();
296 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
298 assert(isa
<CallExpr
>(RE
) && "unexpected suspend expression type");
299 return cast
<CallExpr
>(RE
)->getCallReturnType(Ctx
);
304 CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr
*E
) {
305 assert(getCoroutineSuspendExprReturnType(getContext(), E
)->isReferenceType() &&
306 "Can't have a scalar return unless the return type is a "
308 return emitSuspendExpression(*this, *CurCoro
.Data
, *E
,
309 CurCoro
.Data
->CurrentAwaitKind
, AggValueSlot::ignored(),
310 /*ignoreResult*/false, /*forLValue*/true).LV
;
314 CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr
*E
) {
315 assert(getCoroutineSuspendExprReturnType(getContext(), E
)->isReferenceType() &&
316 "Can't have a scalar return unless the return type is a "
318 return emitSuspendExpression(*this, *CurCoro
.Data
, *E
,
319 AwaitKind::Yield
, AggValueSlot::ignored(),
320 /*ignoreResult*/false, /*forLValue*/true).LV
;
323 // Hunts for the parameter reference in the parameter copy/move declaration.
325 struct GetParamRef
: public StmtVisitor
<GetParamRef
> {
327 DeclRefExpr
*Expr
= nullptr;
329 void VisitDeclRefExpr(DeclRefExpr
*E
) {
330 assert(Expr
== nullptr && "multilple declref in param move");
333 void VisitStmt(Stmt
*S
) {
334 for (auto *C
: S
->children()) {
342 // This class replaces references to parameters to their copies by changing
343 // the addresses in CGF.LocalDeclMap and restoring back the original values in
347 struct ParamReferenceReplacerRAII
{
348 CodeGenFunction::DeclMapTy SavedLocals
;
349 CodeGenFunction::DeclMapTy
& LocalDeclMap
;
351 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy
&LocalDeclMap
)
352 : LocalDeclMap(LocalDeclMap
) {}
354 void addCopy(DeclStmt
const *PM
) {
355 // Figure out what param it refers to.
357 assert(PM
->isSingleDecl());
358 VarDecl
const*VD
= static_cast<VarDecl
const*>(PM
->getSingleDecl());
359 Expr
const *InitExpr
= VD
->getInit();
361 Visitor
.Visit(const_cast<Expr
*>(InitExpr
));
362 assert(Visitor
.Expr
);
363 DeclRefExpr
*DREOrig
= Visitor
.Expr
;
364 auto *PD
= DREOrig
->getDecl();
366 auto it
= LocalDeclMap
.find(PD
);
367 assert(it
!= LocalDeclMap
.end() && "parameter is not found");
368 SavedLocals
.insert({ PD
, it
->second
});
370 auto copyIt
= LocalDeclMap
.find(VD
);
371 assert(copyIt
!= LocalDeclMap
.end() && "parameter copy is not found");
372 it
->second
= copyIt
->getSecond();
375 ~ParamReferenceReplacerRAII() {
376 for (auto&& SavedLocal
: SavedLocals
) {
377 LocalDeclMap
.insert({SavedLocal
.first
, SavedLocal
.second
});
383 // For WinEH exception representation backend needs to know what funclet coro.end
384 // belongs to. That information is passed in a funclet bundle.
385 static SmallVector
<llvm::OperandBundleDef
, 1>
386 getBundlesForCoroEnd(CodeGenFunction
&CGF
) {
387 SmallVector
<llvm::OperandBundleDef
, 1> BundleList
;
389 if (llvm::Instruction
*EHPad
= CGF
.CurrentFuncletPad
)
390 BundleList
.emplace_back("funclet", EHPad
);
396 // We will insert coro.end to cut any of the destructors for objects that
397 // do not need to be destroyed once the coroutine is resumed.
398 // See llvm/docs/Coroutines.rst for more details about coro.end.
399 struct CallCoroEnd final
: public EHScopeStack::Cleanup
{
400 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
402 auto *NullPtr
= llvm::ConstantPointerNull::get(CGF
.Int8PtrTy
);
403 llvm::Function
*CoroEndFn
= CGM
.getIntrinsic(llvm::Intrinsic::coro_end
);
404 // See if we have a funclet bundle to associate coro.end with. (WinEH)
405 auto Bundles
= getBundlesForCoroEnd(CGF
);
407 CGF
.Builder
.CreateCall(CoroEndFn
,
408 {NullPtr
, CGF
.Builder
.getTrue(),
409 llvm::ConstantTokenNone::get(CoroEndFn
->getContext())},
411 if (Bundles
.empty()) {
412 // Otherwise, (landingpad model), create a conditional branch that leads
413 // either to a cleanup block or a block with EH resume instruction.
414 auto *ResumeBB
= CGF
.getEHResumeBlock(/*isCleanup=*/true);
415 auto *CleanupContBB
= CGF
.createBasicBlock("cleanup.cont");
416 CGF
.Builder
.CreateCondBr(CoroEnd
, ResumeBB
, CleanupContBB
);
417 CGF
.EmitBlock(CleanupContBB
);
424 // Make sure to call coro.delete on scope exit.
425 struct CallCoroDelete final
: public EHScopeStack::Cleanup
{
428 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
430 // Note: That deallocation will be emitted twice: once for a normal exit and
431 // once for exceptional exit. This usage is safe because Deallocate does not
432 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
433 // builds a single call to a deallocation function which is safe to emit
435 void Emit(CodeGenFunction
&CGF
, Flags
) override
{
436 // Remember the current point, as we are going to emit deallocation code
437 // first to get to coro.free instruction that is an argument to a delete
439 BasicBlock
*SaveInsertBlock
= CGF
.Builder
.GetInsertBlock();
441 auto *FreeBB
= CGF
.createBasicBlock("coro.free");
442 CGF
.EmitBlock(FreeBB
);
443 CGF
.EmitStmt(Deallocate
);
445 auto *AfterFreeBB
= CGF
.createBasicBlock("after.coro.free");
446 CGF
.EmitBlock(AfterFreeBB
);
448 // We should have captured coro.free from the emission of deallocate.
449 auto *CoroFree
= CGF
.CurCoro
.Data
->LastCoroFree
;
451 CGF
.CGM
.Error(Deallocate
->getBeginLoc(),
452 "Deallocation expressoin does not refer to coro.free");
456 // Get back to the block we were originally and move coro.free there.
457 auto *InsertPt
= SaveInsertBlock
->getTerminator();
458 CoroFree
->moveBefore(InsertPt
);
459 CGF
.Builder
.SetInsertPoint(InsertPt
);
461 // Add if (auto *mem = coro.free) Deallocate;
462 auto *NullPtr
= llvm::ConstantPointerNull::get(CGF
.Int8PtrTy
);
463 auto *Cond
= CGF
.Builder
.CreateICmpNE(CoroFree
, NullPtr
);
464 CGF
.Builder
.CreateCondBr(Cond
, FreeBB
, AfterFreeBB
);
466 // No longer need old terminator.
467 InsertPt
->eraseFromParent();
468 CGF
.Builder
.SetInsertPoint(AfterFreeBB
);
470 explicit CallCoroDelete(Stmt
*DeallocStmt
) : Deallocate(DeallocStmt
) {}
475 struct GetReturnObjectManager
{
476 CodeGenFunction
&CGF
;
477 CGBuilderTy
&Builder
;
478 const CoroutineBodyStmt
&S
;
479 // When true, performs RVO for the return object.
480 bool DirectEmit
= false;
482 Address GroActiveFlag
;
483 CodeGenFunction::AutoVarEmission GroEmission
;
485 GetReturnObjectManager(CodeGenFunction
&CGF
, const CoroutineBodyStmt
&S
)
486 : CGF(CGF
), Builder(CGF
.Builder
), S(S
), GroActiveFlag(Address::invalid()),
487 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
488 // The call to get_Âreturn_Âobject is sequenced before the call to
489 // initial_Âsuspend and is invoked at most once, but there are caveats
490 // regarding on whether the prvalue result object may be initialized
491 // directly/eager or delayed, depending on the types involved.
493 // More info at https://github.com/cplusplus/papers/issues/1414
495 // The general cases:
496 // 1. Same type of get_return_object and coroutine return type (direct
498 // - Constructed in the return slot.
499 // 2. Different types (delayed emission):
500 // - Constructed temporary object prior to initial suspend initialized with
501 // a call to get_return_object()
502 // - When coroutine needs to to return to the caller and needs to construct
503 // return value for the coroutine it is initialized with expiring value of
504 // the temporary obtained above.
506 // Direct emission for void returning coroutines or GROs.
508 auto *RVI
= S
.getReturnValueInit();
509 assert(RVI
&& "expected RVI");
510 auto GroType
= RVI
->getType();
511 return CGF
.getContext().hasSameType(GroType
, CGF
.FnRetTy
);
515 // The gro variable has to outlive coroutine frame and coroutine promise, but,
516 // it can only be initialized after coroutine promise was created, thus, we
517 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
518 // cleanups. Later when coroutine promise is available we initialize the gro
519 // and sets the flag that the cleanup is now active.
520 void EmitGroAlloca() {
524 auto *GroDeclStmt
= dyn_cast_or_null
<DeclStmt
>(S
.getResultDecl());
526 // If get_return_object returns void, no need to do an alloca.
530 auto *GroVarDecl
= cast
<VarDecl
>(GroDeclStmt
->getSingleDecl());
532 // Set GRO flag that it is not initialized yet
533 GroActiveFlag
= CGF
.CreateTempAlloca(Builder
.getInt1Ty(), CharUnits::One(),
535 Builder
.CreateStore(Builder
.getFalse(), GroActiveFlag
);
537 GroEmission
= CGF
.EmitAutoVarAlloca(*GroVarDecl
);
538 auto *GroAlloca
= dyn_cast_or_null
<llvm::AllocaInst
>(
539 GroEmission
.getOriginalAllocatedAddress().getPointer());
540 assert(GroAlloca
&& "expected alloca to be emitted");
541 GroAlloca
->setMetadata(llvm::LLVMContext::MD_coro_outside_frame
,
542 llvm::MDNode::get(CGF
.CGM
.getLLVMContext(), {}));
544 // Remember the top of EHStack before emitting the cleanup.
545 auto old_top
= CGF
.EHStack
.stable_begin();
546 CGF
.EmitAutoVarCleanups(GroEmission
);
547 auto top
= CGF
.EHStack
.stable_begin();
549 // Make the cleanup conditional on gro.active
550 for (auto b
= CGF
.EHStack
.find(top
), e
= CGF
.EHStack
.find(old_top
); b
!= e
;
552 if (auto *Cleanup
= dyn_cast
<EHCleanupScope
>(&*b
)) {
553 assert(!Cleanup
->hasActiveFlag() && "cleanup already has active flag?");
554 Cleanup
->setActiveFlag(GroActiveFlag
);
555 Cleanup
->setTestFlagInEHCleanup();
556 Cleanup
->setTestFlagInNormalCleanup();
563 // ReturnValue should be valid as long as the coroutine's return type
564 // is not void. The assertion could help us to reduce the check later.
565 assert(CGF
.ReturnValue
.isValid() == (bool)S
.getReturnStmt());
566 // Now we have the promise, initialize the GRO.
567 // We need to emit `get_return_object` first. According to:
568 // [dcl.fct.def.coroutine]p7
569 // The call to get_return_Âobject is sequenced before the call to
570 // initial_suspend and is invoked at most once.
572 // So we couldn't emit return value when we emit return statment,
573 // otherwise the call to get_return_object wouldn't be in front
574 // of initial_suspend.
575 if (CGF
.ReturnValue
.isValid()) {
576 CGF
.EmitAnyExprToMem(S
.getReturnValue(), CGF
.ReturnValue
,
577 S
.getReturnValue()->getType().getQualifiers(),
583 if (!GroActiveFlag
.isValid()) {
584 // No Gro variable was allocated. Simply emit the call to
585 // get_return_object.
586 CGF
.EmitStmt(S
.getResultDecl());
590 CGF
.EmitAutoVarInit(GroEmission
);
591 Builder
.CreateStore(Builder
.getTrue(), GroActiveFlag
);
596 static void emitBodyAndFallthrough(CodeGenFunction
&CGF
,
597 const CoroutineBodyStmt
&S
, Stmt
*Body
) {
599 const bool CanFallthrough
= CGF
.Builder
.GetInsertBlock();
601 if (Stmt
*OnFallthrough
= S
.getFallthroughHandler())
602 CGF
.EmitStmt(OnFallthrough
);
605 void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt
&S
) {
606 auto *NullPtr
= llvm::ConstantPointerNull::get(Builder
.getPtrTy());
607 auto &TI
= CGM
.getContext().getTargetInfo();
608 unsigned NewAlign
= TI
.getNewAlign() / TI
.getCharWidth();
610 auto *EntryBB
= Builder
.GetInsertBlock();
611 auto *AllocBB
= createBasicBlock("coro.alloc");
612 auto *InitBB
= createBasicBlock("coro.init");
613 auto *FinalBB
= createBasicBlock("coro.final");
614 auto *RetBB
= createBasicBlock("coro.ret");
616 auto *CoroId
= Builder
.CreateCall(
617 CGM
.getIntrinsic(llvm::Intrinsic::coro_id
),
618 {Builder
.getInt32(NewAlign
), NullPtr
, NullPtr
, NullPtr
});
619 createCoroData(*this, CurCoro
, CoroId
);
620 CurCoro
.Data
->SuspendBB
= RetBB
;
621 assert(ShouldEmitLifetimeMarkers
&&
622 "Must emit lifetime intrinsics for coroutines");
624 // Backend is allowed to elide memory allocations, to help it, emit
625 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
626 auto *CoroAlloc
= Builder
.CreateCall(
627 CGM
.getIntrinsic(llvm::Intrinsic::coro_alloc
), {CoroId
});
629 Builder
.CreateCondBr(CoroAlloc
, AllocBB
, InitBB
);
632 auto *AllocateCall
= EmitScalarExpr(S
.getAllocate());
633 auto *AllocOrInvokeContBB
= Builder
.GetInsertBlock();
635 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
636 if (auto *RetOnAllocFailure
= S
.getReturnStmtOnAllocFailure()) {
637 auto *RetOnFailureBB
= createBasicBlock("coro.ret.on.failure");
639 // See if allocation was successful.
640 auto *NullPtr
= llvm::ConstantPointerNull::get(Int8PtrTy
);
641 auto *Cond
= Builder
.CreateICmpNE(AllocateCall
, NullPtr
);
642 // Expect the allocation to be successful.
643 emitCondLikelihoodViaExpectIntrinsic(Cond
, Stmt::LH_Likely
);
644 Builder
.CreateCondBr(Cond
, InitBB
, RetOnFailureBB
);
646 // If not, return OnAllocFailure object.
647 EmitBlock(RetOnFailureBB
);
648 EmitStmt(RetOnAllocFailure
);
651 Builder
.CreateBr(InitBB
);
656 // Pass the result of the allocation to coro.begin.
657 auto *Phi
= Builder
.CreatePHI(VoidPtrTy
, 2);
658 Phi
->addIncoming(NullPtr
, EntryBB
);
659 Phi
->addIncoming(AllocateCall
, AllocOrInvokeContBB
);
660 auto *CoroBegin
= Builder
.CreateCall(
661 CGM
.getIntrinsic(llvm::Intrinsic::coro_begin
), {CoroId
, Phi
});
662 CurCoro
.Data
->CoroBegin
= CoroBegin
;
664 GetReturnObjectManager
GroManager(*this, S
);
665 GroManager
.EmitGroAlloca();
667 CurCoro
.Data
->CleanupJD
= getJumpDestInCurrentScope(RetBB
);
669 CGDebugInfo
*DI
= getDebugInfo();
670 ParamReferenceReplacerRAII
ParamReplacer(LocalDeclMap
);
671 CodeGenFunction::RunCleanupsScope
ResumeScope(*this);
672 EHStack
.pushCleanup
<CallCoroDelete
>(NormalAndEHCleanup
, S
.getDeallocate());
674 // Create mapping between parameters and copy-params for coroutine function.
675 llvm::ArrayRef
<const Stmt
*> ParamMoves
= S
.getParamMoves();
677 (ParamMoves
.size() == 0 || (ParamMoves
.size() == FnArgs
.size())) &&
678 "ParamMoves and FnArgs should be the same size for coroutine function");
679 if (ParamMoves
.size() == FnArgs
.size() && DI
)
680 for (const auto Pair
: llvm::zip(FnArgs
, ParamMoves
))
681 DI
->getCoroutineParameterMappings().insert(
682 {std::get
<0>(Pair
), std::get
<1>(Pair
)});
684 // Create parameter copies. We do it before creating a promise, since an
685 // evolution of coroutine TS may allow promise constructor to observe
687 for (auto *PM
: S
.getParamMoves()) {
689 ParamReplacer
.addCopy(cast
<DeclStmt
>(PM
));
690 // TODO: if(CoroParam(...)) need to surround ctor and dtor
691 // for the copy, so that llvm can elide it if the copy is
695 EmitStmt(S
.getPromiseDeclStmt());
697 Address PromiseAddr
= GetAddrOfLocalVar(S
.getPromiseDecl());
698 auto *PromiseAddrVoidPtr
=
699 new llvm::BitCastInst(PromiseAddr
.getPointer(), VoidPtrTy
, "", CoroId
);
700 // Update CoroId to refer to the promise. We could not do it earlier because
701 // promise local variable was not emitted yet.
702 CoroId
->setArgOperand(1, PromiseAddrVoidPtr
);
704 // Now we have the promise, initialize the GRO
705 GroManager
.EmitGroInit();
707 EHStack
.pushCleanup
<CallCoroEnd
>(EHCleanup
);
709 CurCoro
.Data
->CurrentAwaitKind
= AwaitKind::Init
;
710 CurCoro
.Data
->ExceptionHandler
= S
.getExceptionHandler();
711 EmitStmt(S
.getInitSuspendStmt());
712 CurCoro
.Data
->FinalJD
= getJumpDestInCurrentScope(FinalBB
);
714 CurCoro
.Data
->CurrentAwaitKind
= AwaitKind::Normal
;
716 if (CurCoro
.Data
->ExceptionHandler
) {
717 // If we generated IR to record whether an exception was thrown from
718 // 'await_resume', then use that IR to determine whether the coroutine
719 // body should be skipped.
720 // If we didn't generate the IR (perhaps because 'await_resume' was marked
721 // as 'noexcept'), then we skip this check.
722 BasicBlock
*ContBB
= nullptr;
723 if (CurCoro
.Data
->ResumeEHVar
) {
724 BasicBlock
*BodyBB
= createBasicBlock("coro.resumed.body");
725 ContBB
= createBasicBlock("coro.resumed.cont");
726 Value
*SkipBody
= Builder
.CreateFlagLoad(CurCoro
.Data
->ResumeEHVar
,
728 Builder
.CreateCondBr(SkipBody
, ContBB
, BodyBB
);
732 auto Loc
= S
.getBeginLoc();
733 CXXCatchStmt
Catch(Loc
, /*exDecl=*/nullptr,
734 CurCoro
.Data
->ExceptionHandler
);
736 CXXTryStmt::Create(getContext(), Loc
, S
.getBody(), &Catch
);
738 EnterCXXTryStmt(*TryStmt
);
739 emitBodyAndFallthrough(*this, S
, TryStmt
->getTryBlock());
740 ExitCXXTryStmt(*TryStmt
);
746 emitBodyAndFallthrough(*this, S
, S
.getBody());
749 // See if we need to generate final suspend.
750 const bool CanFallthrough
= Builder
.GetInsertBlock();
751 const bool HasCoreturns
= CurCoro
.Data
->CoreturnCount
> 0;
752 if (CanFallthrough
|| HasCoreturns
) {
754 CurCoro
.Data
->CurrentAwaitKind
= AwaitKind::Final
;
755 EmitStmt(S
.getFinalSuspendStmt());
757 // We don't need FinalBB. Emit it to make sure the block is deleted.
758 EmitBlock(FinalBB
, /*IsFinished=*/true);
763 // Emit coro.end before getReturnStmt (and parameter destructors), since
764 // resume and destroy parts of the coroutine should not include them.
765 llvm::Function
*CoroEnd
= CGM
.getIntrinsic(llvm::Intrinsic::coro_end
);
766 Builder
.CreateCall(CoroEnd
,
767 {NullPtr
, Builder
.getFalse(),
768 llvm::ConstantTokenNone::get(CoroEnd
->getContext())});
770 if (Stmt
*Ret
= S
.getReturnStmt()) {
771 // Since we already emitted the return value above, so we shouldn't
772 // emit it again here.
773 if (GroManager
.DirectEmit
)
774 cast
<ReturnStmt
>(Ret
)->setRetValue(nullptr);
778 // LLVM require the frontend to mark the coroutine.
779 CurFn
->setPresplitCoroutine();
782 // Emit coroutine intrinsic and patch up arguments of the token type.
783 RValue
CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr
*E
,
785 SmallVector
<llvm::Value
*, 8> Args
;
789 // The coro.frame builtin is replaced with an SSA value of the coro.begin
791 case llvm::Intrinsic::coro_frame
: {
792 if (CurCoro
.Data
&& CurCoro
.Data
->CoroBegin
) {
793 return RValue::get(CurCoro
.Data
->CoroBegin
);
795 CGM
.Error(E
->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
796 "has been used earlier in this function");
797 auto *NullPtr
= llvm::ConstantPointerNull::get(Builder
.getPtrTy());
798 return RValue::get(NullPtr
);
800 case llvm::Intrinsic::coro_size
: {
801 auto &Context
= getContext();
802 CanQualType SizeTy
= Context
.getSizeType();
803 llvm::IntegerType
*T
= Builder
.getIntNTy(Context
.getTypeSize(SizeTy
));
804 llvm::Function
*F
= CGM
.getIntrinsic(llvm::Intrinsic::coro_size
, T
);
805 return RValue::get(Builder
.CreateCall(F
));
807 case llvm::Intrinsic::coro_align
: {
808 auto &Context
= getContext();
809 CanQualType SizeTy
= Context
.getSizeType();
810 llvm::IntegerType
*T
= Builder
.getIntNTy(Context
.getTypeSize(SizeTy
));
811 llvm::Function
*F
= CGM
.getIntrinsic(llvm::Intrinsic::coro_align
, T
);
812 return RValue::get(Builder
.CreateCall(F
));
814 // The following three intrinsics take a token parameter referring to a token
815 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
816 // builtins, we patch it up here.
817 case llvm::Intrinsic::coro_alloc
:
818 case llvm::Intrinsic::coro_begin
:
819 case llvm::Intrinsic::coro_free
: {
820 if (CurCoro
.Data
&& CurCoro
.Data
->CoroId
) {
821 Args
.push_back(CurCoro
.Data
->CoroId
);
824 CGM
.Error(E
->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
825 " been used earlier in this function");
826 // Fallthrough to the next case to add TokenNone as the first argument.
829 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
831 case llvm::Intrinsic::coro_suspend
:
832 Args
.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
835 for (const Expr
*Arg
: E
->arguments())
836 Args
.push_back(EmitScalarExpr(Arg
));
837 // @llvm.coro.end takes a token parameter. Add token 'none' as the last
839 if (IID
== llvm::Intrinsic::coro_end
)
840 Args
.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
842 llvm::Function
*F
= CGM
.getIntrinsic(IID
);
843 llvm::CallInst
*Call
= Builder
.CreateCall(F
, Args
);
845 // Note: The following code is to enable to emit coro.id and coro.begin by
846 // hand to experiment with coroutines in C.
847 // If we see @llvm.coro.id remember it in the CoroData. We will update
848 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
849 if (IID
== llvm::Intrinsic::coro_id
) {
850 createCoroData(*this, CurCoro
, Call
, E
);
852 else if (IID
== llvm::Intrinsic::coro_begin
) {
854 CurCoro
.Data
->CoroBegin
= Call
;
856 else if (IID
== llvm::Intrinsic::coro_free
) {
857 // Remember the last coro_free as we need it to build the conditional
858 // deletion of the coroutine frame.
860 CurCoro
.Data
->LastCoroFree
= Call
;
862 return RValue::get(Call
);