xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code dealing with C++ code generation of coroutines.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CGCleanup.h"
140b57cec5SDimitry Andric #include "CodeGenFunction.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
160b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
170b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric using namespace clang;
200b57cec5SDimitry Andric using namespace CodeGen;
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric using llvm::Value;
230b57cec5SDimitry Andric using llvm::BasicBlock;
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric namespace {
260b57cec5SDimitry Andric enum class AwaitKind { Init, Normal, Yield, Final };
270b57cec5SDimitry Andric static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
280b57cec5SDimitry Andric                                                        "final"};
290b57cec5SDimitry Andric }
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric struct clang::CodeGen::CGCoroData {
320b57cec5SDimitry Andric   // What is the current await expression kind and how many
330b57cec5SDimitry Andric   // await/yield expressions were encountered so far.
340b57cec5SDimitry Andric   // These are used to generate pretty labels for await expressions in LLVM IR.
350b57cec5SDimitry Andric   AwaitKind CurrentAwaitKind = AwaitKind::Init;
360b57cec5SDimitry Andric   unsigned AwaitNum = 0;
370b57cec5SDimitry Andric   unsigned YieldNum = 0;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric   // How many co_return statements are in the coroutine. Used to decide whether
400b57cec5SDimitry Andric   // we need to add co_return; equivalent at the end of the user authored body.
410b57cec5SDimitry Andric   unsigned CoreturnCount = 0;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric   // A branch to this block is emitted when coroutine needs to suspend.
440b57cec5SDimitry Andric   llvm::BasicBlock *SuspendBB = nullptr;
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   // The promise type's 'unhandled_exception' handler, if it defines one.
470b57cec5SDimitry Andric   Stmt *ExceptionHandler = nullptr;
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric   // A temporary i1 alloca that stores whether 'await_resume' threw an
500b57cec5SDimitry Andric   // exception. If it did, 'true' is stored in this variable, and the coroutine
510b57cec5SDimitry Andric   // body must be skipped. If the promise type does not define an exception
520b57cec5SDimitry Andric   // handler, this is null.
530b57cec5SDimitry Andric   llvm::Value *ResumeEHVar = nullptr;
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   // Stores the jump destination just before the coroutine memory is freed.
560b57cec5SDimitry Andric   // This is the destination that every suspend point jumps to for the cleanup
570b57cec5SDimitry Andric   // branch.
580b57cec5SDimitry Andric   CodeGenFunction::JumpDest CleanupJD;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric   // Stores the jump destination just before the final suspend. The co_return
610b57cec5SDimitry Andric   // statements jumps to this point after calling return_xxx promise member.
620b57cec5SDimitry Andric   CodeGenFunction::JumpDest FinalJD;
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric   // Stores the llvm.coro.id emitted in the function so that we can supply it
650b57cec5SDimitry Andric   // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
660b57cec5SDimitry Andric   // Note: llvm.coro.id returns a token that cannot be directly expressed in a
670b57cec5SDimitry Andric   // builtin.
680b57cec5SDimitry Andric   llvm::CallInst *CoroId = nullptr;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric   // Stores the llvm.coro.begin emitted in the function so that we can replace
710b57cec5SDimitry Andric   // all coro.frame intrinsics with direct SSA value of coro.begin that returns
720b57cec5SDimitry Andric   // the address of the coroutine frame of the current coroutine.
730b57cec5SDimitry Andric   llvm::CallInst *CoroBegin = nullptr;
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric   // Stores the last emitted coro.free for the deallocate expressions, we use it
760b57cec5SDimitry Andric   // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
770b57cec5SDimitry Andric   llvm::CallInst *LastCoroFree = nullptr;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   // If coro.id came from the builtin, remember the expression to give better
800b57cec5SDimitry Andric   // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
810b57cec5SDimitry Andric   // EmitCoroutineBody.
820b57cec5SDimitry Andric   CallExpr const *CoroIdExpr = nullptr;
830b57cec5SDimitry Andric };
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric // Defining these here allows to keep CGCoroData private to this file.
860b57cec5SDimitry Andric clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
870b57cec5SDimitry Andric CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric static void createCoroData(CodeGenFunction &CGF,
900b57cec5SDimitry Andric                            CodeGenFunction::CGCoroInfo &CurCoro,
910b57cec5SDimitry Andric                            llvm::CallInst *CoroId,
920b57cec5SDimitry Andric                            CallExpr const *CoroIdExpr = nullptr) {
930b57cec5SDimitry Andric   if (CurCoro.Data) {
940b57cec5SDimitry Andric     if (CurCoro.Data->CoroIdExpr)
950b57cec5SDimitry Andric       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
960b57cec5SDimitry Andric                     "only one __builtin_coro_id can be used in a function");
970b57cec5SDimitry Andric     else if (CoroIdExpr)
980b57cec5SDimitry Andric       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
990b57cec5SDimitry Andric                     "__builtin_coro_id shall not be used in a C++ coroutine");
1000b57cec5SDimitry Andric     else
1010b57cec5SDimitry Andric       llvm_unreachable("EmitCoroutineBodyStatement called twice?");
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric     return;
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric 
106*0fca6ea1SDimitry Andric   CurCoro.Data = std::make_unique<CGCoroData>();
1070b57cec5SDimitry Andric   CurCoro.Data->CoroId = CoroId;
1080b57cec5SDimitry Andric   CurCoro.Data->CoroIdExpr = CoroIdExpr;
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric // Synthesize a pretty name for a suspend point.
1120b57cec5SDimitry Andric static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
1130b57cec5SDimitry Andric   unsigned No = 0;
1140b57cec5SDimitry Andric   switch (Kind) {
1150b57cec5SDimitry Andric   case AwaitKind::Init:
1160b57cec5SDimitry Andric   case AwaitKind::Final:
1170b57cec5SDimitry Andric     break;
1180b57cec5SDimitry Andric   case AwaitKind::Normal:
1190b57cec5SDimitry Andric     No = ++Coro.AwaitNum;
1200b57cec5SDimitry Andric     break;
1210b57cec5SDimitry Andric   case AwaitKind::Yield:
1220b57cec5SDimitry Andric     No = ++Coro.YieldNum;
1230b57cec5SDimitry Andric     break;
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric   SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
1260b57cec5SDimitry Andric   if (No > 1) {
1270b57cec5SDimitry Andric     Twine(No).toVector(Prefix);
1280b57cec5SDimitry Andric   }
1290b57cec5SDimitry Andric   return Prefix;
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1325f757f3fSDimitry Andric // Check if function can throw based on prototype noexcept, also works for
1335f757f3fSDimitry Andric // destructors which are implicitly noexcept but can be marked noexcept(false).
1345f757f3fSDimitry Andric static bool FunctionCanThrow(const FunctionDecl *D) {
1355f757f3fSDimitry Andric   const auto *Proto = D->getType()->getAs<FunctionProtoType>();
1365f757f3fSDimitry Andric   if (!Proto) {
1375f757f3fSDimitry Andric     // Function proto is not found, we conservatively assume throwing.
1380b57cec5SDimitry Andric     return true;
1390b57cec5SDimitry Andric   }
1405f757f3fSDimitry Andric   return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||
1415f757f3fSDimitry Andric          Proto->canThrow() != CT_Cannot;
1425f757f3fSDimitry Andric }
1435f757f3fSDimitry Andric 
144*0fca6ea1SDimitry Andric static bool StmtCanThrow(const Stmt *S) {
1455f757f3fSDimitry Andric   if (const auto *CE = dyn_cast<CallExpr>(S)) {
1465f757f3fSDimitry Andric     const auto *Callee = CE->getDirectCallee();
1475f757f3fSDimitry Andric     if (!Callee)
1485f757f3fSDimitry Andric       // We don't have direct callee. Conservatively assume throwing.
1495f757f3fSDimitry Andric       return true;
1505f757f3fSDimitry Andric 
1515f757f3fSDimitry Andric     if (FunctionCanThrow(Callee))
1525f757f3fSDimitry Andric       return true;
1535f757f3fSDimitry Andric 
1545f757f3fSDimitry Andric     // Fall through to visit the children.
1555f757f3fSDimitry Andric   }
1565f757f3fSDimitry Andric 
1575f757f3fSDimitry Andric   if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {
1585f757f3fSDimitry Andric     // Special handling of CXXBindTemporaryExpr here as calling of Dtor of the
1595f757f3fSDimitry Andric     // temporary is not part of `children()` as covered in the fall through.
1605f757f3fSDimitry Andric     // We need to mark entire statement as throwing if the destructor of the
1615f757f3fSDimitry Andric     // temporary throws.
1625f757f3fSDimitry Andric     const auto *Dtor = TE->getTemporary()->getDestructor();
1635f757f3fSDimitry Andric     if (FunctionCanThrow(Dtor))
1645f757f3fSDimitry Andric       return true;
1655f757f3fSDimitry Andric 
1665f757f3fSDimitry Andric     // Fall through to visit the children.
1675f757f3fSDimitry Andric   }
1685f757f3fSDimitry Andric 
1695f757f3fSDimitry Andric   for (const auto *child : S->children())
170*0fca6ea1SDimitry Andric     if (StmtCanThrow(child))
1715f757f3fSDimitry Andric       return true;
1725f757f3fSDimitry Andric 
1735f757f3fSDimitry Andric   return false;
1745f757f3fSDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric // Emit suspend expression which roughly looks like:
1770b57cec5SDimitry Andric //
1780b57cec5SDimitry Andric //   auto && x = CommonExpr();
1790b57cec5SDimitry Andric //   if (!x.await_ready()) {
1800b57cec5SDimitry Andric //      llvm_coro_save();
181*0fca6ea1SDimitry Andric //      llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)
182*0fca6ea1SDimitry Andric //      llvm_coro_suspend(); (***)
1830b57cec5SDimitry Andric //   }
1840b57cec5SDimitry Andric //   x.await_resume();
1850b57cec5SDimitry Andric //
1860b57cec5SDimitry Andric // where the result of the entire expression is the result of x.await_resume()
1870b57cec5SDimitry Andric //
188*0fca6ea1SDimitry Andric //   (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to
189*0fca6ea1SDimitry Andric //      wrapper(&x, frame) when it's certain not to interfere with
190*0fca6ea1SDimitry Andric //      coroutine transform. await_suspend expression is
191*0fca6ea1SDimitry Andric //      asynchronous to the coroutine body and not all analyses
192*0fca6ea1SDimitry Andric //      and transformations can handle it correctly at the moment.
193*0fca6ea1SDimitry Andric //
194*0fca6ea1SDimitry Andric //      Wrapper function encapsulates x.await_suspend(...) call and looks like:
195*0fca6ea1SDimitry Andric //
196*0fca6ea1SDimitry Andric //      auto __await_suspend_wrapper(auto& awaiter, void* frame) {
197*0fca6ea1SDimitry Andric //        std::coroutine_handle<> handle(frame);
198*0fca6ea1SDimitry Andric //        return awaiter.await_suspend(handle);
199*0fca6ea1SDimitry Andric //      }
200*0fca6ea1SDimitry Andric //
201*0fca6ea1SDimitry Andric //  (**) If x.await_suspend return type is bool, it allows to veto a suspend:
2020b57cec5SDimitry Andric //      if (x.await_suspend(...))
2030b57cec5SDimitry Andric //        llvm_coro_suspend();
2040b57cec5SDimitry Andric //
205*0fca6ea1SDimitry Andric //  (***) llvm_coro_suspend() encodes three possible continuations as
2060b57cec5SDimitry Andric //       a switch instruction:
2070b57cec5SDimitry Andric //
2080b57cec5SDimitry Andric //  %where-to = call i8 @llvm.coro.suspend(...)
2090b57cec5SDimitry Andric //  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
2100b57cec5SDimitry Andric //    i8 0, label %yield.ready   ; go here when resumed
2110b57cec5SDimitry Andric //    i8 1, label %yield.cleanup ; go here when destroyed
2120b57cec5SDimitry Andric //  ]
2130b57cec5SDimitry Andric //
2140b57cec5SDimitry Andric //  See llvm's docs/Coroutines.rst for more details.
2150b57cec5SDimitry Andric //
2160b57cec5SDimitry Andric namespace {
2170b57cec5SDimitry Andric   struct LValueOrRValue {
2180b57cec5SDimitry Andric     LValue LV;
2190b57cec5SDimitry Andric     RValue RV;
2200b57cec5SDimitry Andric   };
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
2230b57cec5SDimitry Andric                                     CoroutineSuspendExpr const &S,
2240b57cec5SDimitry Andric                                     AwaitKind Kind, AggValueSlot aggSlot,
2250b57cec5SDimitry Andric                                     bool ignoreResult, bool forLValue) {
2260b57cec5SDimitry Andric   auto *E = S.getCommonExpr();
2270b57cec5SDimitry Andric 
228*0fca6ea1SDimitry Andric   auto CommonBinder =
2290b57cec5SDimitry Andric       CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
230*0fca6ea1SDimitry Andric   auto UnbindCommonOnExit =
231*0fca6ea1SDimitry Andric       llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   auto Prefix = buildSuspendPrefixStr(Coro, Kind);
2340b57cec5SDimitry Andric   BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
2350b57cec5SDimitry Andric   BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
2360b57cec5SDimitry Andric   BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // If expression is ready, no need to suspend.
2390b57cec5SDimitry Andric   CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Otherwise, emit suspend logic.
2420b57cec5SDimitry Andric   CGF.EmitBlock(SuspendBlock);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   auto &Builder = CGF.Builder;
2450b57cec5SDimitry Andric   llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
2460b57cec5SDimitry Andric   auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
2470b57cec5SDimitry Andric   auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
2480b57cec5SDimitry Andric 
249*0fca6ea1SDimitry Andric   auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
250*0fca6ea1SDimitry Andric       CGF.CurFn->getName(), Prefix, S);
251*0fca6ea1SDimitry Andric 
25206c3fb27SDimitry Andric   CGF.CurCoro.InSuspendBlock = true;
253*0fca6ea1SDimitry Andric 
254*0fca6ea1SDimitry Andric   assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
255*0fca6ea1SDimitry Andric          "expected to be called in coroutine context");
256*0fca6ea1SDimitry Andric 
257*0fca6ea1SDimitry Andric   SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
258*0fca6ea1SDimitry Andric   SuspendIntrinsicCallArgs.push_back(
259*0fca6ea1SDimitry Andric       CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));
260*0fca6ea1SDimitry Andric 
261*0fca6ea1SDimitry Andric   SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
262*0fca6ea1SDimitry Andric   SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
263*0fca6ea1SDimitry Andric 
264*0fca6ea1SDimitry Andric   const auto SuspendReturnType = S.getSuspendReturnType();
265*0fca6ea1SDimitry Andric   llvm::Intrinsic::ID AwaitSuspendIID;
266*0fca6ea1SDimitry Andric 
267*0fca6ea1SDimitry Andric   switch (SuspendReturnType) {
268*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
269*0fca6ea1SDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
270*0fca6ea1SDimitry Andric     break;
271*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendBool:
272*0fca6ea1SDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
273*0fca6ea1SDimitry Andric     break;
274*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:
275*0fca6ea1SDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
276*0fca6ea1SDimitry Andric     break;
277*0fca6ea1SDimitry Andric   }
278*0fca6ea1SDimitry Andric 
279*0fca6ea1SDimitry Andric   llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
280*0fca6ea1SDimitry Andric 
281*0fca6ea1SDimitry Andric   // SuspendHandle might throw since it also resumes the returned handle.
282*0fca6ea1SDimitry Andric   const bool AwaitSuspendCanThrow =
283*0fca6ea1SDimitry Andric       SuspendReturnType ==
284*0fca6ea1SDimitry Andric           CoroutineSuspendExpr::SuspendReturnType::SuspendHandle ||
285*0fca6ea1SDimitry Andric       StmtCanThrow(S.getSuspendExpr());
286*0fca6ea1SDimitry Andric 
287*0fca6ea1SDimitry Andric   llvm::CallBase *SuspendRet = nullptr;
288*0fca6ea1SDimitry Andric   // FIXME: add call attributes?
289*0fca6ea1SDimitry Andric   if (AwaitSuspendCanThrow)
290*0fca6ea1SDimitry Andric     SuspendRet =
291*0fca6ea1SDimitry Andric         CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
292*0fca6ea1SDimitry Andric   else
293*0fca6ea1SDimitry Andric     SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
294*0fca6ea1SDimitry Andric                                              SuspendIntrinsicCallArgs);
295*0fca6ea1SDimitry Andric 
296*0fca6ea1SDimitry Andric   assert(SuspendRet);
29706c3fb27SDimitry Andric   CGF.CurCoro.InSuspendBlock = false;
2985f757f3fSDimitry Andric 
299*0fca6ea1SDimitry Andric   switch (SuspendReturnType) {
300*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
301*0fca6ea1SDimitry Andric     assert(SuspendRet->getType()->isVoidTy());
302*0fca6ea1SDimitry Andric     break;
303*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {
304*0fca6ea1SDimitry Andric     assert(SuspendRet->getType()->isIntegerTy());
305*0fca6ea1SDimitry Andric 
3060b57cec5SDimitry Andric     // Veto suspension if requested by bool returning await_suspend.
3070b57cec5SDimitry Andric     BasicBlock *RealSuspendBlock =
3080b57cec5SDimitry Andric         CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
3090b57cec5SDimitry Andric     CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
3100b57cec5SDimitry Andric     CGF.EmitBlock(RealSuspendBlock);
311*0fca6ea1SDimitry Andric     break;
312*0fca6ea1SDimitry Andric   }
313*0fca6ea1SDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle: {
314*0fca6ea1SDimitry Andric     assert(SuspendRet->getType()->isVoidTy());
315*0fca6ea1SDimitry Andric     break;
316*0fca6ea1SDimitry Andric   }
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // Emit the suspend point.
3200b57cec5SDimitry Andric   const bool IsFinalSuspend = (Kind == AwaitKind::Final);
3210b57cec5SDimitry Andric   llvm::Function *CoroSuspend =
3220b57cec5SDimitry Andric       CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
3230b57cec5SDimitry Andric   auto *SuspendResult = Builder.CreateCall(
3240b57cec5SDimitry Andric       CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   // Create a switch capturing three possible continuations.
3270b57cec5SDimitry Andric   auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
3280b57cec5SDimitry Andric   Switch->addCase(Builder.getInt8(0), ReadyBlock);
3290b57cec5SDimitry Andric   Switch->addCase(Builder.getInt8(1), CleanupBlock);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   // Emit cleanup for this suspend point.
3320b57cec5SDimitry Andric   CGF.EmitBlock(CleanupBlock);
3330b57cec5SDimitry Andric   CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric   // Emit await_resume expression.
3360b57cec5SDimitry Andric   CGF.EmitBlock(ReadyBlock);
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   // Exception handling requires additional IR. If the 'await_resume' function
3390b57cec5SDimitry Andric   // is marked as 'noexcept', we avoid generating this additional IR.
3400b57cec5SDimitry Andric   CXXTryStmt *TryStmt = nullptr;
3410b57cec5SDimitry Andric   if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
342*0fca6ea1SDimitry Andric       StmtCanThrow(S.getResumeExpr())) {
3430b57cec5SDimitry Andric     Coro.ResumeEHVar =
3440b57cec5SDimitry Andric         CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
3450b57cec5SDimitry Andric     Builder.CreateFlagStore(true, Coro.ResumeEHVar);
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric     auto Loc = S.getResumeExpr()->getExprLoc();
3480b57cec5SDimitry Andric     auto *Catch = new (CGF.getContext())
3490b57cec5SDimitry Andric         CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
35081ad6265SDimitry Andric     auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
35181ad6265SDimitry Andric                                          FPOptionsOverride(), Loc, Loc);
3520b57cec5SDimitry Andric     TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
3530b57cec5SDimitry Andric     CGF.EnterCXXTryStmt(*TryStmt);
3545f757f3fSDimitry Andric     CGF.EmitStmt(TryBody);
3555f757f3fSDimitry Andric     // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
3565f757f3fSDimitry Andric     // doesn't exist in the body.
3575f757f3fSDimitry Andric     Builder.CreateFlagStore(false, Coro.ResumeEHVar);
3585f757f3fSDimitry Andric     CGF.ExitCXXTryStmt(*TryStmt);
3595f757f3fSDimitry Andric     LValueOrRValue Res;
3605f757f3fSDimitry Andric     // We are not supposed to obtain the value from init suspend await_resume().
3615f757f3fSDimitry Andric     Res.RV = RValue::getIgnored();
3625f757f3fSDimitry Andric     return Res;
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   LValueOrRValue Res;
3660b57cec5SDimitry Andric   if (forLValue)
3670b57cec5SDimitry Andric     Res.LV = CGF.EmitLValue(S.getResumeExpr());
3680b57cec5SDimitry Andric   else
3690b57cec5SDimitry Andric     Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   return Res;
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
3750b57cec5SDimitry Andric                                         AggValueSlot aggSlot,
3760b57cec5SDimitry Andric                                         bool ignoreResult) {
3770b57cec5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, E,
3780b57cec5SDimitry Andric                                CurCoro.Data->CurrentAwaitKind, aggSlot,
3790b57cec5SDimitry Andric                                ignoreResult, /*forLValue*/false).RV;
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
3820b57cec5SDimitry Andric                                         AggValueSlot aggSlot,
3830b57cec5SDimitry Andric                                         bool ignoreResult) {
3840b57cec5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
3850b57cec5SDimitry Andric                                aggSlot, ignoreResult, /*forLValue*/false).RV;
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
3890b57cec5SDimitry Andric   ++CurCoro.Data->CoreturnCount;
3900b57cec5SDimitry Andric   const Expr *RV = S.getOperand();
3915ffd83dbSDimitry Andric   if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
3925ffd83dbSDimitry Andric     // Make sure to evaluate the non initlist expression of a co_return
3935ffd83dbSDimitry Andric     // with a void expression for side effects.
3940b57cec5SDimitry Andric     RunCleanupsScope cleanupScope(*this);
3950b57cec5SDimitry Andric     EmitIgnoredExpr(RV);
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric   EmitStmt(S.getPromiseCall());
3980b57cec5SDimitry Andric   EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric #ifndef NDEBUG
4030b57cec5SDimitry Andric static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
4040b57cec5SDimitry Andric   const CoroutineSuspendExpr *E) {
4050b57cec5SDimitry Andric   const auto *RE = E->getResumeExpr();
4060b57cec5SDimitry Andric   // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
4070b57cec5SDimitry Andric   // a MemberCallExpr?
4080b57cec5SDimitry Andric   assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
4090b57cec5SDimitry Andric   return cast<CallExpr>(RE)->getCallReturnType(Ctx);
4100b57cec5SDimitry Andric }
4110b57cec5SDimitry Andric #endif
4120b57cec5SDimitry Andric 
413*0fca6ea1SDimitry Andric llvm::Function *
414*0fca6ea1SDimitry Andric CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,
415*0fca6ea1SDimitry Andric                                              Twine const &SuspendPointName,
416*0fca6ea1SDimitry Andric                                              CoroutineSuspendExpr const &S) {
417*0fca6ea1SDimitry Andric   std::string FuncName =
418*0fca6ea1SDimitry Andric       (CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
419*0fca6ea1SDimitry Andric 
420*0fca6ea1SDimitry Andric   ASTContext &C = getContext();
421*0fca6ea1SDimitry Andric 
422*0fca6ea1SDimitry Andric   FunctionArgList args;
423*0fca6ea1SDimitry Andric 
424*0fca6ea1SDimitry Andric   ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
425*0fca6ea1SDimitry Andric   ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
426*0fca6ea1SDimitry Andric   QualType ReturnTy = S.getSuspendExpr()->getType();
427*0fca6ea1SDimitry Andric 
428*0fca6ea1SDimitry Andric   args.push_back(&AwaiterDecl);
429*0fca6ea1SDimitry Andric   args.push_back(&FrameDecl);
430*0fca6ea1SDimitry Andric 
431*0fca6ea1SDimitry Andric   const CGFunctionInfo &FI =
432*0fca6ea1SDimitry Andric       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
433*0fca6ea1SDimitry Andric 
434*0fca6ea1SDimitry Andric   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
435*0fca6ea1SDimitry Andric 
436*0fca6ea1SDimitry Andric   llvm::Function *Fn = llvm::Function::Create(
437*0fca6ea1SDimitry Andric       LTy, llvm::GlobalValue::PrivateLinkage, FuncName, &CGM.getModule());
438*0fca6ea1SDimitry Andric 
439*0fca6ea1SDimitry Andric   Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
440*0fca6ea1SDimitry Andric   Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
441*0fca6ea1SDimitry Andric 
442*0fca6ea1SDimitry Andric   Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
443*0fca6ea1SDimitry Andric 
444*0fca6ea1SDimitry Andric   Fn->setMustProgress();
445*0fca6ea1SDimitry Andric   Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
446*0fca6ea1SDimitry Andric 
447*0fca6ea1SDimitry Andric   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
448*0fca6ea1SDimitry Andric 
449*0fca6ea1SDimitry Andric   // FIXME: add TBAA metadata to the loads
450*0fca6ea1SDimitry Andric   llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(&AwaiterDecl));
451*0fca6ea1SDimitry Andric   auto AwaiterLValue =
452*0fca6ea1SDimitry Andric       MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl.getType());
453*0fca6ea1SDimitry Andric 
454*0fca6ea1SDimitry Andric   CurAwaitSuspendWrapper.FramePtr =
455*0fca6ea1SDimitry Andric       Builder.CreateLoad(GetAddrOfLocalVar(&FrameDecl));
456*0fca6ea1SDimitry Andric 
457*0fca6ea1SDimitry Andric   auto AwaiterBinder = CodeGenFunction::OpaqueValueMappingData::bind(
458*0fca6ea1SDimitry Andric       *this, S.getOpaqueValue(), AwaiterLValue);
459*0fca6ea1SDimitry Andric 
460*0fca6ea1SDimitry Andric   auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());
461*0fca6ea1SDimitry Andric 
462*0fca6ea1SDimitry Andric   auto UnbindCommonOnExit =
463*0fca6ea1SDimitry Andric       llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });
464*0fca6ea1SDimitry Andric   if (SuspendRet != nullptr) {
465*0fca6ea1SDimitry Andric     Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
466*0fca6ea1SDimitry Andric     Builder.CreateStore(SuspendRet, ReturnValue);
467*0fca6ea1SDimitry Andric   }
468*0fca6ea1SDimitry Andric 
469*0fca6ea1SDimitry Andric   CurAwaitSuspendWrapper.FramePtr = nullptr;
470*0fca6ea1SDimitry Andric   FinishFunction();
471*0fca6ea1SDimitry Andric   return Fn;
472*0fca6ea1SDimitry Andric }
473*0fca6ea1SDimitry Andric 
4740b57cec5SDimitry Andric LValue
4750b57cec5SDimitry Andric CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
4760b57cec5SDimitry Andric   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
4770b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
4780b57cec5SDimitry Andric          "reference type!");
4790b57cec5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, *E,
4800b57cec5SDimitry Andric                                CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
4810b57cec5SDimitry Andric                                /*ignoreResult*/false, /*forLValue*/true).LV;
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric LValue
4850b57cec5SDimitry Andric CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
4860b57cec5SDimitry Andric   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
4870b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
4880b57cec5SDimitry Andric          "reference type!");
4890b57cec5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, *E,
4900b57cec5SDimitry Andric                                AwaitKind::Yield, AggValueSlot::ignored(),
4910b57cec5SDimitry Andric                                /*ignoreResult*/false, /*forLValue*/true).LV;
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric // Hunts for the parameter reference in the parameter copy/move declaration.
4950b57cec5SDimitry Andric namespace {
4960b57cec5SDimitry Andric struct GetParamRef : public StmtVisitor<GetParamRef> {
4970b57cec5SDimitry Andric public:
4980b57cec5SDimitry Andric   DeclRefExpr *Expr = nullptr;
4990b57cec5SDimitry Andric   GetParamRef() {}
5000b57cec5SDimitry Andric   void VisitDeclRefExpr(DeclRefExpr *E) {
5010b57cec5SDimitry Andric     assert(Expr == nullptr && "multilple declref in param move");
5020b57cec5SDimitry Andric     Expr = E;
5030b57cec5SDimitry Andric   }
5040b57cec5SDimitry Andric   void VisitStmt(Stmt *S) {
5050b57cec5SDimitry Andric     for (auto *C : S->children()) {
5060b57cec5SDimitry Andric       if (C)
5070b57cec5SDimitry Andric         Visit(C);
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric   }
5100b57cec5SDimitry Andric };
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric // This class replaces references to parameters to their copies by changing
5140b57cec5SDimitry Andric // the addresses in CGF.LocalDeclMap and restoring back the original values in
5150b57cec5SDimitry Andric // its destructor.
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric namespace {
5180b57cec5SDimitry Andric   struct ParamReferenceReplacerRAII {
5190b57cec5SDimitry Andric     CodeGenFunction::DeclMapTy SavedLocals;
5200b57cec5SDimitry Andric     CodeGenFunction::DeclMapTy& LocalDeclMap;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric     ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
5230b57cec5SDimitry Andric         : LocalDeclMap(LocalDeclMap) {}
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric     void addCopy(DeclStmt const *PM) {
5260b57cec5SDimitry Andric       // Figure out what param it refers to.
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric       assert(PM->isSingleDecl());
5290b57cec5SDimitry Andric       VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
5300b57cec5SDimitry Andric       Expr const *InitExpr = VD->getInit();
5310b57cec5SDimitry Andric       GetParamRef Visitor;
5320b57cec5SDimitry Andric       Visitor.Visit(const_cast<Expr*>(InitExpr));
5330b57cec5SDimitry Andric       assert(Visitor.Expr);
5340b57cec5SDimitry Andric       DeclRefExpr *DREOrig = Visitor.Expr;
5350b57cec5SDimitry Andric       auto *PD = DREOrig->getDecl();
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric       auto it = LocalDeclMap.find(PD);
5380b57cec5SDimitry Andric       assert(it != LocalDeclMap.end() && "parameter is not found");
5390b57cec5SDimitry Andric       SavedLocals.insert({ PD, it->second });
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric       auto copyIt = LocalDeclMap.find(VD);
5420b57cec5SDimitry Andric       assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
5430b57cec5SDimitry Andric       it->second = copyIt->getSecond();
5440b57cec5SDimitry Andric     }
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric     ~ParamReferenceReplacerRAII() {
5470b57cec5SDimitry Andric       for (auto&& SavedLocal : SavedLocals) {
5480b57cec5SDimitry Andric         LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
5490b57cec5SDimitry Andric       }
5500b57cec5SDimitry Andric     }
5510b57cec5SDimitry Andric   };
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric // For WinEH exception representation backend needs to know what funclet coro.end
5550b57cec5SDimitry Andric // belongs to. That information is passed in a funclet bundle.
5560b57cec5SDimitry Andric static SmallVector<llvm::OperandBundleDef, 1>
5570b57cec5SDimitry Andric getBundlesForCoroEnd(CodeGenFunction &CGF) {
5580b57cec5SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> BundleList;
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
5610b57cec5SDimitry Andric     BundleList.emplace_back("funclet", EHPad);
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   return BundleList;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric namespace {
5670b57cec5SDimitry Andric // We will insert coro.end to cut any of the destructors for objects that
5680b57cec5SDimitry Andric // do not need to be destroyed once the coroutine is resumed.
5690b57cec5SDimitry Andric // See llvm/docs/Coroutines.rst for more details about coro.end.
5700b57cec5SDimitry Andric struct CallCoroEnd final : public EHScopeStack::Cleanup {
5710b57cec5SDimitry Andric   void Emit(CodeGenFunction &CGF, Flags flags) override {
5720b57cec5SDimitry Andric     auto &CGM = CGF.CGM;
5730b57cec5SDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
5740b57cec5SDimitry Andric     llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
5750b57cec5SDimitry Andric     // See if we have a funclet bundle to associate coro.end with. (WinEH)
5760b57cec5SDimitry Andric     auto Bundles = getBundlesForCoroEnd(CGF);
5775f757f3fSDimitry Andric     auto *CoroEnd =
5785f757f3fSDimitry Andric       CGF.Builder.CreateCall(CoroEndFn,
5795f757f3fSDimitry Andric                              {NullPtr, CGF.Builder.getTrue(),
5805f757f3fSDimitry Andric                               llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
5815f757f3fSDimitry Andric                              Bundles);
5820b57cec5SDimitry Andric     if (Bundles.empty()) {
5830b57cec5SDimitry Andric       // Otherwise, (landingpad model), create a conditional branch that leads
5840b57cec5SDimitry Andric       // either to a cleanup block or a block with EH resume instruction.
5850b57cec5SDimitry Andric       auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
5860b57cec5SDimitry Andric       auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
5870b57cec5SDimitry Andric       CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
5880b57cec5SDimitry Andric       CGF.EmitBlock(CleanupContBB);
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric   }
5910b57cec5SDimitry Andric };
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric namespace {
5950b57cec5SDimitry Andric // Make sure to call coro.delete on scope exit.
5960b57cec5SDimitry Andric struct CallCoroDelete final : public EHScopeStack::Cleanup {
5970b57cec5SDimitry Andric   Stmt *Deallocate;
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   // Note: That deallocation will be emitted twice: once for a normal exit and
6020b57cec5SDimitry Andric   // once for exceptional exit. This usage is safe because Deallocate does not
6030b57cec5SDimitry Andric   // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
6040b57cec5SDimitry Andric   // builds a single call to a deallocation function which is safe to emit
6050b57cec5SDimitry Andric   // multiple times.
6060b57cec5SDimitry Andric   void Emit(CodeGenFunction &CGF, Flags) override {
6070b57cec5SDimitry Andric     // Remember the current point, as we are going to emit deallocation code
6080b57cec5SDimitry Andric     // first to get to coro.free instruction that is an argument to a delete
6090b57cec5SDimitry Andric     // call.
6100b57cec5SDimitry Andric     BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric     auto *FreeBB = CGF.createBasicBlock("coro.free");
6130b57cec5SDimitry Andric     CGF.EmitBlock(FreeBB);
6140b57cec5SDimitry Andric     CGF.EmitStmt(Deallocate);
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
6170b57cec5SDimitry Andric     CGF.EmitBlock(AfterFreeBB);
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric     // We should have captured coro.free from the emission of deallocate.
6200b57cec5SDimitry Andric     auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
6210b57cec5SDimitry Andric     if (!CoroFree) {
6220b57cec5SDimitry Andric       CGF.CGM.Error(Deallocate->getBeginLoc(),
6230b57cec5SDimitry Andric                     "Deallocation expressoin does not refer to coro.free");
6240b57cec5SDimitry Andric       return;
6250b57cec5SDimitry Andric     }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric     // Get back to the block we were originally and move coro.free there.
6280b57cec5SDimitry Andric     auto *InsertPt = SaveInsertBlock->getTerminator();
6290b57cec5SDimitry Andric     CoroFree->moveBefore(InsertPt);
6300b57cec5SDimitry Andric     CGF.Builder.SetInsertPoint(InsertPt);
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric     // Add if (auto *mem = coro.free) Deallocate;
6330b57cec5SDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
6340b57cec5SDimitry Andric     auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
6350b57cec5SDimitry Andric     CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric     // No longer need old terminator.
6380b57cec5SDimitry Andric     InsertPt->eraseFromParent();
6390b57cec5SDimitry Andric     CGF.Builder.SetInsertPoint(AfterFreeBB);
6400b57cec5SDimitry Andric   }
6410b57cec5SDimitry Andric   explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
6420b57cec5SDimitry Andric };
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric 
64506c3fb27SDimitry Andric namespace {
64606c3fb27SDimitry Andric struct GetReturnObjectManager {
64706c3fb27SDimitry Andric   CodeGenFunction &CGF;
64806c3fb27SDimitry Andric   CGBuilderTy &Builder;
64906c3fb27SDimitry Andric   const CoroutineBodyStmt &S;
65006c3fb27SDimitry Andric   // When true, performs RVO for the return object.
65106c3fb27SDimitry Andric   bool DirectEmit = false;
65206c3fb27SDimitry Andric 
65306c3fb27SDimitry Andric   Address GroActiveFlag;
65406c3fb27SDimitry Andric   CodeGenFunction::AutoVarEmission GroEmission;
65506c3fb27SDimitry Andric 
65606c3fb27SDimitry Andric   GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
65706c3fb27SDimitry Andric       : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
65806c3fb27SDimitry Andric         GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
65906c3fb27SDimitry Andric     // The call to get_­return_­object is sequenced before the call to
66006c3fb27SDimitry Andric     // initial_­suspend and is invoked at most once, but there are caveats
66106c3fb27SDimitry Andric     // regarding on whether the prvalue result object may be initialized
66206c3fb27SDimitry Andric     // directly/eager or delayed, depending on the types involved.
66306c3fb27SDimitry Andric     //
66406c3fb27SDimitry Andric     // More info at https://github.com/cplusplus/papers/issues/1414
66506c3fb27SDimitry Andric     //
66606c3fb27SDimitry Andric     // The general cases:
66706c3fb27SDimitry Andric     // 1. Same type of get_return_object and coroutine return type (direct
66806c3fb27SDimitry Andric     // emission):
66906c3fb27SDimitry Andric     //  - Constructed in the return slot.
67006c3fb27SDimitry Andric     // 2. Different types (delayed emission):
67106c3fb27SDimitry Andric     //  - Constructed temporary object prior to initial suspend initialized with
67206c3fb27SDimitry Andric     //  a call to get_return_object()
67306c3fb27SDimitry Andric     //  - When coroutine needs to to return to the caller and needs to construct
67406c3fb27SDimitry Andric     //  return value for the coroutine it is initialized with expiring value of
67506c3fb27SDimitry Andric     //  the temporary obtained above.
67606c3fb27SDimitry Andric     //
67706c3fb27SDimitry Andric     // Direct emission for void returning coroutines or GROs.
67806c3fb27SDimitry Andric     DirectEmit = [&]() {
67906c3fb27SDimitry Andric       auto *RVI = S.getReturnValueInit();
68006c3fb27SDimitry Andric       assert(RVI && "expected RVI");
68106c3fb27SDimitry Andric       auto GroType = RVI->getType();
68206c3fb27SDimitry Andric       return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
68306c3fb27SDimitry Andric     }();
68406c3fb27SDimitry Andric   }
68506c3fb27SDimitry Andric 
68606c3fb27SDimitry Andric   // The gro variable has to outlive coroutine frame and coroutine promise, but,
68706c3fb27SDimitry Andric   // it can only be initialized after coroutine promise was created, thus, we
68806c3fb27SDimitry Andric   // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
68906c3fb27SDimitry Andric   // cleanups. Later when coroutine promise is available we initialize the gro
69006c3fb27SDimitry Andric   // and sets the flag that the cleanup is now active.
69106c3fb27SDimitry Andric   void EmitGroAlloca() {
69206c3fb27SDimitry Andric     if (DirectEmit)
69306c3fb27SDimitry Andric       return;
69406c3fb27SDimitry Andric 
69506c3fb27SDimitry Andric     auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
69606c3fb27SDimitry Andric     if (!GroDeclStmt) {
69706c3fb27SDimitry Andric       // If get_return_object returns void, no need to do an alloca.
69806c3fb27SDimitry Andric       return;
69906c3fb27SDimitry Andric     }
70006c3fb27SDimitry Andric 
70106c3fb27SDimitry Andric     auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
70206c3fb27SDimitry Andric 
70306c3fb27SDimitry Andric     // Set GRO flag that it is not initialized yet
70406c3fb27SDimitry Andric     GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
70506c3fb27SDimitry Andric                                          "gro.active");
70606c3fb27SDimitry Andric     Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
70706c3fb27SDimitry Andric 
70806c3fb27SDimitry Andric     GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
7095f757f3fSDimitry Andric     auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
7105f757f3fSDimitry Andric         GroEmission.getOriginalAllocatedAddress().getPointer());
7115f757f3fSDimitry Andric     assert(GroAlloca && "expected alloca to be emitted");
7125f757f3fSDimitry Andric     GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
7135f757f3fSDimitry Andric                            llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
71406c3fb27SDimitry Andric 
71506c3fb27SDimitry Andric     // Remember the top of EHStack before emitting the cleanup.
71606c3fb27SDimitry Andric     auto old_top = CGF.EHStack.stable_begin();
71706c3fb27SDimitry Andric     CGF.EmitAutoVarCleanups(GroEmission);
71806c3fb27SDimitry Andric     auto top = CGF.EHStack.stable_begin();
71906c3fb27SDimitry Andric 
72006c3fb27SDimitry Andric     // Make the cleanup conditional on gro.active
72106c3fb27SDimitry Andric     for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
72206c3fb27SDimitry Andric          b++) {
72306c3fb27SDimitry Andric       if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
72406c3fb27SDimitry Andric         assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
72506c3fb27SDimitry Andric         Cleanup->setActiveFlag(GroActiveFlag);
72606c3fb27SDimitry Andric         Cleanup->setTestFlagInEHCleanup();
72706c3fb27SDimitry Andric         Cleanup->setTestFlagInNormalCleanup();
72806c3fb27SDimitry Andric       }
72906c3fb27SDimitry Andric     }
73006c3fb27SDimitry Andric   }
73106c3fb27SDimitry Andric 
73206c3fb27SDimitry Andric   void EmitGroInit() {
73306c3fb27SDimitry Andric     if (DirectEmit) {
73406c3fb27SDimitry Andric       // ReturnValue should be valid as long as the coroutine's return type
73506c3fb27SDimitry Andric       // is not void. The assertion could help us to reduce the check later.
73606c3fb27SDimitry Andric       assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
73706c3fb27SDimitry Andric       // Now we have the promise, initialize the GRO.
73806c3fb27SDimitry Andric       // We need to emit `get_return_object` first. According to:
73906c3fb27SDimitry Andric       // [dcl.fct.def.coroutine]p7
74006c3fb27SDimitry Andric       // The call to get_return_­object is sequenced before the call to
74106c3fb27SDimitry Andric       // initial_suspend and is invoked at most once.
74206c3fb27SDimitry Andric       //
74306c3fb27SDimitry Andric       // So we couldn't emit return value when we emit return statment,
74406c3fb27SDimitry Andric       // otherwise the call to get_return_object wouldn't be in front
74506c3fb27SDimitry Andric       // of initial_suspend.
74606c3fb27SDimitry Andric       if (CGF.ReturnValue.isValid()) {
74706c3fb27SDimitry Andric         CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,
74806c3fb27SDimitry Andric                              S.getReturnValue()->getType().getQualifiers(),
74906c3fb27SDimitry Andric                              /*IsInit*/ true);
75006c3fb27SDimitry Andric       }
75106c3fb27SDimitry Andric       return;
75206c3fb27SDimitry Andric     }
75306c3fb27SDimitry Andric 
75406c3fb27SDimitry Andric     if (!GroActiveFlag.isValid()) {
75506c3fb27SDimitry Andric       // No Gro variable was allocated. Simply emit the call to
75606c3fb27SDimitry Andric       // get_return_object.
75706c3fb27SDimitry Andric       CGF.EmitStmt(S.getResultDecl());
75806c3fb27SDimitry Andric       return;
75906c3fb27SDimitry Andric     }
76006c3fb27SDimitry Andric 
76106c3fb27SDimitry Andric     CGF.EmitAutoVarInit(GroEmission);
76206c3fb27SDimitry Andric     Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
76306c3fb27SDimitry Andric   }
76406c3fb27SDimitry Andric };
76506c3fb27SDimitry Andric } // namespace
76606c3fb27SDimitry Andric 
7670b57cec5SDimitry Andric static void emitBodyAndFallthrough(CodeGenFunction &CGF,
7680b57cec5SDimitry Andric                                    const CoroutineBodyStmt &S, Stmt *Body) {
7690b57cec5SDimitry Andric   CGF.EmitStmt(Body);
7700b57cec5SDimitry Andric   const bool CanFallthrough = CGF.Builder.GetInsertBlock();
7710b57cec5SDimitry Andric   if (CanFallthrough)
7720b57cec5SDimitry Andric     if (Stmt *OnFallthrough = S.getFallthroughHandler())
7730b57cec5SDimitry Andric       CGF.EmitStmt(OnFallthrough);
7740b57cec5SDimitry Andric }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
7775f757f3fSDimitry Andric   auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
7780b57cec5SDimitry Andric   auto &TI = CGM.getContext().getTargetInfo();
7790b57cec5SDimitry Andric   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   auto *EntryBB = Builder.GetInsertBlock();
7820b57cec5SDimitry Andric   auto *AllocBB = createBasicBlock("coro.alloc");
7830b57cec5SDimitry Andric   auto *InitBB = createBasicBlock("coro.init");
7840b57cec5SDimitry Andric   auto *FinalBB = createBasicBlock("coro.final");
7850b57cec5SDimitry Andric   auto *RetBB = createBasicBlock("coro.ret");
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric   auto *CoroId = Builder.CreateCall(
7880b57cec5SDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_id),
7890b57cec5SDimitry Andric       {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
7900b57cec5SDimitry Andric   createCoroData(*this, CurCoro, CoroId);
7910b57cec5SDimitry Andric   CurCoro.Data->SuspendBB = RetBB;
792fe6060f1SDimitry Andric   assert(ShouldEmitLifetimeMarkers &&
793fe6060f1SDimitry Andric          "Must emit lifetime intrinsics for coroutines");
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   // Backend is allowed to elide memory allocations, to help it, emit
7960b57cec5SDimitry Andric   // auto mem = coro.alloc() ? 0 : ... allocation code ...;
7970b57cec5SDimitry Andric   auto *CoroAlloc = Builder.CreateCall(
7980b57cec5SDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   EmitBlock(AllocBB);
8030b57cec5SDimitry Andric   auto *AllocateCall = EmitScalarExpr(S.getAllocate());
8040b57cec5SDimitry Andric   auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
8070b57cec5SDimitry Andric   if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
8080b57cec5SDimitry Andric     auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric     // See if allocation was successful.
8110b57cec5SDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
8120b57cec5SDimitry Andric     auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
81306c3fb27SDimitry Andric     // Expect the allocation to be successful.
81406c3fb27SDimitry Andric     emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
8150b57cec5SDimitry Andric     Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric     // If not, return OnAllocFailure object.
8180b57cec5SDimitry Andric     EmitBlock(RetOnFailureBB);
8190b57cec5SDimitry Andric     EmitStmt(RetOnAllocFailure);
8200b57cec5SDimitry Andric   }
8210b57cec5SDimitry Andric   else {
8220b57cec5SDimitry Andric     Builder.CreateBr(InitBB);
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   EmitBlock(InitBB);
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // Pass the result of the allocation to coro.begin.
8280b57cec5SDimitry Andric   auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
8290b57cec5SDimitry Andric   Phi->addIncoming(NullPtr, EntryBB);
8300b57cec5SDimitry Andric   Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
8310b57cec5SDimitry Andric   auto *CoroBegin = Builder.CreateCall(
8320b57cec5SDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
8330b57cec5SDimitry Andric   CurCoro.Data->CoroBegin = CoroBegin;
8340b57cec5SDimitry Andric 
83506c3fb27SDimitry Andric   GetReturnObjectManager GroManager(*this, S);
83606c3fb27SDimitry Andric   GroManager.EmitGroAlloca();
83706c3fb27SDimitry Andric 
8380b57cec5SDimitry Andric   CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
8390b57cec5SDimitry Andric   {
840fe6060f1SDimitry Andric     CGDebugInfo *DI = getDebugInfo();
8410b57cec5SDimitry Andric     ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
8420b57cec5SDimitry Andric     CodeGenFunction::RunCleanupsScope ResumeScope(*this);
8430b57cec5SDimitry Andric     EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
8440b57cec5SDimitry Andric 
845fe6060f1SDimitry Andric     // Create mapping between parameters and copy-params for coroutine function.
846bdd1243dSDimitry Andric     llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
847fe6060f1SDimitry Andric     assert(
848fe6060f1SDimitry Andric         (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
849fe6060f1SDimitry Andric         "ParamMoves and FnArgs should be the same size for coroutine function");
850fe6060f1SDimitry Andric     if (ParamMoves.size() == FnArgs.size() && DI)
851fe6060f1SDimitry Andric       for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
852fe6060f1SDimitry Andric         DI->getCoroutineParameterMappings().insert(
853fe6060f1SDimitry Andric             {std::get<0>(Pair), std::get<1>(Pair)});
854fe6060f1SDimitry Andric 
8550b57cec5SDimitry Andric     // Create parameter copies. We do it before creating a promise, since an
8560b57cec5SDimitry Andric     // evolution of coroutine TS may allow promise constructor to observe
8570b57cec5SDimitry Andric     // parameter copies.
8580b57cec5SDimitry Andric     for (auto *PM : S.getParamMoves()) {
8590b57cec5SDimitry Andric       EmitStmt(PM);
8600b57cec5SDimitry Andric       ParamReplacer.addCopy(cast<DeclStmt>(PM));
8610b57cec5SDimitry Andric       // TODO: if(CoroParam(...)) need to surround ctor and dtor
8620b57cec5SDimitry Andric       // for the copy, so that llvm can elide it if the copy is
8630b57cec5SDimitry Andric       // not needed.
8640b57cec5SDimitry Andric     }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric     EmitStmt(S.getPromiseDeclStmt());
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric     Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
869*0fca6ea1SDimitry Andric     auto *PromiseAddrVoidPtr = new llvm::BitCastInst(
870*0fca6ea1SDimitry Andric         PromiseAddr.emitRawPointer(*this), VoidPtrTy, "", CoroId);
8710b57cec5SDimitry Andric     // Update CoroId to refer to the promise. We could not do it earlier because
8720b57cec5SDimitry Andric     // promise local variable was not emitted yet.
8730b57cec5SDimitry Andric     CoroId->setArgOperand(1, PromiseAddrVoidPtr);
8740b57cec5SDimitry Andric 
87506c3fb27SDimitry Andric     // Now we have the promise, initialize the GRO
87606c3fb27SDimitry Andric     GroManager.EmitGroInit();
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric     EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric     CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
8810b57cec5SDimitry Andric     CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
8820b57cec5SDimitry Andric     EmitStmt(S.getInitSuspendStmt());
8830b57cec5SDimitry Andric     CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric     CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric     if (CurCoro.Data->ExceptionHandler) {
8880b57cec5SDimitry Andric       // If we generated IR to record whether an exception was thrown from
8890b57cec5SDimitry Andric       // 'await_resume', then use that IR to determine whether the coroutine
8900b57cec5SDimitry Andric       // body should be skipped.
8910b57cec5SDimitry Andric       // If we didn't generate the IR (perhaps because 'await_resume' was marked
8920b57cec5SDimitry Andric       // as 'noexcept'), then we skip this check.
8930b57cec5SDimitry Andric       BasicBlock *ContBB = nullptr;
8940b57cec5SDimitry Andric       if (CurCoro.Data->ResumeEHVar) {
8950b57cec5SDimitry Andric         BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
8960b57cec5SDimitry Andric         ContBB = createBasicBlock("coro.resumed.cont");
8970b57cec5SDimitry Andric         Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
8980b57cec5SDimitry Andric                                                  "coro.resumed.eh");
8990b57cec5SDimitry Andric         Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
9000b57cec5SDimitry Andric         EmitBlock(BodyBB);
9010b57cec5SDimitry Andric       }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric       auto Loc = S.getBeginLoc();
9040b57cec5SDimitry Andric       CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
9050b57cec5SDimitry Andric                          CurCoro.Data->ExceptionHandler);
9060b57cec5SDimitry Andric       auto *TryStmt =
9070b57cec5SDimitry Andric           CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric       EnterCXXTryStmt(*TryStmt);
9100b57cec5SDimitry Andric       emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
9110b57cec5SDimitry Andric       ExitCXXTryStmt(*TryStmt);
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric       if (ContBB)
9140b57cec5SDimitry Andric         EmitBlock(ContBB);
9150b57cec5SDimitry Andric     }
9160b57cec5SDimitry Andric     else {
9170b57cec5SDimitry Andric       emitBodyAndFallthrough(*this, S, S.getBody());
9180b57cec5SDimitry Andric     }
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric     // See if we need to generate final suspend.
9210b57cec5SDimitry Andric     const bool CanFallthrough = Builder.GetInsertBlock();
9220b57cec5SDimitry Andric     const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
9230b57cec5SDimitry Andric     if (CanFallthrough || HasCoreturns) {
9240b57cec5SDimitry Andric       EmitBlock(FinalBB);
9250b57cec5SDimitry Andric       CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
9260b57cec5SDimitry Andric       EmitStmt(S.getFinalSuspendStmt());
9270b57cec5SDimitry Andric     } else {
9280b57cec5SDimitry Andric       // We don't need FinalBB. Emit it to make sure the block is deleted.
9290b57cec5SDimitry Andric       EmitBlock(FinalBB, /*IsFinished=*/true);
9300b57cec5SDimitry Andric     }
9310b57cec5SDimitry Andric   }
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric   EmitBlock(RetBB);
9340b57cec5SDimitry Andric   // Emit coro.end before getReturnStmt (and parameter destructors), since
9350b57cec5SDimitry Andric   // resume and destroy parts of the coroutine should not include them.
9360b57cec5SDimitry Andric   llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
9375f757f3fSDimitry Andric   Builder.CreateCall(CoroEnd,
9385f757f3fSDimitry Andric                      {NullPtr, Builder.getFalse(),
9395f757f3fSDimitry Andric                       llvm::ConstantTokenNone::get(CoroEnd->getContext())});
9400b57cec5SDimitry Andric 
94181ad6265SDimitry Andric   if (Stmt *Ret = S.getReturnStmt()) {
94281ad6265SDimitry Andric     // Since we already emitted the return value above, so we shouldn't
94381ad6265SDimitry Andric     // emit it again here.
94406c3fb27SDimitry Andric     if (GroManager.DirectEmit)
94581ad6265SDimitry Andric       cast<ReturnStmt>(Ret)->setRetValue(nullptr);
9460b57cec5SDimitry Andric     EmitStmt(Ret);
94781ad6265SDimitry Andric   }
94804eeddc0SDimitry Andric 
94981ad6265SDimitry Andric   // LLVM require the frontend to mark the coroutine.
95081ad6265SDimitry Andric   CurFn->setPresplitCoroutine();
9515f757f3fSDimitry Andric 
9525f757f3fSDimitry Andric   if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
9535f757f3fSDimitry Andric       RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
9545f757f3fSDimitry Andric     CurFn->setCoroDestroyOnlyWhenComplete();
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric // Emit coroutine intrinsic and patch up arguments of the token type.
9580b57cec5SDimitry Andric RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
9590b57cec5SDimitry Andric                                                unsigned int IID) {
9600b57cec5SDimitry Andric   SmallVector<llvm::Value *, 8> Args;
9610b57cec5SDimitry Andric   switch (IID) {
9620b57cec5SDimitry Andric   default:
9630b57cec5SDimitry Andric     break;
9640b57cec5SDimitry Andric   // The coro.frame builtin is replaced with an SSA value of the coro.begin
9650b57cec5SDimitry Andric   // intrinsic.
9660b57cec5SDimitry Andric   case llvm::Intrinsic::coro_frame: {
9670b57cec5SDimitry Andric     if (CurCoro.Data && CurCoro.Data->CoroBegin) {
9680b57cec5SDimitry Andric       return RValue::get(CurCoro.Data->CoroBegin);
9690b57cec5SDimitry Andric     }
970*0fca6ea1SDimitry Andric 
971*0fca6ea1SDimitry Andric     if (CurAwaitSuspendWrapper.FramePtr) {
972*0fca6ea1SDimitry Andric       return RValue::get(CurAwaitSuspendWrapper.FramePtr);
973*0fca6ea1SDimitry Andric     }
974*0fca6ea1SDimitry Andric 
9750b57cec5SDimitry Andric     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
9760b57cec5SDimitry Andric                                 "has been used earlier in this function");
9775f757f3fSDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
9780b57cec5SDimitry Andric     return RValue::get(NullPtr);
9790b57cec5SDimitry Andric   }
980bdd1243dSDimitry Andric   case llvm::Intrinsic::coro_size: {
981bdd1243dSDimitry Andric     auto &Context = getContext();
982bdd1243dSDimitry Andric     CanQualType SizeTy = Context.getSizeType();
983bdd1243dSDimitry Andric     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
984bdd1243dSDimitry Andric     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
985bdd1243dSDimitry Andric     return RValue::get(Builder.CreateCall(F));
986bdd1243dSDimitry Andric   }
987bdd1243dSDimitry Andric   case llvm::Intrinsic::coro_align: {
988bdd1243dSDimitry Andric     auto &Context = getContext();
989bdd1243dSDimitry Andric     CanQualType SizeTy = Context.getSizeType();
990bdd1243dSDimitry Andric     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
991bdd1243dSDimitry Andric     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
992bdd1243dSDimitry Andric     return RValue::get(Builder.CreateCall(F));
993bdd1243dSDimitry Andric   }
9940b57cec5SDimitry Andric   // The following three intrinsics take a token parameter referring to a token
9950b57cec5SDimitry Andric   // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
9960b57cec5SDimitry Andric   // builtins, we patch it up here.
9970b57cec5SDimitry Andric   case llvm::Intrinsic::coro_alloc:
9980b57cec5SDimitry Andric   case llvm::Intrinsic::coro_begin:
9990b57cec5SDimitry Andric   case llvm::Intrinsic::coro_free: {
10000b57cec5SDimitry Andric     if (CurCoro.Data && CurCoro.Data->CoroId) {
10010b57cec5SDimitry Andric       Args.push_back(CurCoro.Data->CoroId);
10020b57cec5SDimitry Andric       break;
10030b57cec5SDimitry Andric     }
10040b57cec5SDimitry Andric     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
10050b57cec5SDimitry Andric                                 " been used earlier in this function");
10060b57cec5SDimitry Andric     // Fallthrough to the next case to add TokenNone as the first argument.
1007bdd1243dSDimitry Andric     [[fallthrough]];
10080b57cec5SDimitry Andric   }
10090b57cec5SDimitry Andric   // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
10100b57cec5SDimitry Andric   // argument.
10110b57cec5SDimitry Andric   case llvm::Intrinsic::coro_suspend:
10120b57cec5SDimitry Andric     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
10130b57cec5SDimitry Andric     break;
10140b57cec5SDimitry Andric   }
10150b57cec5SDimitry Andric   for (const Expr *Arg : E->arguments())
10160b57cec5SDimitry Andric     Args.push_back(EmitScalarExpr(Arg));
10175f757f3fSDimitry Andric   // @llvm.coro.end takes a token parameter. Add token 'none' as the last
10185f757f3fSDimitry Andric   // argument.
10195f757f3fSDimitry Andric   if (IID == llvm::Intrinsic::coro_end)
10205f757f3fSDimitry Andric     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(IID);
10230b57cec5SDimitry Andric   llvm::CallInst *Call = Builder.CreateCall(F, Args);
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   // Note: The following code is to enable to emit coro.id and coro.begin by
10260b57cec5SDimitry Andric   // hand to experiment with coroutines in C.
10270b57cec5SDimitry Andric   // If we see @llvm.coro.id remember it in the CoroData. We will update
10280b57cec5SDimitry Andric   // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
10290b57cec5SDimitry Andric   if (IID == llvm::Intrinsic::coro_id) {
10300b57cec5SDimitry Andric     createCoroData(*this, CurCoro, Call, E);
10310b57cec5SDimitry Andric   }
10320b57cec5SDimitry Andric   else if (IID == llvm::Intrinsic::coro_begin) {
10330b57cec5SDimitry Andric     if (CurCoro.Data)
10340b57cec5SDimitry Andric       CurCoro.Data->CoroBegin = Call;
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric   else if (IID == llvm::Intrinsic::coro_free) {
10370b57cec5SDimitry Andric     // Remember the last coro_free as we need it to build the conditional
10380b57cec5SDimitry Andric     // deletion of the coroutine frame.
10390b57cec5SDimitry Andric     if (CurCoro.Data)
10400b57cec5SDimitry Andric       CurCoro.Data->LastCoroFree = Call;
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric   return RValue::get(Call);
10430b57cec5SDimitry Andric }
1044