Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp
35234 views
//===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code dealing with C++ code generation of coroutines.9//10//===----------------------------------------------------------------------===//1112#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"1718using namespace clang;19using namespace CodeGen;2021using llvm::Value;22using llvm::BasicBlock;2324namespace {25enum class AwaitKind { Init, Normal, Yield, Final };26static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",27"final"};28}2930struct clang::CodeGen::CGCoroData {31// What is the current await expression kind and how many32// await/yield expressions were encountered so far.33// These are used to generate pretty labels for await expressions in LLVM IR.34AwaitKind CurrentAwaitKind = AwaitKind::Init;35unsigned AwaitNum = 0;36unsigned YieldNum = 0;3738// How many co_return statements are in the coroutine. Used to decide whether39// we need to add co_return; equivalent at the end of the user authored body.40unsigned CoreturnCount = 0;4142// A branch to this block is emitted when coroutine needs to suspend.43llvm::BasicBlock *SuspendBB = nullptr;4445// The promise type's 'unhandled_exception' handler, if it defines one.46Stmt *ExceptionHandler = nullptr;4748// A temporary i1 alloca that stores whether 'await_resume' threw an49// exception. If it did, 'true' is stored in this variable, and the coroutine50// body must be skipped. If the promise type does not define an exception51// handler, this is null.52llvm::Value *ResumeEHVar = nullptr;5354// Stores the jump destination just before the coroutine memory is freed.55// This is the destination that every suspend point jumps to for the cleanup56// branch.57CodeGenFunction::JumpDest CleanupJD;5859// Stores the jump destination just before the final suspend. The co_return60// statements jumps to this point after calling return_xxx promise member.61CodeGenFunction::JumpDest FinalJD;6263// Stores the llvm.coro.id emitted in the function so that we can supply it64// as the first argument to coro.begin, coro.alloc and coro.free intrinsics.65// Note: llvm.coro.id returns a token that cannot be directly expressed in a66// builtin.67llvm::CallInst *CoroId = nullptr;6869// Stores the llvm.coro.begin emitted in the function so that we can replace70// all coro.frame intrinsics with direct SSA value of coro.begin that returns71// the address of the coroutine frame of the current coroutine.72llvm::CallInst *CoroBegin = nullptr;7374// Stores the last emitted coro.free for the deallocate expressions, we use it75// to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).76llvm::CallInst *LastCoroFree = nullptr;7778// If coro.id came from the builtin, remember the expression to give better79// diagnostic. If CoroIdExpr is nullptr, the coro.id was created by80// EmitCoroutineBody.81CallExpr const *CoroIdExpr = nullptr;82};8384// Defining these here allows to keep CGCoroData private to this file.85clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}86CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}8788static void createCoroData(CodeGenFunction &CGF,89CodeGenFunction::CGCoroInfo &CurCoro,90llvm::CallInst *CoroId,91CallExpr const *CoroIdExpr = nullptr) {92if (CurCoro.Data) {93if (CurCoro.Data->CoroIdExpr)94CGF.CGM.Error(CoroIdExpr->getBeginLoc(),95"only one __builtin_coro_id can be used in a function");96else if (CoroIdExpr)97CGF.CGM.Error(CoroIdExpr->getBeginLoc(),98"__builtin_coro_id shall not be used in a C++ coroutine");99else100llvm_unreachable("EmitCoroutineBodyStatement called twice?");101102return;103}104105CurCoro.Data = std::make_unique<CGCoroData>();106CurCoro.Data->CoroId = CoroId;107CurCoro.Data->CoroIdExpr = CoroIdExpr;108}109110// Synthesize a pretty name for a suspend point.111static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {112unsigned No = 0;113switch (Kind) {114case AwaitKind::Init:115case AwaitKind::Final:116break;117case AwaitKind::Normal:118No = ++Coro.AwaitNum;119break;120case AwaitKind::Yield:121No = ++Coro.YieldNum;122break;123}124SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);125if (No > 1) {126Twine(No).toVector(Prefix);127}128return Prefix;129}130131// Check if function can throw based on prototype noexcept, also works for132// destructors which are implicitly noexcept but can be marked noexcept(false).133static bool FunctionCanThrow(const FunctionDecl *D) {134const auto *Proto = D->getType()->getAs<FunctionProtoType>();135if (!Proto) {136// Function proto is not found, we conservatively assume throwing.137return true;138}139return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||140Proto->canThrow() != CT_Cannot;141}142143static bool StmtCanThrow(const Stmt *S) {144if (const auto *CE = dyn_cast<CallExpr>(S)) {145const auto *Callee = CE->getDirectCallee();146if (!Callee)147// We don't have direct callee. Conservatively assume throwing.148return true;149150if (FunctionCanThrow(Callee))151return true;152153// Fall through to visit the children.154}155156if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {157// Special handling of CXXBindTemporaryExpr here as calling of Dtor of the158// temporary is not part of `children()` as covered in the fall through.159// We need to mark entire statement as throwing if the destructor of the160// temporary throws.161const auto *Dtor = TE->getTemporary()->getDestructor();162if (FunctionCanThrow(Dtor))163return true;164165// Fall through to visit the children.166}167168for (const auto *child : S->children())169if (StmtCanThrow(child))170return true;171172return false;173}174175// Emit suspend expression which roughly looks like:176//177// auto && x = CommonExpr();178// if (!x.await_ready()) {179// llvm_coro_save();180// llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)181// llvm_coro_suspend(); (***)182// }183// x.await_resume();184//185// where the result of the entire expression is the result of x.await_resume()186//187// (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to188// wrapper(&x, frame) when it's certain not to interfere with189// coroutine transform. await_suspend expression is190// asynchronous to the coroutine body and not all analyses191// and transformations can handle it correctly at the moment.192//193// Wrapper function encapsulates x.await_suspend(...) call and looks like:194//195// auto __await_suspend_wrapper(auto& awaiter, void* frame) {196// std::coroutine_handle<> handle(frame);197// return awaiter.await_suspend(handle);198// }199//200// (**) If x.await_suspend return type is bool, it allows to veto a suspend:201// if (x.await_suspend(...))202// llvm_coro_suspend();203//204// (***) llvm_coro_suspend() encodes three possible continuations as205// a switch instruction:206//207// %where-to = call i8 @llvm.coro.suspend(...)208// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend209// i8 0, label %yield.ready ; go here when resumed210// i8 1, label %yield.cleanup ; go here when destroyed211// ]212//213// See llvm's docs/Coroutines.rst for more details.214//215namespace {216struct LValueOrRValue {217LValue LV;218RValue RV;219};220}221static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,222CoroutineSuspendExpr const &S,223AwaitKind Kind, AggValueSlot aggSlot,224bool ignoreResult, bool forLValue) {225auto *E = S.getCommonExpr();226227auto CommonBinder =228CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);229auto UnbindCommonOnExit =230llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });231232auto Prefix = buildSuspendPrefixStr(Coro, Kind);233BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));234BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));235BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));236237// If expression is ready, no need to suspend.238CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);239240// Otherwise, emit suspend logic.241CGF.EmitBlock(SuspendBlock);242243auto &Builder = CGF.Builder;244llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);245auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);246auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});247248auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(249CGF.CurFn->getName(), Prefix, S);250251CGF.CurCoro.InSuspendBlock = true;252253assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&254"expected to be called in coroutine context");255256SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;257SuspendIntrinsicCallArgs.push_back(258CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));259260SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);261SuspendIntrinsicCallArgs.push_back(SuspendWrapper);262263const auto SuspendReturnType = S.getSuspendReturnType();264llvm::Intrinsic::ID AwaitSuspendIID;265266switch (SuspendReturnType) {267case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:268AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;269break;270case CoroutineSuspendExpr::SuspendReturnType::SuspendBool:271AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;272break;273case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:274AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;275break;276}277278llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);279280// SuspendHandle might throw since it also resumes the returned handle.281const bool AwaitSuspendCanThrow =282SuspendReturnType ==283CoroutineSuspendExpr::SuspendReturnType::SuspendHandle ||284StmtCanThrow(S.getSuspendExpr());285286llvm::CallBase *SuspendRet = nullptr;287// FIXME: add call attributes?288if (AwaitSuspendCanThrow)289SuspendRet =290CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);291else292SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,293SuspendIntrinsicCallArgs);294295assert(SuspendRet);296CGF.CurCoro.InSuspendBlock = false;297298switch (SuspendReturnType) {299case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:300assert(SuspendRet->getType()->isVoidTy());301break;302case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {303assert(SuspendRet->getType()->isIntegerTy());304305// Veto suspension if requested by bool returning await_suspend.306BasicBlock *RealSuspendBlock =307CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));308CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);309CGF.EmitBlock(RealSuspendBlock);310break;311}312case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle: {313assert(SuspendRet->getType()->isVoidTy());314break;315}316}317318// Emit the suspend point.319const bool IsFinalSuspend = (Kind == AwaitKind::Final);320llvm::Function *CoroSuspend =321CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);322auto *SuspendResult = Builder.CreateCall(323CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});324325// Create a switch capturing three possible continuations.326auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);327Switch->addCase(Builder.getInt8(0), ReadyBlock);328Switch->addCase(Builder.getInt8(1), CleanupBlock);329330// Emit cleanup for this suspend point.331CGF.EmitBlock(CleanupBlock);332CGF.EmitBranchThroughCleanup(Coro.CleanupJD);333334// Emit await_resume expression.335CGF.EmitBlock(ReadyBlock);336337// Exception handling requires additional IR. If the 'await_resume' function338// is marked as 'noexcept', we avoid generating this additional IR.339CXXTryStmt *TryStmt = nullptr;340if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&341StmtCanThrow(S.getResumeExpr())) {342Coro.ResumeEHVar =343CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));344Builder.CreateFlagStore(true, Coro.ResumeEHVar);345346auto Loc = S.getResumeExpr()->getExprLoc();347auto *Catch = new (CGF.getContext())348CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);349auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),350FPOptionsOverride(), Loc, Loc);351TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);352CGF.EnterCXXTryStmt(*TryStmt);353CGF.EmitStmt(TryBody);354// We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that355// doesn't exist in the body.356Builder.CreateFlagStore(false, Coro.ResumeEHVar);357CGF.ExitCXXTryStmt(*TryStmt);358LValueOrRValue Res;359// We are not supposed to obtain the value from init suspend await_resume().360Res.RV = RValue::getIgnored();361return Res;362}363364LValueOrRValue Res;365if (forLValue)366Res.LV = CGF.EmitLValue(S.getResumeExpr());367else368Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);369370return Res;371}372373RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,374AggValueSlot aggSlot,375bool ignoreResult) {376return emitSuspendExpression(*this, *CurCoro.Data, E,377CurCoro.Data->CurrentAwaitKind, aggSlot,378ignoreResult, /*forLValue*/false).RV;379}380RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,381AggValueSlot aggSlot,382bool ignoreResult) {383return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,384aggSlot, ignoreResult, /*forLValue*/false).RV;385}386387void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {388++CurCoro.Data->CoreturnCount;389const Expr *RV = S.getOperand();390if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {391// Make sure to evaluate the non initlist expression of a co_return392// with a void expression for side effects.393RunCleanupsScope cleanupScope(*this);394EmitIgnoredExpr(RV);395}396EmitStmt(S.getPromiseCall());397EmitBranchThroughCleanup(CurCoro.Data->FinalJD);398}399400401#ifndef NDEBUG402static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,403const CoroutineSuspendExpr *E) {404const auto *RE = E->getResumeExpr();405// Is it possible for RE to be a CXXBindTemporaryExpr wrapping406// a MemberCallExpr?407assert(isa<CallExpr>(RE) && "unexpected suspend expression type");408return cast<CallExpr>(RE)->getCallReturnType(Ctx);409}410#endif411412llvm::Function *413CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,414Twine const &SuspendPointName,415CoroutineSuspendExpr const &S) {416std::string FuncName =417(CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();418419ASTContext &C = getContext();420421FunctionArgList args;422423ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);424ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);425QualType ReturnTy = S.getSuspendExpr()->getType();426427args.push_back(&AwaiterDecl);428args.push_back(&FrameDecl);429430const CGFunctionInfo &FI =431CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);432433llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);434435llvm::Function *Fn = llvm::Function::Create(436LTy, llvm::GlobalValue::PrivateLinkage, FuncName, &CGM.getModule());437438Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);439Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);440441Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);442443Fn->setMustProgress();444Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);445446StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);447448// FIXME: add TBAA metadata to the loads449llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(&AwaiterDecl));450auto AwaiterLValue =451MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl.getType());452453CurAwaitSuspendWrapper.FramePtr =454Builder.CreateLoad(GetAddrOfLocalVar(&FrameDecl));455456auto AwaiterBinder = CodeGenFunction::OpaqueValueMappingData::bind(457*this, S.getOpaqueValue(), AwaiterLValue);458459auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());460461auto UnbindCommonOnExit =462llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });463if (SuspendRet != nullptr) {464Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);465Builder.CreateStore(SuspendRet, ReturnValue);466}467468CurAwaitSuspendWrapper.FramePtr = nullptr;469FinishFunction();470return Fn;471}472473LValue474CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {475assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&476"Can't have a scalar return unless the return type is a "477"reference type!");478return emitSuspendExpression(*this, *CurCoro.Data, *E,479CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),480/*ignoreResult*/false, /*forLValue*/true).LV;481}482483LValue484CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {485assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&486"Can't have a scalar return unless the return type is a "487"reference type!");488return emitSuspendExpression(*this, *CurCoro.Data, *E,489AwaitKind::Yield, AggValueSlot::ignored(),490/*ignoreResult*/false, /*forLValue*/true).LV;491}492493// Hunts for the parameter reference in the parameter copy/move declaration.494namespace {495struct GetParamRef : public StmtVisitor<GetParamRef> {496public:497DeclRefExpr *Expr = nullptr;498GetParamRef() {}499void VisitDeclRefExpr(DeclRefExpr *E) {500assert(Expr == nullptr && "multilple declref in param move");501Expr = E;502}503void VisitStmt(Stmt *S) {504for (auto *C : S->children()) {505if (C)506Visit(C);507}508}509};510}511512// This class replaces references to parameters to their copies by changing513// the addresses in CGF.LocalDeclMap and restoring back the original values in514// its destructor.515516namespace {517struct ParamReferenceReplacerRAII {518CodeGenFunction::DeclMapTy SavedLocals;519CodeGenFunction::DeclMapTy& LocalDeclMap;520521ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)522: LocalDeclMap(LocalDeclMap) {}523524void addCopy(DeclStmt const *PM) {525// Figure out what param it refers to.526527assert(PM->isSingleDecl());528VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());529Expr const *InitExpr = VD->getInit();530GetParamRef Visitor;531Visitor.Visit(const_cast<Expr*>(InitExpr));532assert(Visitor.Expr);533DeclRefExpr *DREOrig = Visitor.Expr;534auto *PD = DREOrig->getDecl();535536auto it = LocalDeclMap.find(PD);537assert(it != LocalDeclMap.end() && "parameter is not found");538SavedLocals.insert({ PD, it->second });539540auto copyIt = LocalDeclMap.find(VD);541assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");542it->second = copyIt->getSecond();543}544545~ParamReferenceReplacerRAII() {546for (auto&& SavedLocal : SavedLocals) {547LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});548}549}550};551}552553// For WinEH exception representation backend needs to know what funclet coro.end554// belongs to. That information is passed in a funclet bundle.555static SmallVector<llvm::OperandBundleDef, 1>556getBundlesForCoroEnd(CodeGenFunction &CGF) {557SmallVector<llvm::OperandBundleDef, 1> BundleList;558559if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)560BundleList.emplace_back("funclet", EHPad);561562return BundleList;563}564565namespace {566// We will insert coro.end to cut any of the destructors for objects that567// do not need to be destroyed once the coroutine is resumed.568// See llvm/docs/Coroutines.rst for more details about coro.end.569struct CallCoroEnd final : public EHScopeStack::Cleanup {570void Emit(CodeGenFunction &CGF, Flags flags) override {571auto &CGM = CGF.CGM;572auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);573llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);574// See if we have a funclet bundle to associate coro.end with. (WinEH)575auto Bundles = getBundlesForCoroEnd(CGF);576auto *CoroEnd =577CGF.Builder.CreateCall(CoroEndFn,578{NullPtr, CGF.Builder.getTrue(),579llvm::ConstantTokenNone::get(CoroEndFn->getContext())},580Bundles);581if (Bundles.empty()) {582// Otherwise, (landingpad model), create a conditional branch that leads583// either to a cleanup block or a block with EH resume instruction.584auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);585auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");586CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);587CGF.EmitBlock(CleanupContBB);588}589}590};591}592593namespace {594// Make sure to call coro.delete on scope exit.595struct CallCoroDelete final : public EHScopeStack::Cleanup {596Stmt *Deallocate;597598// Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"599600// Note: That deallocation will be emitted twice: once for a normal exit and601// once for exceptional exit. This usage is safe because Deallocate does not602// contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()603// builds a single call to a deallocation function which is safe to emit604// multiple times.605void Emit(CodeGenFunction &CGF, Flags) override {606// Remember the current point, as we are going to emit deallocation code607// first to get to coro.free instruction that is an argument to a delete608// call.609BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();610611auto *FreeBB = CGF.createBasicBlock("coro.free");612CGF.EmitBlock(FreeBB);613CGF.EmitStmt(Deallocate);614615auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");616CGF.EmitBlock(AfterFreeBB);617618// We should have captured coro.free from the emission of deallocate.619auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;620if (!CoroFree) {621CGF.CGM.Error(Deallocate->getBeginLoc(),622"Deallocation expressoin does not refer to coro.free");623return;624}625626// Get back to the block we were originally and move coro.free there.627auto *InsertPt = SaveInsertBlock->getTerminator();628CoroFree->moveBefore(InsertPt);629CGF.Builder.SetInsertPoint(InsertPt);630631// Add if (auto *mem = coro.free) Deallocate;632auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);633auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);634CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);635636// No longer need old terminator.637InsertPt->eraseFromParent();638CGF.Builder.SetInsertPoint(AfterFreeBB);639}640explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}641};642}643644namespace {645struct GetReturnObjectManager {646CodeGenFunction &CGF;647CGBuilderTy &Builder;648const CoroutineBodyStmt &S;649// When true, performs RVO for the return object.650bool DirectEmit = false;651652Address GroActiveFlag;653CodeGenFunction::AutoVarEmission GroEmission;654655GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)656: CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),657GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {658// The call to get_return_object is sequenced before the call to659// initial_suspend and is invoked at most once, but there are caveats660// regarding on whether the prvalue result object may be initialized661// directly/eager or delayed, depending on the types involved.662//663// More info at https://github.com/cplusplus/papers/issues/1414664//665// The general cases:666// 1. Same type of get_return_object and coroutine return type (direct667// emission):668// - Constructed in the return slot.669// 2. Different types (delayed emission):670// - Constructed temporary object prior to initial suspend initialized with671// a call to get_return_object()672// - When coroutine needs to to return to the caller and needs to construct673// return value for the coroutine it is initialized with expiring value of674// the temporary obtained above.675//676// Direct emission for void returning coroutines or GROs.677DirectEmit = [&]() {678auto *RVI = S.getReturnValueInit();679assert(RVI && "expected RVI");680auto GroType = RVI->getType();681return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);682}();683}684685// The gro variable has to outlive coroutine frame and coroutine promise, but,686// it can only be initialized after coroutine promise was created, thus, we687// split its emission in two parts. EmitGroAlloca emits an alloca and sets up688// cleanups. Later when coroutine promise is available we initialize the gro689// and sets the flag that the cleanup is now active.690void EmitGroAlloca() {691if (DirectEmit)692return;693694auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());695if (!GroDeclStmt) {696// If get_return_object returns void, no need to do an alloca.697return;698}699700auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());701702// Set GRO flag that it is not initialized yet703GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),704"gro.active");705Builder.CreateStore(Builder.getFalse(), GroActiveFlag);706707GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);708auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(709GroEmission.getOriginalAllocatedAddress().getPointer());710assert(GroAlloca && "expected alloca to be emitted");711GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,712llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));713714// Remember the top of EHStack before emitting the cleanup.715auto old_top = CGF.EHStack.stable_begin();716CGF.EmitAutoVarCleanups(GroEmission);717auto top = CGF.EHStack.stable_begin();718719// Make the cleanup conditional on gro.active720for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;721b++) {722if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {723assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");724Cleanup->setActiveFlag(GroActiveFlag);725Cleanup->setTestFlagInEHCleanup();726Cleanup->setTestFlagInNormalCleanup();727}728}729}730731void EmitGroInit() {732if (DirectEmit) {733// ReturnValue should be valid as long as the coroutine's return type734// is not void. The assertion could help us to reduce the check later.735assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());736// Now we have the promise, initialize the GRO.737// We need to emit `get_return_object` first. According to:738// [dcl.fct.def.coroutine]p7739// The call to get_return_object is sequenced before the call to740// initial_suspend and is invoked at most once.741//742// So we couldn't emit return value when we emit return statment,743// otherwise the call to get_return_object wouldn't be in front744// of initial_suspend.745if (CGF.ReturnValue.isValid()) {746CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,747S.getReturnValue()->getType().getQualifiers(),748/*IsInit*/ true);749}750return;751}752753if (!GroActiveFlag.isValid()) {754// No Gro variable was allocated. Simply emit the call to755// get_return_object.756CGF.EmitStmt(S.getResultDecl());757return;758}759760CGF.EmitAutoVarInit(GroEmission);761Builder.CreateStore(Builder.getTrue(), GroActiveFlag);762}763};764} // namespace765766static void emitBodyAndFallthrough(CodeGenFunction &CGF,767const CoroutineBodyStmt &S, Stmt *Body) {768CGF.EmitStmt(Body);769const bool CanFallthrough = CGF.Builder.GetInsertBlock();770if (CanFallthrough)771if (Stmt *OnFallthrough = S.getFallthroughHandler())772CGF.EmitStmt(OnFallthrough);773}774775void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {776auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());777auto &TI = CGM.getContext().getTargetInfo();778unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();779780auto *EntryBB = Builder.GetInsertBlock();781auto *AllocBB = createBasicBlock("coro.alloc");782auto *InitBB = createBasicBlock("coro.init");783auto *FinalBB = createBasicBlock("coro.final");784auto *RetBB = createBasicBlock("coro.ret");785786auto *CoroId = Builder.CreateCall(787CGM.getIntrinsic(llvm::Intrinsic::coro_id),788{Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});789createCoroData(*this, CurCoro, CoroId);790CurCoro.Data->SuspendBB = RetBB;791assert(ShouldEmitLifetimeMarkers &&792"Must emit lifetime intrinsics for coroutines");793794// Backend is allowed to elide memory allocations, to help it, emit795// auto mem = coro.alloc() ? 0 : ... allocation code ...;796auto *CoroAlloc = Builder.CreateCall(797CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});798799Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);800801EmitBlock(AllocBB);802auto *AllocateCall = EmitScalarExpr(S.getAllocate());803auto *AllocOrInvokeContBB = Builder.GetInsertBlock();804805// Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.806if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {807auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");808809// See if allocation was successful.810auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);811auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);812// Expect the allocation to be successful.813emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);814Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);815816// If not, return OnAllocFailure object.817EmitBlock(RetOnFailureBB);818EmitStmt(RetOnAllocFailure);819}820else {821Builder.CreateBr(InitBB);822}823824EmitBlock(InitBB);825826// Pass the result of the allocation to coro.begin.827auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);828Phi->addIncoming(NullPtr, EntryBB);829Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);830auto *CoroBegin = Builder.CreateCall(831CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});832CurCoro.Data->CoroBegin = CoroBegin;833834GetReturnObjectManager GroManager(*this, S);835GroManager.EmitGroAlloca();836837CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);838{839CGDebugInfo *DI = getDebugInfo();840ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);841CodeGenFunction::RunCleanupsScope ResumeScope(*this);842EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());843844// Create mapping between parameters and copy-params for coroutine function.845llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();846assert(847(ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&848"ParamMoves and FnArgs should be the same size for coroutine function");849if (ParamMoves.size() == FnArgs.size() && DI)850for (const auto Pair : llvm::zip(FnArgs, ParamMoves))851DI->getCoroutineParameterMappings().insert(852{std::get<0>(Pair), std::get<1>(Pair)});853854// Create parameter copies. We do it before creating a promise, since an855// evolution of coroutine TS may allow promise constructor to observe856// parameter copies.857for (auto *PM : S.getParamMoves()) {858EmitStmt(PM);859ParamReplacer.addCopy(cast<DeclStmt>(PM));860// TODO: if(CoroParam(...)) need to surround ctor and dtor861// for the copy, so that llvm can elide it if the copy is862// not needed.863}864865EmitStmt(S.getPromiseDeclStmt());866867Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());868auto *PromiseAddrVoidPtr = new llvm::BitCastInst(869PromiseAddr.emitRawPointer(*this), VoidPtrTy, "", CoroId);870// Update CoroId to refer to the promise. We could not do it earlier because871// promise local variable was not emitted yet.872CoroId->setArgOperand(1, PromiseAddrVoidPtr);873874// Now we have the promise, initialize the GRO875GroManager.EmitGroInit();876877EHStack.pushCleanup<CallCoroEnd>(EHCleanup);878879CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;880CurCoro.Data->ExceptionHandler = S.getExceptionHandler();881EmitStmt(S.getInitSuspendStmt());882CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);883884CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;885886if (CurCoro.Data->ExceptionHandler) {887// If we generated IR to record whether an exception was thrown from888// 'await_resume', then use that IR to determine whether the coroutine889// body should be skipped.890// If we didn't generate the IR (perhaps because 'await_resume' was marked891// as 'noexcept'), then we skip this check.892BasicBlock *ContBB = nullptr;893if (CurCoro.Data->ResumeEHVar) {894BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");895ContBB = createBasicBlock("coro.resumed.cont");896Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,897"coro.resumed.eh");898Builder.CreateCondBr(SkipBody, ContBB, BodyBB);899EmitBlock(BodyBB);900}901902auto Loc = S.getBeginLoc();903CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,904CurCoro.Data->ExceptionHandler);905auto *TryStmt =906CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);907908EnterCXXTryStmt(*TryStmt);909emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());910ExitCXXTryStmt(*TryStmt);911912if (ContBB)913EmitBlock(ContBB);914}915else {916emitBodyAndFallthrough(*this, S, S.getBody());917}918919// See if we need to generate final suspend.920const bool CanFallthrough = Builder.GetInsertBlock();921const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;922if (CanFallthrough || HasCoreturns) {923EmitBlock(FinalBB);924CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;925EmitStmt(S.getFinalSuspendStmt());926} else {927// We don't need FinalBB. Emit it to make sure the block is deleted.928EmitBlock(FinalBB, /*IsFinished=*/true);929}930}931932EmitBlock(RetBB);933// Emit coro.end before getReturnStmt (and parameter destructors), since934// resume and destroy parts of the coroutine should not include them.935llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);936Builder.CreateCall(CoroEnd,937{NullPtr, Builder.getFalse(),938llvm::ConstantTokenNone::get(CoroEnd->getContext())});939940if (Stmt *Ret = S.getReturnStmt()) {941// Since we already emitted the return value above, so we shouldn't942// emit it again here.943if (GroManager.DirectEmit)944cast<ReturnStmt>(Ret)->setRetValue(nullptr);945EmitStmt(Ret);946}947948// LLVM require the frontend to mark the coroutine.949CurFn->setPresplitCoroutine();950951if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();952RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())953CurFn->setCoroDestroyOnlyWhenComplete();954}955956// Emit coroutine intrinsic and patch up arguments of the token type.957RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,958unsigned int IID) {959SmallVector<llvm::Value *, 8> Args;960switch (IID) {961default:962break;963// The coro.frame builtin is replaced with an SSA value of the coro.begin964// intrinsic.965case llvm::Intrinsic::coro_frame: {966if (CurCoro.Data && CurCoro.Data->CoroBegin) {967return RValue::get(CurCoro.Data->CoroBegin);968}969970if (CurAwaitSuspendWrapper.FramePtr) {971return RValue::get(CurAwaitSuspendWrapper.FramePtr);972}973974CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "975"has been used earlier in this function");976auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());977return RValue::get(NullPtr);978}979case llvm::Intrinsic::coro_size: {980auto &Context = getContext();981CanQualType SizeTy = Context.getSizeType();982llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));983llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);984return RValue::get(Builder.CreateCall(F));985}986case llvm::Intrinsic::coro_align: {987auto &Context = getContext();988CanQualType SizeTy = Context.getSizeType();989llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));990llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);991return RValue::get(Builder.CreateCall(F));992}993// The following three intrinsics take a token parameter referring to a token994// returned by earlier call to @llvm.coro.id. Since we cannot represent it in995// builtins, we patch it up here.996case llvm::Intrinsic::coro_alloc:997case llvm::Intrinsic::coro_begin:998case llvm::Intrinsic::coro_free: {999if (CurCoro.Data && CurCoro.Data->CoroId) {1000Args.push_back(CurCoro.Data->CoroId);1001break;1002}1003CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"1004" been used earlier in this function");1005// Fallthrough to the next case to add TokenNone as the first argument.1006[[fallthrough]];1007}1008// @llvm.coro.suspend takes a token parameter. Add token 'none' as the first1009// argument.1010case llvm::Intrinsic::coro_suspend:1011Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));1012break;1013}1014for (const Expr *Arg : E->arguments())1015Args.push_back(EmitScalarExpr(Arg));1016// @llvm.coro.end takes a token parameter. Add token 'none' as the last1017// argument.1018if (IID == llvm::Intrinsic::coro_end)1019Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));10201021llvm::Function *F = CGM.getIntrinsic(IID);1022llvm::CallInst *Call = Builder.CreateCall(F, Args);10231024// Note: The following code is to enable to emit coro.id and coro.begin by1025// hand to experiment with coroutines in C.1026// If we see @llvm.coro.id remember it in the CoroData. We will update1027// coro.alloc, coro.begin and coro.free intrinsics to refer to it.1028if (IID == llvm::Intrinsic::coro_id) {1029createCoroData(*this, CurCoro, Call, E);1030}1031else if (IID == llvm::Intrinsic::coro_begin) {1032if (CurCoro.Data)1033CurCoro.Data->CoroBegin = Call;1034}1035else if (IID == llvm::Intrinsic::coro_free) {1036// Remember the last coro_free as we need it to build the conditional1037// deletion of the coroutine frame.1038if (CurCoro.Data)1039CurCoro.Data->LastCoroFree = Call;1040}1041return RValue::get(Call);1042}104310441045